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.MacEntryKey;
167 import org.opendaylight.yangtools.yang.binding.DataObject;
168 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
169 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.InstanceIdentifierBuilder;
170 import org.opendaylight.yangtools.yang.common.RpcResult;
171 import org.slf4j.Logger;
172 import org.slf4j.LoggerFactory;
175 public class ElanUtils {
177 private static final Logger LOG = LoggerFactory.getLogger(ElanUtils.class);
179 private static Map<String, ElanInterface> elanInterfaceLocalCache = new ConcurrentHashMap<>();
180 private static Map<String, Set<DpnInterfaces>> elanInstancToDpnsCache = new ConcurrentHashMap<>();
181 private static Map<String, Set<String>> elanInstanceToInterfacesCache = new ConcurrentHashMap<>();
183 private final DataBroker broker;
184 private final IMdsalApiManager mdsalManager;
185 private final OdlInterfaceRpcService interfaceManagerRpcService;
186 private final ItmRpcService itmRpcService;
187 private final IInterfaceManager interfaceManager;
188 private final ElanConfig elanConfig;
189 private final ElanItmUtils elanItmUtils;
190 private final ElanEtreeUtils elanEtreeUtils;
192 public static final FutureCallback<Void> DEFAULT_CALLBACK = new FutureCallback<Void>() {
194 public void onSuccess(Void result) {
195 LOG.debug("Success in Datastore operation");
199 public void onFailure(Throwable error) {
200 LOG.error("Error in Datastore operation", error);
205 public ElanUtils(DataBroker dataBroker, IMdsalApiManager mdsalManager,
206 OdlInterfaceRpcService interfaceManagerRpcService, ItmRpcService itmRpcService, ElanConfig elanConfig,
207 IInterfaceManager interfaceManager, ElanEtreeUtils elanEtreeUtils, ElanItmUtils elanItmUtils) {
208 this.broker = dataBroker;
209 this.mdsalManager = mdsalManager;
210 this.interfaceManagerRpcService = interfaceManagerRpcService;
211 this.itmRpcService = itmRpcService;
212 this.interfaceManager = interfaceManager;
213 this.elanConfig = elanConfig;
214 this.elanEtreeUtils = elanEtreeUtils;
215 this.elanItmUtils = elanItmUtils;
218 public final Boolean isOpenstackVniSemanticsEnforced() {
219 return elanConfig.isOpenstackVniSemanticsEnforced() != null
220 ? elanConfig.isOpenstackVniSemanticsEnforced() : false;
223 public static void addElanInterfaceIntoCache(String interfaceName, ElanInterface elanInterface) {
224 elanInterfaceLocalCache.put(interfaceName, elanInterface);
227 public static void removeElanInterfaceFromCache(String interfaceName) {
228 elanInterfaceLocalCache.remove(interfaceName);
231 public static ElanInterface getElanInterfaceFromCache(String interfaceName) {
232 return elanInterfaceLocalCache.get(interfaceName);
236 * Uses the IdManager to retrieve a brand new ElanTag.
242 * @return the integer
244 public static Long retrieveNewElanTag(IdManagerService idManager, String idKey) {
246 AllocateIdInput getIdInput = new AllocateIdInputBuilder().setPoolName(ElanConstants.ELAN_ID_POOL_NAME)
247 .setIdKey(idKey).build();
250 Future<RpcResult<AllocateIdOutput>> result = idManager.allocateId(getIdInput);
251 RpcResult<AllocateIdOutput> rpcResult = result.get();
252 if (rpcResult.isSuccessful()) {
253 return rpcResult.getResult().getIdValue();
255 LOG.warn("RPC Call to Allocate Id returned with Errors {}", rpcResult.getErrors());
257 } catch (InterruptedException | ExecutionException e) {
258 LOG.warn("Exception when Allocating Id", e);
263 public static void releaseId(IdManagerService idManager, String poolName, String idKey) {
264 ReleaseIdInput releaseIdInput = new ReleaseIdInputBuilder().setPoolName(poolName).setIdKey(idKey).build();
265 JdkFutures.addErrorLogging(idManager.releaseId(releaseIdInput), LOG, "Release Id");
271 * @deprecated Consider using {@link #read2(LogicalDatastoreType, InstanceIdentifier)} with proper exception
273 * @param broker dataBroker
274 * @param datastoreType Logical DataStore type
275 * @param path IID to read
276 * @param <T> T extends DataObject
277 * @return the read value T
280 @SuppressWarnings("checkstyle:IllegalCatch")
281 public static <T extends DataObject> Optional<T> read(@Nonnull DataBroker broker,
282 LogicalDatastoreType datastoreType, InstanceIdentifier<T> path) {
283 try (ReadOnlyTransaction tx = broker.newReadOnlyTransaction()) {
284 return tx.read(datastoreType, path).get();
285 } catch (Exception e) {
286 throw new RuntimeException(e);
290 public <T extends DataObject> Optional<T> read2(LogicalDatastoreType datastoreType, InstanceIdentifier<T> path)
291 throws ReadFailedException {
292 try (ReadOnlyTransaction tx = broker.newReadOnlyTransaction()) {
293 CheckedFuture<Optional<T>, ReadFailedException> checkedFuture = tx.read(datastoreType, path);
294 return checkedFuture.checkedGet();
298 public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
299 InstanceIdentifier<T> path) {
300 WriteTransaction tx = broker.newWriteOnlyTransaction();
301 tx.delete(datastoreType, path);
302 Futures.addCallback(tx.submit(), DEFAULT_CALLBACK, MoreExecutors.directExecutor());
305 public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
306 InstanceIdentifier<T> path, FutureCallback<Void> callback) {
307 WriteTransaction tx = broker.newWriteOnlyTransaction();
308 tx.delete(datastoreType, path);
309 Futures.addCallback(tx.submit(), callback, MoreExecutors.directExecutor());
312 public static InstanceIdentifier<ElanInstance> getElanInstanceIdentifier() {
313 return InstanceIdentifier.builder(ElanInstances.class).child(ElanInstance.class).build();
316 // elan-interfaces Config Container
317 public static ElanInterface getElanInterfaceByElanInterfaceName(DataBroker broker, String elanInterfaceName) {
318 ElanInterface elanInterfaceObj = getElanInterfaceFromCache(elanInterfaceName);
319 if (elanInterfaceObj != null) {
320 return elanInterfaceObj;
322 InstanceIdentifier<ElanInterface> elanInterfaceId = getElanInterfaceConfigurationDataPathId(elanInterfaceName);
323 return MDSALUtil.read(broker, LogicalDatastoreType.CONFIGURATION, elanInterfaceId).orNull();
326 public static EtreeInterface getEtreeInterfaceByElanInterfaceName(DataBroker broker, String elanInterfaceName) {
327 ElanInterface elanInterface = getElanInterfaceByElanInterfaceName(broker, elanInterfaceName);
328 if (elanInterface == null) {
331 return elanInterface.getAugmentation(EtreeInterface.class);
335 public static InstanceIdentifier<ElanInterface> getElanInterfaceConfigurationDataPathId(String interfaceName) {
336 return InstanceIdentifier.builder(ElanInterfaces.class)
337 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).build();
340 // elan-state Operational container
341 public static Elan getElanByName(DataBroker broker, String elanInstanceName) {
342 InstanceIdentifier<Elan> elanIdentifier = getElanInstanceOperationalDataPath(elanInstanceName);
343 return MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL, elanIdentifier).orNull();
346 public static InstanceIdentifier<Elan> getElanInstanceOperationalDataPath(String elanInstanceName) {
347 return InstanceIdentifier.builder(ElanState.class).child(Elan.class, new ElanKey(elanInstanceName)).build();
350 // grouping of forwarding-entries
351 public MacEntry getInterfaceMacEntriesOperationalDataPath(String interfaceName, PhysAddress physAddress) {
352 InstanceIdentifier<MacEntry> existingMacEntryId = getInterfaceMacEntriesIdentifierOperationalDataPath(
353 interfaceName, physAddress);
354 return read(broker, LogicalDatastoreType.OPERATIONAL, existingMacEntryId).orNull();
357 public MacEntry getInterfaceMacEntriesOperationalDataPathFromId(InstanceIdentifier identifier) {
358 Optional<MacEntry> existingInterfaceMacEntry = read(broker,
359 LogicalDatastoreType.OPERATIONAL, identifier);
360 return existingInterfaceMacEntry.orNull();
363 public static InstanceIdentifier<MacEntry> getInterfaceMacEntriesIdentifierOperationalDataPath(String interfaceName,
364 PhysAddress physAddress) {
365 return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class)
366 .child(ElanInterfaceMac.class, new ElanInterfaceMacKey(interfaceName))
367 .child(MacEntry.class, new MacEntryKey(physAddress)).build();
371 // elan-forwarding-tables Operational container
372 public Optional<MacEntry> getMacEntryForElanInstance(String elanName, PhysAddress physAddress) {
373 InstanceIdentifier<MacEntry> macId = getMacEntryOperationalDataPath(elanName, physAddress);
374 return read(broker, LogicalDatastoreType.OPERATIONAL, macId);
377 public MacEntry getMacEntryFromElanMacId(InstanceIdentifier identifier) {
378 Optional<MacEntry> existingInterfaceMacEntry = read(broker,
379 LogicalDatastoreType.OPERATIONAL, identifier);
380 return existingInterfaceMacEntry.orNull();
383 public static InstanceIdentifier<MacEntry> getMacEntryOperationalDataPath(String elanName,
384 PhysAddress physAddress) {
385 return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class, new MacTableKey(elanName))
386 .child(MacEntry.class, new MacEntryKey(physAddress)).build();
389 public static InstanceIdentifier<MacTable> getElanMacTableOperationalDataPath(String elanName) {
390 return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class, new MacTableKey(elanName))
394 // elan-interface-forwarding-entries Operational container
395 public ElanInterfaceMac getElanInterfaceMacByInterfaceName(String interfaceName) {
396 return getElanInterfaceMacByInterfaceName(broker, interfaceName);
400 public static ElanInterfaceMac getElanInterfaceMacByInterfaceName(DataBroker dataBroker, String interfaceName) {
401 InstanceIdentifier<ElanInterfaceMac> elanInterfaceId = getElanInterfaceMacEntriesOperationalDataPath(
403 return read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanInterfaceId).orNull();
407 * Gets the elan interface mac addresses.
409 * @param interfaceName
411 * @return the elan interface mac addresses
413 public List<PhysAddress> getElanInterfaceMacAddresses(String interfaceName) {
414 List<PhysAddress> macAddresses = new ArrayList<>();
415 ElanInterfaceMac elanInterfaceMac = getElanInterfaceMacByInterfaceName(interfaceName);
416 if (elanInterfaceMac != null && elanInterfaceMac.getMacEntry() != null) {
417 List<MacEntry> macEntries = elanInterfaceMac.getMacEntry();
418 for (MacEntry macEntry : macEntries) {
419 macAddresses.add(macEntry.getMacAddress());
425 public static InstanceIdentifier<ElanInterfaceMac> getElanInterfaceMacEntriesOperationalDataPath(
426 String interfaceName) {
427 return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class)
428 .child(ElanInterfaceMac.class, new ElanInterfaceMacKey(interfaceName)).build();
432 * Returns the list of Interfaces that belong to an Elan on an specific DPN.
433 * Data retrieved from Elan's operational DS: elan-dpn-interfaces container
435 * @param elanInstanceName
436 * name of the Elan to which the interfaces must belong to
438 * Id of the DPN where the interfaces are located
439 * @return the elan interface Info
441 public DpnInterfaces getElanInterfaceInfoByElanDpn(String elanInstanceName, BigInteger dpId) {
442 InstanceIdentifier<DpnInterfaces> elanDpnInterfacesId = getElanDpnInterfaceOperationalDataPath(elanInstanceName,
444 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfacesId).orNull();
448 * Returns the InstanceIdentifier that points to the Interfaces of an Elan
449 * in a given DPN in the Operational DS. Data retrieved from Elans's
450 * operational DS: dpn-interfaces list
452 * @param elanInstanceName
453 * name of the Elan to which the interfaces must belong to
455 * Id of the DPN where the interfaces are located
456 * @return the elan dpn interface
458 public static InstanceIdentifier<DpnInterfaces> getElanDpnInterfaceOperationalDataPath(String elanInstanceName,
460 return InstanceIdentifier.builder(ElanDpnInterfaces.class)
461 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName))
462 .child(DpnInterfaces.class, new DpnInterfacesKey(dpId)).build();
465 // elan-tag-name-map Operational Container
466 public ElanTagName getElanInfoByElanTag(long elanTag) {
467 InstanceIdentifier<ElanTagName> elanId = getElanInfoEntriesOperationalDataPath(elanTag);
468 Optional<ElanTagName> existingElanInfo = read(broker,
469 LogicalDatastoreType.OPERATIONAL, elanId);
470 return existingElanInfo.orNull();
473 public static InstanceIdentifier<ElanTagName> getElanInfoEntriesOperationalDataPath(long elanTag) {
474 return InstanceIdentifier.builder(ElanTagNameMap.class).child(ElanTagName.class, new ElanTagNameKey(elanTag))
478 // interface-index-tag operational container
479 public Optional<IfIndexInterface> getInterfaceInfoByInterfaceTag(long interfaceTag) {
480 InstanceIdentifier<IfIndexInterface> interfaceId = getInterfaceInfoEntriesOperationalDataPath(interfaceTag);
481 return read(broker, LogicalDatastoreType.OPERATIONAL, interfaceId);
484 public static InstanceIdentifier<IfIndexInterface> getInterfaceInfoEntriesOperationalDataPath(long interfaceTag) {
485 return InstanceIdentifier.builder(IfIndexesInterfaceMap.class)
486 .child(IfIndexInterface.class, new IfIndexInterfaceKey((int) interfaceTag)).build();
489 public static InstanceIdentifier<ElanDpnInterfacesList> getElanDpnOperationDataPath(String elanInstanceName) {
490 return InstanceIdentifier.builder(ElanDpnInterfaces.class)
491 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName)).build();
494 public ElanDpnInterfacesList getElanDpnInterfacesList(String elanName) {
495 InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanName);
496 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orNull();
499 public ElanDpnInterfaces getElanDpnInterfacesList() {
500 InstanceIdentifier<ElanDpnInterfaces> elanDpnInterfaceId = InstanceIdentifier.builder(ElanDpnInterfaces.class)
502 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orNull();
506 * This method is useful get all ELAN participating CSS dpIds to install
507 * program remote dmac entries and updating remote bc groups for tor
510 * @param elanInstanceName
511 * the elan instance name
512 * @return list of dpIds
515 public List<BigInteger> getParticipatingDpnsInElanInstance(String elanInstanceName) {
516 List<BigInteger> dpIds = new ArrayList<>();
517 InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
518 Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = read(broker,
519 LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
520 if (!existingElanDpnInterfaces.isPresent()) {
523 List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().getDpnInterfaces();
524 for (DpnInterfaces dpnInterface : dpnInterfaces) {
525 dpIds.add(dpnInterface.getDpId());
531 * To check given dpId is already present in Elan instance. This can be used
532 * to program flow entry in external tunnel table when a new access port
533 * added for first time into the ELAN instance
537 * @param elanInstanceName
538 * the elan instance name
539 * @return true if dpId is already present, otherwise return false
541 public boolean isDpnAlreadyPresentInElanInstance(BigInteger dpId, String elanInstanceName) {
542 InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
543 Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = read(broker,
544 LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
545 if (!existingElanDpnInterfaces.isPresent()) {
548 List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().getDpnInterfaces();
549 for (DpnInterfaces dpnInterface : dpnInterfaces) {
550 if (dpnInterface.getDpId().equals(dpId)) {
557 public ElanForwardingTables getElanForwardingList() {
558 InstanceIdentifier<ElanForwardingTables> elanForwardingTableId = InstanceIdentifier
559 .builder(ElanForwardingTables.class).build();
560 return read(broker, LogicalDatastoreType.OPERATIONAL, elanForwardingTableId).orNull();
563 public static long getElanRemoteBroadCastGroupID(long elanTag) {
564 return ElanConstants.ELAN_GID_MIN + elanTag % ElanConstants.ELAN_GID_MIN * 2;
568 * Gets the elan mac table.
572 * @return the elan mac table
574 public MacTable getElanMacTable(String elanName) {
575 return getElanMacTable(broker, elanName);
579 public static MacTable getElanMacTable(DataBroker dataBroker, String elanName) {
580 InstanceIdentifier<MacTable> elanMacTableId = getElanMacTableOperationalDataPath(elanName);
581 return read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanMacTableId).orNull();
584 public static long getElanLocalBCGId(long elanTag) {
585 return ElanConstants.ELAN_GID_MIN + (elanTag % ElanConstants.ELAN_GID_MIN * 2 - 1);
588 public static long getElanRemoteBCGId(long elanTag) {
589 return ElanConstants.ELAN_GID_MIN + elanTag % ElanConstants.ELAN_GID_MIN * 2;
592 public static long getEtreeLeafLocalBCGId(long etreeLeafTag) {
593 return ElanConstants.ELAN_GID_MIN + (etreeLeafTag % ElanConstants.ELAN_GID_MIN * 2 - 1);
596 public static long getEtreeLeafRemoteBCGId(long etreeLeafTag) {
597 return ElanConstants.ELAN_GID_MIN + etreeLeafTag % ElanConstants.ELAN_GID_MIN * 2;
600 public static BigInteger getElanMetadataLabel(long elanTag, boolean isSHFlagSet) {
601 int shBit = isSHFlagSet ? 1 : 0;
602 return BigInteger.valueOf(elanTag).shiftLeft(24).or(BigInteger.valueOf(shBit));
606 * Setting SMAC, DMAC, UDMAC in this DPN and optionally in other DPNs.
610 * @param interfaceInfo
616 * @param configureRemoteFlows
617 * true if remote dmac flows should be configured as well
618 * @param writeFlowGroupTx
620 * @throws ElanException in case of issues creating the flow objects
622 public void setupMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo,
623 long macTimeout, String macAddress, boolean configureRemoteFlows,
624 WriteTransaction writeFlowGroupTx) throws ElanException {
625 synchronized (getElanMacDPNKey(elanInfo.getElanTag(), macAddress, interfaceInfo.getDpId())) {
626 setupKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress, mdsalManager,
628 setupOrigDmacFlows(elanInfo, interfaceInfo, macAddress, configureRemoteFlows, mdsalManager,
633 public void setupDMacFlowOnRemoteDpn(ElanInstance elanInfo, InterfaceInfo interfaceInfo, BigInteger dstDpId,
634 String macAddress, WriteTransaction writeFlowTx) throws ElanException {
635 String elanInstanceName = elanInfo.getElanInstanceName();
636 setupRemoteDmacFlow(dstDpId, interfaceInfo.getDpId(), interfaceInfo.getInterfaceTag(), elanInfo.getElanTag(),
637 macAddress, elanInstanceName, writeFlowTx, interfaceInfo.getInterfaceName(), elanInfo);
638 LOG.info("Remote Dmac flow entry created for elan Name:{}, logical port Name:{} and"
639 + " mac address {} on dpn:{}", elanInstanceName, interfaceInfo.getPortName(),
640 macAddress, dstDpId);
644 * Inserts a Flow in SMAC table to state that the MAC has already been
647 private void setupKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
648 String macAddress, IMdsalApiManager mdsalApiManager, WriteTransaction writeFlowGroupTx) {
649 FlowEntity flowEntity = buildKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress);
650 mdsalApiManager.addFlowToTx(flowEntity, writeFlowGroupTx);
651 LOG.debug("Known Smac flow entry created for elan Name:{}, logical Interface port:{} and mac address:{}",
652 elanInfo.getElanInstanceName(), elanInfo.getDescription(), macAddress);
655 public FlowEntity buildKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
657 int lportTag = interfaceInfo.getInterfaceTag();
658 // Matching metadata and eth_src fields
659 List<MatchInfo> mkMatches = new ArrayList<>();
660 mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanInfo.getElanTag(), lportTag),
661 ElanHelper.getElanMetadataMask()));
662 mkMatches.add(new MatchEthernetSource(new MacAddress(macAddress)));
663 List<InstructionInfo> mkInstructions = new ArrayList<>();
664 mkInstructions.add(new InstructionGotoTable(NwConstants.ELAN_DMAC_TABLE));
665 BigInteger dpId = interfaceInfo.getDpId();
666 long elanTag = getElanTag(broker, elanInfo, interfaceInfo);
667 return new FlowEntityBuilder()
669 .setTableId(NwConstants.ELAN_SMAC_TABLE)
670 .setFlowId(getKnownDynamicmacFlowRef(NwConstants.ELAN_SMAC_TABLE, dpId, lportTag, macAddress, elanTag))
672 .setFlowName(elanInfo.getDescription())
673 .setIdleTimeOut((int) macTimeout)
675 .setCookie(ElanConstants.COOKIE_ELAN_KNOWN_SMAC.add(BigInteger.valueOf(elanTag)))
676 .setMatchInfoList(mkMatches)
677 .setInstructionInfoList(mkInstructions)
679 // If Mac timeout is 0, the flow won't be deleted automatically, so no need to get notified
680 .setSendFlowRemFlag(macTimeout != 0)
684 private static Long getElanTag(DataBroker broker, ElanInstance elanInfo, InterfaceInfo interfaceInfo) {
685 EtreeInterface etreeInterface = getEtreeInterfaceByElanInterfaceName(broker, interfaceInfo.getInterfaceName());
686 if (etreeInterface == null || etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
687 return elanInfo.getElanTag();
689 EtreeInstance etreeInstance = elanInfo.getAugmentation(EtreeInstance.class);
690 if (etreeInstance == null) {
691 LOG.warn("EtreeInterface {} is connected to a non-Etree network: {}",
692 interfaceInfo.getInterfaceName(), elanInfo.getElanInstanceName());
693 return elanInfo.getElanTag();
695 return etreeInstance.getEtreeLeafTagVal().getValue();
701 * Installs a Flow in INTERNAL_TUNNEL_TABLE of the affected DPN that sends
702 * the packet through the specified interface if the tunnel_id matches the
703 * interface's lportTag.
705 * @param interfaceInfo
707 * @param mdsalApiManager
708 * the mdsal API manager
709 * @param writeFlowGroupTx
710 * the writeFLowGroup tx
712 public void setupTermDmacFlows(InterfaceInfo interfaceInfo, IMdsalApiManager mdsalApiManager,
713 WriteTransaction writeFlowGroupTx) {
714 BigInteger dpId = interfaceInfo.getDpId();
715 int lportTag = interfaceInfo.getInterfaceTag();
716 Flow flow = MDSALUtil.buildFlowNew(NwConstants.INTERNAL_TUNNEL_TABLE,
717 getIntTunnelTableFlowRef(NwConstants.INTERNAL_TUNNEL_TABLE, lportTag), 5,
718 String.format("%s:%d", "ITM Flow Entry ", lportTag), 0, 0,
719 ITMConstants.COOKIE_ITM.add(BigInteger.valueOf(lportTag)),
720 getTunnelIdMatchForFilterEqualsLPortTag(lportTag),
721 getInstructionsInPortForOutGroup(interfaceInfo.getInterfaceName()));
722 mdsalApiManager.addFlowToTx(dpId, flow, writeFlowGroupTx);
723 LOG.debug("Terminating service table flow entry created on dpn:{} for logical Interface port:{}", dpId,
724 interfaceInfo.getPortName());
728 * Constructs the FlowName for flows installed in the Internal Tunnel Table,
729 * consisting in tableId + elanTag.
735 * @return the Internal tunnel
737 public static String getIntTunnelTableFlowRef(short tableId, int elanTag) {
738 return new StringBuffer().append(tableId).append(elanTag).toString();
742 * Constructs the Matches that checks that the tunnel_id field contains a
746 * lportTag that must be checked against the tunnel_id field
747 * @return the list of match Info
749 public static List<MatchInfo> getTunnelIdMatchForFilterEqualsLPortTag(int lportTag) {
750 List<MatchInfo> mkMatches = new ArrayList<>();
752 mkMatches.add(new MatchTunnelId(BigInteger.valueOf(lportTag)));
757 * Constructs the Instructions that take the packet over a given interface.
760 * Name of the interface where the packet must be sent over. It
761 * can be a local interface or a tunnel interface (internal or
763 * @return the Instruction
765 public List<Instruction> getInstructionsInPortForOutGroup(String ifName) {
766 List<Instruction> mkInstructions = new ArrayList<>();
767 List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
769 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
770 return mkInstructions;
774 * Returns the list of Actions to be taken when sending the packet through
775 * an Elan interface. Note that this interface can refer to an ElanInterface
776 * where the Elan VM is attached to a DPN or an ITM tunnel interface where
777 * Elan traffic can be sent through. In this latter case, the tunnelKey is
778 * mandatory and it can hold serviceId for internal tunnels or the VNI for
785 * @return the egress actions for interface
787 @SuppressWarnings("checkstyle:IllegalCatch")
788 public List<Action> getEgressActionsForInterface(String ifName, Long tunnelKey) {
789 List<Action> listAction = new ArrayList<>();
791 GetEgressActionsForInterfaceInput getEgressActionInput = new GetEgressActionsForInterfaceInputBuilder()
792 .setIntfName(ifName).setTunnelKey(tunnelKey).build();
793 Future<RpcResult<GetEgressActionsForInterfaceOutput>> result = interfaceManagerRpcService
794 .getEgressActionsForInterface(getEgressActionInput);
795 RpcResult<GetEgressActionsForInterfaceOutput> rpcResult = result.get();
796 if (!rpcResult.isSuccessful()) {
797 LOG.debug("RPC Call to Get egress actions for interface {} returned with Errors {}", ifName,
798 rpcResult.getErrors());
800 List<Action> actions = rpcResult.getResult().getAction();
801 listAction = actions;
803 } catch (Exception e) {
804 LOG.warn("Exception when egress actions for interface {}", ifName, e);
809 private void setupOrigDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
810 boolean configureRemoteFlows, IMdsalApiManager mdsalApiManager,
811 WriteTransaction writeFlowGroupTx)
812 throws ElanException {
813 BigInteger dpId = interfaceInfo.getDpId();
814 String ifName = interfaceInfo.getInterfaceName();
815 long ifTag = interfaceInfo.getInterfaceTag();
816 String elanInstanceName = elanInfo.getElanInstanceName();
818 Long elanTag = elanInfo.getElanTag();
820 setupLocalDmacFlow(elanTag, dpId, ifName, macAddress, elanInfo, mdsalApiManager, ifTag,
822 LOG.debug("Dmac flow entry created for elan Name:{}, logical port Name:{} mand mac address:{} "
823 + "on dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, dpId);
825 if (!configureRemoteFlows) {
829 List<DpnInterfaces> elanDpns = getInvolvedDpnsInElan(elanInstanceName);
830 for (DpnInterfaces elanDpn : elanDpns) {
832 if (elanDpn.getDpId().equals(dpId)) {
836 // Check for the Remote DPN present in Inventory Manager
837 if (!isDpnPresent(elanDpn.getDpId())) {
841 // For remote DPNs a flow is needed to indicate that packets of this ELAN going to this MAC need to be
842 // forwarded through the appropriate ITM tunnel
843 setupRemoteDmacFlow(elanDpn.getDpId(), // srcDpn (the remote DPN in this case)
844 dpId, // dstDpn (the local DPN)
845 interfaceInfo.getInterfaceTag(), // lportTag of the local interface
846 elanTag, // identifier of the Elan
847 macAddress, // MAC to be programmed in remote DPN
848 elanInstanceName, writeFlowGroupTx, ifName, elanInfo
850 LOG.debug("Remote Dmac flow entry created for elan Name:{}, logical port Name:{} and mac address:{} on"
851 + " dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, elanDpn.getDpId());
854 // TODO: Make sure that the same is performed against the ElanDevices.
858 public List<DpnInterfaces> getInvolvedDpnsInElan(String elanName) {
859 return getElanDPNByName(elanName);
863 public List<DpnInterfaces> getElanDPNByName(String elanInstanceName) {
864 InstanceIdentifier<ElanDpnInterfacesList> elanIdentifier = getElanDpnOperationDataPath(elanInstanceName);
865 return MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL, elanIdentifier).toJavaUtil().map(
866 ElanDpnInterfacesList::getDpnInterfaces).orElse(Collections.emptyList());
869 private void setupLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
870 ElanInstance elanInfo, IMdsalApiManager mdsalApiManager, long ifTag, WriteTransaction writeFlowGroupTx) {
871 Flow flowEntity = buildLocalDmacFlowEntry(elanTag, dpId, ifName, macAddress, elanInfo, ifTag);
872 mdsalApiManager.addFlowToTx(dpId, flowEntity, writeFlowGroupTx);
873 installEtreeLocalDmacFlow(elanTag, dpId, ifName, macAddress, elanInfo,
874 mdsalApiManager, ifTag, writeFlowGroupTx);
877 private void installEtreeLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
878 ElanInstance elanInfo, IMdsalApiManager mdsalApiManager, long ifTag, WriteTransaction writeFlowGroupTx) {
879 EtreeInterface etreeInterface = getEtreeInterfaceByElanInterfaceName(broker, ifName);
880 if (etreeInterface != null) {
881 if (etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
882 EtreeLeafTagName etreeTagName = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
883 if (etreeTagName == null) {
884 LOG.warn("Interface {} seems like it belongs to Etree but etreeTagName from elanTag {} is null",
887 Flow flowEntity = buildLocalDmacFlowEntry(etreeTagName.getEtreeLeafTag().getValue(), dpId, ifName,
888 macAddress, elanInfo, ifTag);
889 mdsalApiManager.addFlowToTx(dpId, flowEntity, writeFlowGroupTx);
895 public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, long lporTag, String macAddress,
897 return new StringBuffer().append(tableId).append(elanTag).append(dpId).append(lporTag).append(macAddress)
901 public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, BigInteger remoteDpId,
902 String macAddress, long elanTag) {
903 return new StringBuffer().append(tableId).append(elanTag).append(dpId).append(remoteDpId).append(macAddress)
907 public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, String macAddress, long elanTag) {
908 return new StringBuffer().append(tableId).append(elanTag).append(dpId).append(macAddress).toString();
911 public static String getKnownDynamicmacFlowRef(short elanDmacTable, BigInteger dpId, String extDeviceNodeId,
912 String dstMacAddress, long elanTag, boolean shFlag) {
913 return new StringBuffer().append(elanDmacTable).append(elanTag).append(dpId).append(extDeviceNodeId)
914 .append(dstMacAddress).append(shFlag).toString();
918 * Builds the flow to be programmed in the DMAC table of the local DPN (that
919 * is, where the MAC is attached to). This flow consists in:
921 * <p>Match: + elanTag in metadata + packet goes to a MAC locally attached
922 * Actions: + optionally, pop-vlan + set-vlan-id + output to ifName's
939 public Flow buildLocalDmacFlowEntry(long elanTag, BigInteger dpId, String ifName, String macAddress,
940 ElanInstance elanInfo, long ifTag) {
942 List<MatchInfo> mkMatches = new ArrayList<>();
943 mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
944 mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddress)));
946 List<Instruction> mkInstructions = new ArrayList<>();
947 List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
948 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
949 Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
950 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, ifTag, macAddress, elanTag), 20,
951 elanInfo.getElanInstanceName(), 0, 0, ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(
952 BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
957 public void setupRemoteDmacFlow(BigInteger srcDpId, BigInteger destDpId, int lportTag, long elanTag, String
958 macAddress, String displayName, WriteTransaction writeFlowGroupTx, String interfaceName, ElanInstance
959 elanInstance) throws ElanException {
960 if (interfaceManager.isExternalInterface(interfaceName)) {
961 LOG.debug("Ignoring install remote DMAC {} flow on provider interface {} elan {}",
962 macAddress, interfaceName, elanInstance.getElanInstanceName());
966 // if openstack-vni-semantics are enforced, segmentation ID is passed as network VNI for VxLAN based provider
967 // networks, 0 otherwise
968 long lportTagOrVni = !isOpenstackVniSemanticsEnforced() ? lportTag : isVxlan(elanInstance)
969 ? elanInstance.getSegmentationId() : 0;
970 flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTagOrVni, elanTag, macAddress, displayName,
972 mdsalManager.addFlowToTx(srcDpId, flowEntity, writeFlowGroupTx);
973 setupEtreeRemoteDmacFlow(srcDpId, destDpId, lportTagOrVni, elanTag, macAddress, displayName, interfaceName,
974 writeFlowGroupTx, elanInstance);
977 private void setupEtreeRemoteDmacFlow(BigInteger srcDpId, BigInteger destDpId, long lportTagOrVni, long elanTag,
978 String macAddress, String displayName, String interfaceName,
979 WriteTransaction writeFlowGroupTx, ElanInstance elanInstance)
980 throws ElanException {
982 EtreeInterface etreeInterface = getEtreeInterfaceByElanInterfaceName(broker, interfaceName);
983 if (etreeInterface != null) {
984 if (etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
985 EtreeLeafTagName etreeTagName = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
986 if (etreeTagName == null) {
987 LOG.warn("Interface " + interfaceName
988 + " seems like it belongs to Etree but etreeTagName from elanTag " + elanTag + " is null.");
990 flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTagOrVni,
991 etreeTagName.getEtreeLeafTag().getValue(), macAddress, displayName, elanInstance);
992 mdsalManager.addFlowToTx(srcDpId, flowEntity, writeFlowGroupTx);
999 * Builds a Flow to be programmed in a remote DPN's DMAC table. This flow
1000 * consists in: Match: + elanTag in packet's metadata + packet going to a
1001 * MAC known to be located in another DPN Actions: + set_tunnel_id
1002 * + output ITM internal tunnel interface with the other DPN
1008 * @param lportTagOrVni
1009 * lportTag or network VNI
1014 * @param displayName
1016 * @param elanInstance
1018 * @return the flow remote Dmac
1019 * @throws ElanException in case of issues creating the flow objects
1021 @SuppressWarnings("checkstyle:IllegalCatch")
1022 public Flow buildRemoteDmacFlowEntry(BigInteger srcDpId, BigInteger destDpId, long lportTagOrVni, long elanTag,
1023 String macAddress, String displayName, ElanInstance elanInstance) throws ElanException {
1024 List<MatchInfo> mkMatches = new ArrayList<>();
1025 mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
1026 mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddress)));
1028 List<Instruction> mkInstructions = new ArrayList<>();
1030 // List of Action for the provided Source and Destination DPIDs
1032 List<Action> actions = null;
1033 if (isVlan(elanInstance) || isFlat(elanInstance)) {
1034 String interfaceName = getExternalElanInterface(elanInstance.getElanInstanceName(), srcDpId);
1035 if (null == interfaceName) {
1036 LOG.info("buildRemoteDmacFlowEntry: Could not find interfaceName for {} {}", srcDpId,
1039 actions = getEgressActionsForInterface(interfaceName, null);
1040 } else if (isVxlan(elanInstance)) {
1041 actions = elanItmUtils.getInternalTunnelItmEgressAction(srcDpId, destDpId, lportTagOrVni);
1043 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
1044 } catch (Exception e) {
1045 LOG.error("Could not get egress actions to add to flow for srcDpId=" + srcDpId + ", destDpId=" + destDpId
1046 + ", lportTag/VNI=" + lportTagOrVni, e);
1049 Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
1050 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, srcDpId, destDpId, macAddress, elanTag),
1052 displayName, 0, /* idleTimeout */
1053 0, /* hardTimeout */
1054 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
1060 public void deleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, MacEntry macEntry,
1061 WriteTransaction deleteFlowGroupTx) {
1062 if (elanInfo == null || interfaceInfo == null) {
1065 String macAddress = macEntry.getMacAddress().getValue();
1066 synchronized (getElanMacDPNKey(elanInfo.getElanTag(), macAddress, interfaceInfo.getDpId())) {
1067 deleteMacFlows(elanInfo, interfaceInfo, macAddress, /* alsoDeleteSMAC */ true, deleteFlowGroupTx);
1071 public void deleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1072 boolean deleteSmac, WriteTransaction deleteFlowGroupTx) {
1073 String elanInstanceName = elanInfo.getElanInstanceName();
1074 List<DpnInterfaces> remoteFEs = getInvolvedDpnsInElan(elanInstanceName);
1075 BigInteger srcdpId = interfaceInfo.getDpId();
1076 boolean isFlowsRemovedInSrcDpn = false;
1077 for (DpnInterfaces dpnInterface : remoteFEs) {
1078 Long elanTag = elanInfo.getElanTag();
1079 BigInteger dstDpId = dpnInterface.getDpId();
1080 if (executeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1081 elanTag, dstDpId, deleteFlowGroupTx)) {
1082 isFlowsRemovedInSrcDpn = true;
1084 executeEtreeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1085 elanTag, dstDpId, deleteFlowGroupTx);
1087 if (!isFlowsRemovedInSrcDpn) {
1088 deleteSmacAndDmacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, deleteFlowGroupTx);
1092 private void executeEtreeDeleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1093 boolean deleteSmac, String elanInstanceName, BigInteger srcdpId, Long elanTag, BigInteger dstDpId,
1094 WriteTransaction deleteFlowGroupTx) {
1095 EtreeLeafTagName etreeLeafTag = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
1096 if (etreeLeafTag != null) {
1097 executeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1098 etreeLeafTag.getEtreeLeafTag().getValue(), dstDpId, deleteFlowGroupTx);
1102 private boolean executeDeleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1103 boolean deleteSmac, String elanInstanceName, BigInteger srcdpId, Long elanTag, BigInteger dstDpId,
1104 WriteTransaction deleteFlowGroupTx) {
1105 boolean isFlowsRemovedInSrcDpn = false;
1106 if (dstDpId.equals(srcdpId)) {
1107 isFlowsRemovedInSrcDpn = true;
1108 deleteSmacAndDmacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, deleteFlowGroupTx);
1109 } else if (isDpnPresent(dstDpId)) {
1111 .removeFlowToTx(dstDpId,
1112 MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, getKnownDynamicmacFlowRef(
1113 NwConstants.ELAN_DMAC_TABLE, dstDpId, srcdpId, macAddress, elanTag)),
1115 LOG.debug("Dmac flow entry deleted for elan:{}, logical interface port:{} and mac address:{} on dpn:{}",
1116 elanInstanceName, interfaceInfo.getPortName(), macAddress, dstDpId);
1118 return isFlowsRemovedInSrcDpn;
1121 private void deleteSmacAndDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1122 boolean deleteSmac, WriteTransaction deleteFlowGroupTx) {
1123 String elanInstanceName = elanInfo.getElanInstanceName();
1124 long ifTag = interfaceInfo.getInterfaceTag();
1125 BigInteger srcdpId = interfaceInfo.getDpId();
1126 Long elanTag = elanInfo.getElanTag();
1129 .removeFlowToTx(srcdpId,
1130 MDSALUtil.buildFlow(NwConstants.ELAN_SMAC_TABLE, getKnownDynamicmacFlowRef(
1131 NwConstants.ELAN_SMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)),
1134 mdsalManager.removeFlowToTx(srcdpId,
1135 MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE,
1136 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)),
1138 LOG.debug("All the required flows deleted for elan:{}, logical Interface port:{} and MAC address:{} on dpn:{}",
1139 elanInstanceName, interfaceInfo.getPortName(), macAddress, srcdpId);
1143 * Updates the Elan information in the Operational DS. It also updates the
1144 * ElanInstance in the Config DS by setting the adquired elanTag.
1150 * @param elanInstanceAdded
1151 * the elan instance added
1152 * @param elanInterfaces
1153 * the elan interfaces
1157 * @return the updated ELAN instance.
1159 public static ElanInstance updateOperationalDataStore(DataBroker broker, IdManagerService idManager,
1160 ElanInstance elanInstanceAdded, List<String> elanInterfaces, WriteTransaction tx) {
1161 String elanInstanceName = elanInstanceAdded.getElanInstanceName();
1162 Long elanTag = elanInstanceAdded.getElanTag();
1163 if (elanTag == null || elanTag == 0L) {
1164 elanTag = retrieveNewElanTag(idManager, elanInstanceName);
1166 Elan elanInfo = new ElanBuilder().setName(elanInstanceName).setElanInterfaces(elanInterfaces)
1167 .setKey(new ElanKey(elanInstanceName)).build();
1169 // Add the ElanState in the elan-state operational data-store
1170 tx.put(LogicalDatastoreType.OPERATIONAL, getElanInstanceOperationalDataPath(elanInstanceName),
1171 elanInfo, WriteTransaction.CREATE_MISSING_PARENTS);
1173 // Add the ElanMacTable in the elan-mac-table operational data-store
1174 MacTable elanMacTable = new MacTableBuilder().setKey(new MacTableKey(elanInstanceName)).build();
1175 tx.put(LogicalDatastoreType.OPERATIONAL, getElanMacTableOperationalDataPath(elanInstanceName),
1176 elanMacTable, WriteTransaction.CREATE_MISSING_PARENTS);
1178 ElanTagNameBuilder elanTagNameBuilder = new ElanTagNameBuilder().setElanTag(elanTag)
1179 .setKey(new ElanTagNameKey(elanTag)).setName(elanInstanceName);
1180 long etreeLeafTag = -1;
1181 if (isEtreeInstance(elanInstanceAdded)) {
1182 etreeLeafTag = retrieveNewElanTag(idManager,elanInstanceName + ElanConstants
1184 EtreeLeafTagName etreeLeafTagName = new EtreeLeafTagNameBuilder()
1185 .setEtreeLeafTag(new EtreeLeafTag(etreeLeafTag)).build();
1186 elanTagNameBuilder.addAugmentation(EtreeLeafTagName.class, etreeLeafTagName);
1187 addTheLeafTagAsElanTag(broker, elanInstanceName, etreeLeafTag, tx);
1189 ElanTagName elanTagName = elanTagNameBuilder.build();
1191 // Add the ElanTag to ElanName in the elan-tag-name Operational
1193 tx.put(LogicalDatastoreType.OPERATIONAL,
1194 getElanInfoEntriesOperationalDataPath(elanTag), elanTagName);
1196 // Updates the ElanInstance Config DS by setting the just acquired
1198 ElanInstanceBuilder elanInstanceBuilder = new ElanInstanceBuilder().setElanInstanceName(elanInstanceName)
1199 .setDescription(elanInstanceAdded.getDescription())
1200 .setMacTimeout(elanInstanceAdded.getMacTimeout() == null
1201 ? Long.valueOf(ElanConstants.DEFAULT_MAC_TIME_OUT) : elanInstanceAdded.getMacTimeout())
1202 .setKey(elanInstanceAdded.getKey()).setElanTag(elanTag);
1203 if (isEtreeInstance(elanInstanceAdded)) {
1204 EtreeInstance etreeInstance = new EtreeInstanceBuilder().setEtreeLeafTagVal(new EtreeLeafTag(etreeLeafTag))
1206 elanInstanceBuilder.addAugmentation(EtreeInstance.class, etreeInstance);
1208 ElanInstance elanInstanceWithTag = elanInstanceBuilder.build();
1209 tx.merge(LogicalDatastoreType.CONFIGURATION, ElanHelper.getElanInstanceConfigurationDataPath(elanInstanceName),
1210 elanInstanceWithTag, WriteTransaction.CREATE_MISSING_PARENTS);
1211 return elanInstanceWithTag;
1214 private static void addTheLeafTagAsElanTag(DataBroker broker, String elanInstanceName, long etreeLeafTag,
1215 WriteTransaction tx) {
1216 ElanTagName etreeTagAsElanTag = new ElanTagNameBuilder().setElanTag(etreeLeafTag)
1217 .setKey(new ElanTagNameKey(etreeLeafTag)).setName(elanInstanceName).build();
1218 tx.put(LogicalDatastoreType.OPERATIONAL,
1219 getElanInfoEntriesOperationalDataPath(etreeLeafTag), etreeTagAsElanTag);
1222 private static boolean isEtreeInstance(ElanInstance elanInstanceAdded) {
1223 return elanInstanceAdded.getAugmentation(EtreeInstance.class) != null;
1226 public boolean isDpnPresent(BigInteger dpnId) {
1227 String dpn = String.format("%s:%s", "openflow", dpnId);
1228 NodeId nodeId = new NodeId(dpn);
1230 InstanceIdentifier<Node> node = InstanceIdentifier.builder(Nodes.class).child(Node.class, new NodeKey(nodeId))
1232 return read(broker, LogicalDatastoreType.CONFIGURATION, node).isPresent();
1235 public static ServicesInfo getServiceInfo(String elanInstanceName, String interfaceName) {
1236 return InterfaceServiceUtil.buildServiceInfo(elanInstanceName + "." + interfaceName,
1237 ElanConstants.ELAN_SERVICE_PRIORITY);
1240 public static String getElanServiceName(String elanName, String interfaceName) {
1241 return "elan." + elanName + interfaceName;
1244 public static BoundServices getBoundServices(String serviceName, short servicePriority, int flowPriority,
1245 BigInteger cookie, List<Instruction> instructions) {
1246 StypeOpenflowBuilder augBuilder = new StypeOpenflowBuilder().setFlowCookie(cookie).setFlowPriority(flowPriority)
1247 .setInstruction(instructions);
1248 return new BoundServicesBuilder().setKey(new BoundServicesKey(servicePriority)).setServiceName(serviceName)
1249 .setServicePriority(servicePriority).setServiceType(ServiceTypeFlowBased.class)
1250 .addAugmentation(StypeOpenflow.class, augBuilder.build()).build();
1253 public static InstanceIdentifier<BoundServices> buildServiceId(String interfaceName, short serviceIndex) {
1254 return InstanceIdentifier.builder(ServiceBindings.class)
1255 .child(ServicesInfo.class, new ServicesInfoKey(interfaceName, ServiceModeIngress.class))
1256 .child(BoundServices.class, new BoundServicesKey(serviceIndex)).build();
1259 public static List<MatchInfo> getTunnelMatchesForServiceId(int elanTag) {
1260 List<MatchInfo> mkMatches = new ArrayList<>();
1261 // Matching metadata
1262 mkMatches.add(new MatchTunnelId(BigInteger.valueOf(elanTag)));
1267 public void removeTerminatingServiceAction(BigInteger destDpId, int serviceId) {
1268 RemoveTerminatingServiceActionsInput input = new RemoveTerminatingServiceActionsInputBuilder()
1269 .setDpnId(destDpId).setServiceId(serviceId).build();
1270 Future<RpcResult<Void>> futureObject = itmRpcService.removeTerminatingServiceActions(input);
1272 RpcResult<Void> result = futureObject.get();
1273 if (result.isSuccessful()) {
1274 LOG.debug("Successfully completed removeTerminatingServiceActions for ELAN with serviceId {} on "
1275 + "dpn {}", serviceId, destDpId);
1277 LOG.debug("Failure in removeTerminatingServiceAction RPC call for ELAN with serviceId {} on "
1278 + "dpn {}", serviceId, destDpId);
1280 } catch (InterruptedException | ExecutionException e) {
1281 LOG.error("Error in RPC call removeTerminatingServiceActions for ELAN with serviceId {} on "
1282 + "dpn {}: {}", serviceId, destDpId, e);
1287 * Gets the external tunnel.
1289 * @param sourceDevice
1291 * @param destinationDevice
1292 * the destination device
1293 * @param datastoreType
1294 * the datastore type
1295 * @return the external tunnel
1297 public ExternalTunnel getExternalTunnel(String sourceDevice, String destinationDevice,
1298 LogicalDatastoreType datastoreType) {
1299 Class<? extends TunnelTypeBase> tunType = TunnelTypeVxlan.class;
1300 InstanceIdentifier<ExternalTunnel> iid = InstanceIdentifier.builder(ExternalTunnelList.class)
1301 .child(ExternalTunnel.class, new ExternalTunnelKey(destinationDevice, sourceDevice, tunType)).build();
1302 return read(broker, datastoreType, iid).orNull();
1306 * Gets the external tunnel.
1308 * @param interfaceName
1309 * the interface name
1310 * @param datastoreType
1311 * the datastore type
1312 * @return the external tunnel
1314 public ExternalTunnel getExternalTunnel(String interfaceName, LogicalDatastoreType datastoreType) {
1315 ExternalTunnel externalTunnel = null;
1316 List<ExternalTunnel> externalTunnels = getAllExternalTunnels(datastoreType);
1317 for (ExternalTunnel tunnel : externalTunnels) {
1318 if (StringUtils.equalsIgnoreCase(interfaceName, tunnel.getTunnelInterfaceName())) {
1319 externalTunnel = tunnel;
1323 return externalTunnel;
1327 * Gets the all external tunnels.
1329 * @param datastoreType
1330 * the data store type
1331 * @return the all external tunnels
1333 public List<ExternalTunnel> getAllExternalTunnels(LogicalDatastoreType datastoreType) {
1334 InstanceIdentifier<ExternalTunnelList> iid = InstanceIdentifier.builder(ExternalTunnelList.class).build();
1335 return read(broker, datastoreType, iid).toJavaUtil().map(ExternalTunnelList::getExternalTunnel).orElse(
1336 Collections.emptyList());
1339 public static List<MatchInfo> buildMatchesForElanTagShFlagAndDstMac(long elanTag, boolean shFlag, String macAddr) {
1340 List<MatchInfo> mkMatches = new ArrayList<>();
1342 new MatchMetadata(getElanMetadataLabel(elanTag, shFlag), MetaDataUtil.METADATA_MASK_SERVICE_SH_FLAG));
1343 mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddr)));
1348 * Checks if is interface operational.
1350 * @param interfaceName
1351 * the interface name
1354 * @return true, if is interface operational
1356 public static boolean isInterfaceOperational(String interfaceName, DataBroker dataBroker) {
1357 if (StringUtils.isBlank(interfaceName)) {
1360 Interface ifState = getInterfaceStateFromOperDS(interfaceName, dataBroker);
1361 if (ifState == null) {
1364 return ifState.getOperStatus() == OperStatus.Up && ifState.getAdminStatus() == AdminStatus.Up;
1368 * Gets the interface state from operational ds.
1370 * @param interfaceName
1371 * the interface name
1374 * @return the interface state from oper ds
1376 public static org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1377 .ietf.interfaces.rev140508.interfaces.state.Interface getInterfaceStateFromOperDS(
1378 String interfaceName, DataBroker dataBroker) {
1379 InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1380 .ietf.interfaces.rev140508.interfaces.state.Interface> ifStateId = createInterfaceStateInstanceIdentifier(
1382 return MDSALUtil.read(dataBroker, LogicalDatastoreType.OPERATIONAL, ifStateId).orNull();
1386 * Creates the interface state instance identifier.
1388 * @param interfaceName
1389 * the interface name
1390 * @return the instance identifier
1392 public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1393 .ietf.interfaces.rev140508.interfaces.state.Interface> createInterfaceStateInstanceIdentifier(
1394 String interfaceName) {
1395 InstanceIdentifierBuilder<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1396 .ietf.interfaces.rev140508.interfaces.state.Interface> idBuilder = InstanceIdentifier
1397 .builder(InterfacesState.class)
1398 .child(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1399 .ietf.interfaces.rev140508.interfaces.state.Interface.class,
1400 new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1401 .ietf.interfaces.rev140508.interfaces.state.InterfaceKey(
1403 return idBuilder.build();
1406 public static CheckedFuture<Void, TransactionCommitFailedException> waitForTransactionToComplete(
1407 WriteTransaction tx) {
1408 CheckedFuture<Void, TransactionCommitFailedException> futures = tx.submit();
1411 } catch (InterruptedException | ExecutionException e) {
1412 LOG.error("Error writing to datastore {}", e);
1417 public static boolean isVxlan(ElanInstance elanInstance) {
1418 return elanInstance != null && elanInstance.getSegmentType() != null
1419 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1420 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId() != 0;
1423 private static boolean isVxlanSegment(ElanInstance elanInstance) {
1424 if (elanInstance != null) {
1425 List<ElanSegments> elanSegments = elanInstance.getElanSegments();
1426 if (elanSegments != null) {
1427 for (ElanSegments segment : elanSegments) {
1428 if (segment != null && segment.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1429 && segment.getSegmentationId() != null
1430 && segment.getSegmentationId().longValue() != 0) {
1439 public static boolean isVxlanNetworkOrVxlanSegment(ElanInstance elanInstance) {
1440 return isVxlan(elanInstance) || isVxlanSegment(elanInstance);
1443 public static Long getVxlanSegmentationId(ElanInstance elanInstance) {
1444 Long segmentationId = 0L;
1445 if (elanInstance == null) {
1446 return segmentationId;
1449 if (elanInstance.getSegmentType() != null
1450 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1451 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId().longValue() != 0) {
1452 segmentationId = elanInstance.getSegmentationId();
1454 for (ElanSegments segment: elanInstance.getElanSegments()) {
1455 if (segment != null && segment.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1456 && segment.getSegmentationId() != null
1457 && segment.getSegmentationId().longValue() != 0) {
1458 segmentationId = segment.getSegmentationId();
1462 return segmentationId;
1465 public static boolean isVlan(ElanInstance elanInstance) {
1466 return elanInstance != null && elanInstance.getSegmentType() != null
1467 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVlan.class)
1468 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId() != 0;
1471 public static boolean isFlat(ElanInstance elanInstance) {
1472 return elanInstance != null && elanInstance.getSegmentType() != null
1473 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeFlat.class);
1476 public void addDmacRedirectToDispatcherFlows(Long elanTag, String displayName,
1477 String macAddress, List<BigInteger> dpnIds) {
1478 for (BigInteger dpId : dpnIds) {
1479 WriteTransaction writeTx = broker.newWriteOnlyTransaction();
1480 mdsalManager.addFlowToTx(buildDmacRedirectToDispatcherFlow(dpId, macAddress, displayName, elanTag),
1486 public void removeDmacRedirectToDispatcherFlows(Long elanTag, String macAddress, List<BigInteger> dpnIds) {
1487 for (BigInteger dpId : dpnIds) {
1488 String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, macAddress, elanTag);
1489 mdsalManager.removeFlow(dpId, MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, flowId));
1493 public static FlowEntity buildDmacRedirectToDispatcherFlow(BigInteger dpId, String dstMacAddress,
1494 String displayName, long elanTag) {
1495 List<MatchInfo> matches = new ArrayList<>();
1496 matches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
1497 matches.add(new MatchEthernetDestination(new MacAddress(dstMacAddress)));
1498 List<InstructionInfo> instructions = new ArrayList<>();
1499 List<ActionInfo> actions = new ArrayList<>();
1500 actions.add(new ActionNxResubmit(NwConstants.LPORT_DISPATCHER_TABLE));
1502 instructions.add(new InstructionApplyActions(actions));
1503 String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, dstMacAddress, elanTag);
1504 FlowEntity flow = MDSALUtil.buildFlowEntity(dpId, NwConstants.ELAN_DMAC_TABLE, flowId, 20, displayName, 0, 0,
1505 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)),
1506 matches, instructions);
1510 public String getExternalElanInterface(String elanInstanceName, BigInteger dpnId) {
1511 DpnInterfaces dpnInterfaces = getElanInterfaceInfoByElanDpn(elanInstanceName, dpnId);
1512 if (dpnInterfaces == null || dpnInterfaces.getInterfaces() == null) {
1513 LOG.trace("Elan {} does not have interfaces in DPN {}", elanInstanceName, dpnId);
1517 for (String dpnInterface : dpnInterfaces.getInterfaces()) {
1518 if (interfaceManager.isExternalInterface(dpnInterface)) {
1519 return dpnInterface;
1523 LOG.trace("Elan {} does not have any external interace attached to DPN {}", elanInstanceName, dpnId);
1527 public static String getElanMacDPNKey(long elanTag, String macAddress, BigInteger dpnId) {
1528 String elanMacDmacDpnKey = "MAC-" + macAddress + " ELAN_TAG-" + elanTag + "DPN_ID-" + dpnId;
1529 return elanMacDmacDpnKey.intern();
1532 public static String getElanMacKey(long elanTag, String macAddress) {
1533 String elanMacKey = "MAC-" + macAddress + " ELAN_TAG-" + elanTag;
1534 return elanMacKey.intern();
1537 // TODO This should return a collection of futures
1538 public static void addToListenableFutureIfTxException(RuntimeException exception,
1539 List<ListenableFuture<Void>> futures) {
1540 Throwable cause = exception.getCause();
1541 if (cause != null && cause instanceof TransactionCommitFailedException) {
1542 futures.add(Futures.immediateFailedCheckedFuture((TransactionCommitFailedException) cause));
1546 public static List<PhysAddress> getPhysAddress(List<String> macAddress) {
1547 Preconditions.checkNotNull(macAddress, "macAddress cannot be null");
1548 List<PhysAddress> physAddresses = new ArrayList<>();
1549 for (String mac : macAddress) {
1550 physAddresses.add(new PhysAddress(mac));
1552 return physAddresses;
1555 public static List<StaticMacEntries> getStaticMacEntries(List<String> staticMacAddresses) {
1556 if (isEmpty(staticMacAddresses)) {
1557 return Collections.EMPTY_LIST;
1559 StaticMacEntriesBuilder staticMacEntriesBuilder = new StaticMacEntriesBuilder();
1560 List<StaticMacEntries> staticMacEntries = new ArrayList<>();
1561 List<PhysAddress> physAddressList = getPhysAddress(staticMacAddresses);
1562 for (PhysAddress physAddress : physAddressList) {
1563 staticMacEntries.add(staticMacEntriesBuilder.setMacAddress(physAddress).build());
1565 return staticMacEntries;
1568 public static InstanceIdentifier<StaticMacEntries> getStaticMacEntriesCfgDataPathIdentifier(String interfaceName,
1569 String macAddress) {
1570 return InstanceIdentifier.builder(ElanInterfaces.class)
1571 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).child(StaticMacEntries.class,
1572 new StaticMacEntriesKey(new PhysAddress(macAddress))).build();
1575 public static List<StaticMacEntries> getDeletedEntries(List<StaticMacEntries> originalStaticMacEntries,
1576 List<StaticMacEntries> updatedStaticMacEntries) {
1577 if (isEmpty(originalStaticMacEntries)) {
1578 return Collections.EMPTY_LIST;
1580 List<StaticMacEntries> deleted = Lists.newArrayList(originalStaticMacEntries);
1581 if (isNotEmpty(updatedStaticMacEntries)) {
1582 deleted.removeAll(updatedStaticMacEntries);
1587 public static <T> List<T> diffOf(List<T> orig, List<T> updated) {
1588 if (isEmpty(orig)) {
1589 return Collections.EMPTY_LIST;
1591 List<T> diff = Lists.newArrayList(orig);
1592 if (isNotEmpty(updated)) {
1593 diff.removeAll(updated);
1598 public static void segregateToBeDeletedAndAddEntries(List<StaticMacEntries> originalStaticMacEntries,
1599 List<StaticMacEntries> updatedStaticMacEntries) {
1600 if (isNotEmpty(updatedStaticMacEntries)) {
1601 List<StaticMacEntries> existingClonedStaticMacEntries = new ArrayList<>();
1602 if (isNotEmpty(originalStaticMacEntries)) {
1603 existingClonedStaticMacEntries.addAll(0, originalStaticMacEntries);
1604 originalStaticMacEntries.removeAll(updatedStaticMacEntries);
1605 updatedStaticMacEntries.removeAll(existingClonedStaticMacEntries);
1610 public static boolean isEmpty(Collection collection) {
1611 return collection == null || collection.isEmpty();
1614 public static boolean isNotEmpty(Collection collection) {
1615 return !isEmpty(collection);
1618 public static void setElanInstancToDpnsCache(Map<String, Set<DpnInterfaces>> elanInstancToDpnsCache) {
1619 ElanUtils.elanInstancToDpnsCache = elanInstancToDpnsCache;
1622 public static Set<DpnInterfaces> getElanInvolvedDPNsFromCache(String elanName) {
1623 return elanInstancToDpnsCache.get(elanName);
1626 public static void addDPNInterfaceToElanInCache(String elanName, DpnInterfaces dpnInterfaces) {
1627 elanInstancToDpnsCache.computeIfAbsent(elanName, key -> new HashSet<>()).add(dpnInterfaces);
1630 public static void removeDPNInterfaceFromElanInCache(String elanName, DpnInterfaces dpnInterfaces) {
1631 elanInstancToDpnsCache.computeIfAbsent(elanName, key -> new HashSet<>()).remove(dpnInterfaces);
1634 public Optional<IpAddress> getSourceIpAddress(Ethernet ethernet) {
1635 Optional<IpAddress> srcIpAddress = Optional.absent();
1636 if (ethernet.getPayload() == null) {
1637 return srcIpAddress;
1639 byte[] ipAddrBytes = null;
1640 if (ethernet.getPayload() instanceof IPv4) {
1641 IPv4 ipv4 = (IPv4) ethernet.getPayload();
1642 ipAddrBytes = Ints.toByteArray(ipv4.getSourceAddress());
1643 } else if (ethernet.getPayload() instanceof ARP) {
1644 ipAddrBytes = ((ARP) ethernet.getPayload()).getSenderProtocolAddress();
1646 if (ipAddrBytes != null) {
1647 String ipAddr = NWUtil.toStringIpAddress(ipAddrBytes);
1648 return Optional.of(IpAddressBuilder.getDefaultInstance(ipAddr));
1650 return srcIpAddress;
1653 public List<MacEntry> getElanMacEntries(String elanName) {
1654 MacTable macTable = getElanMacTable(elanName);
1655 if (macTable == null) {
1656 return Collections.emptyList();
1658 return macTable.getMacEntry();
1661 public boolean isTunnelInLogicalGroup(String interfaceName) {
1662 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1663 .ietf.interfaces.rev140508.interfaces.Interface configIface =
1664 interfaceManager.getInterfaceInfoFromConfigDataStore(interfaceName);
1665 IfTunnel ifTunnel = configIface.getAugmentation(IfTunnel.class);
1666 if (ifTunnel != null && ifTunnel.getTunnelInterfaceType().isAssignableFrom(TunnelTypeVxlan.class)) {
1667 ParentRefs refs = configIface.getAugmentation(ParentRefs.class);
1668 if (refs != null && !Strings.isNullOrEmpty(refs.getParentInterface())) {
1669 return true; //multiple VxLAN tunnels enabled, i.e. only logical tunnel should be treated
1675 public static void addElanInterfaceToElanInstanceCache(String elanInstanceName, String elanInterfaceName) {
1676 elanInstanceToInterfacesCache.computeIfAbsent(elanInstanceName, key -> new HashSet<>()).add(elanInterfaceName);
1679 public static void removeElanInterfaceToElanInstanceCache(String elanInstanceName, String interfaceName) {
1680 Set<String> elanInterfaces = elanInstanceToInterfacesCache.get(elanInstanceName);
1681 if (elanInterfaces == null || elanInterfaces.isEmpty()) {
1684 elanInterfaces.remove(interfaceName);
1687 @Nonnull public static Set<String> removeAndGetElanInterfaces(String elanInstanceName) {
1688 Set<String> removed = elanInstanceToInterfacesCache.remove(elanInstanceName);
1689 return removed != null ? removed : Collections.emptySet();
1692 public static InstanceIdentifier<Flow> getFlowIid(Flow flow, BigInteger dpnId) {
1693 FlowKey flowKey = new FlowKey(new FlowId(flow.getId()));
1694 org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId nodeId =
1695 new org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId("openflow:" + dpnId);
1696 org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node nodeDpn =
1697 new NodeBuilder().setId(nodeId).setKey(new NodeKey(nodeId)).build();
1698 return InstanceIdentifier.builder(Nodes.class)
1699 .child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node.class,
1700 nodeDpn.getKey()).augmentation(FlowCapableNode.class)
1701 .child(Table.class, new TableKey(flow.getTableId())).child(Flow.class, flowKey).build();
1704 public static String getElanInterfaceJobKey(String interfaceName) {
1705 return "elaninterface-" + interfaceName;
1708 public void removeArpResponderFlow(BigInteger dpnId, String ingressInterfaceName, String ipAddress,
1710 LOG.info("Removing the ARP responder flow on DPN {} of Interface {} with IP {}", dpnId, ingressInterfaceName,
1712 ArpResponderUtil.removeFlow(mdsalManager, dpnId, ArpResponderUtil.getFlowId(lportTag, ipAddress));