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<String>> elanInstanceToInterfacesCache = new ConcurrentHashMap<>();
182 private final DataBroker broker;
183 private final IMdsalApiManager mdsalManager;
184 private final OdlInterfaceRpcService interfaceManagerRpcService;
185 private final ItmRpcService itmRpcService;
186 private final IInterfaceManager interfaceManager;
187 private final ElanConfig elanConfig;
188 private final ElanItmUtils elanItmUtils;
189 private final ElanEtreeUtils elanEtreeUtils;
191 public static final FutureCallback<Void> DEFAULT_CALLBACK = new FutureCallback<Void>() {
193 public void onSuccess(Void result) {
194 LOG.debug("Success in Datastore operation");
198 public void onFailure(Throwable error) {
199 LOG.error("Error in Datastore operation", error);
204 public ElanUtils(DataBroker dataBroker, IMdsalApiManager mdsalManager,
205 OdlInterfaceRpcService interfaceManagerRpcService, ItmRpcService itmRpcService, ElanConfig elanConfig,
206 IInterfaceManager interfaceManager, ElanEtreeUtils elanEtreeUtils, ElanItmUtils elanItmUtils) {
207 this.broker = dataBroker;
208 this.mdsalManager = mdsalManager;
209 this.interfaceManagerRpcService = interfaceManagerRpcService;
210 this.itmRpcService = itmRpcService;
211 this.interfaceManager = interfaceManager;
212 this.elanConfig = elanConfig;
213 this.elanEtreeUtils = elanEtreeUtils;
214 this.elanItmUtils = elanItmUtils;
217 public final Boolean isOpenstackVniSemanticsEnforced() {
218 return elanConfig.isOpenstackVniSemanticsEnforced() != null
219 ? elanConfig.isOpenstackVniSemanticsEnforced() : false;
222 public static void addElanInterfaceIntoCache(String interfaceName, ElanInterface elanInterface) {
223 elanInterfaceLocalCache.put(interfaceName, elanInterface);
226 public static void removeElanInterfaceFromCache(String interfaceName) {
227 elanInterfaceLocalCache.remove(interfaceName);
230 public static ElanInterface getElanInterfaceFromCache(String interfaceName) {
231 return elanInterfaceLocalCache.get(interfaceName);
235 * Uses the IdManager to retrieve a brand new ElanTag.
241 * @return the integer
243 public static Long retrieveNewElanTag(IdManagerService idManager, String idKey) {
245 AllocateIdInput getIdInput = new AllocateIdInputBuilder().setPoolName(ElanConstants.ELAN_ID_POOL_NAME)
246 .setIdKey(idKey).build();
249 Future<RpcResult<AllocateIdOutput>> result = idManager.allocateId(getIdInput);
250 RpcResult<AllocateIdOutput> rpcResult = result.get();
251 if (rpcResult.isSuccessful()) {
252 return rpcResult.getResult().getIdValue();
254 LOG.warn("RPC Call to Allocate Id returned with Errors {}", rpcResult.getErrors());
256 } catch (InterruptedException | ExecutionException e) {
257 LOG.warn("Exception when Allocating Id", e);
262 public static void releaseId(IdManagerService idManager, String poolName, String idKey) {
263 ReleaseIdInput releaseIdInput = new ReleaseIdInputBuilder().setPoolName(poolName).setIdKey(idKey).build();
264 JdkFutures.addErrorLogging(idManager.releaseId(releaseIdInput), LOG, "Release Id");
270 * @deprecated Consider using {@link #read2(LogicalDatastoreType, InstanceIdentifier)} with proper exception
272 * @param broker dataBroker
273 * @param datastoreType Logical DataStore type
274 * @param path IID to read
275 * @param <T> T extends DataObject
276 * @return the read value T
279 @SuppressWarnings("checkstyle:IllegalCatch")
280 public static <T extends DataObject> Optional<T> read(@Nonnull DataBroker broker,
281 LogicalDatastoreType datastoreType, InstanceIdentifier<T> path) {
282 try (ReadOnlyTransaction tx = broker.newReadOnlyTransaction()) {
283 return tx.read(datastoreType, path).get();
284 } catch (Exception e) {
285 throw new RuntimeException(e);
289 public <T extends DataObject> Optional<T> read2(LogicalDatastoreType datastoreType, InstanceIdentifier<T> path)
290 throws ReadFailedException {
291 try (ReadOnlyTransaction tx = broker.newReadOnlyTransaction()) {
292 CheckedFuture<Optional<T>, ReadFailedException> checkedFuture = tx.read(datastoreType, path);
293 return checkedFuture.checkedGet();
297 public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
298 InstanceIdentifier<T> path) {
299 WriteTransaction tx = broker.newWriteOnlyTransaction();
300 tx.delete(datastoreType, path);
301 Futures.addCallback(tx.submit(), DEFAULT_CALLBACK, MoreExecutors.directExecutor());
304 public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
305 InstanceIdentifier<T> path, FutureCallback<Void> callback) {
306 WriteTransaction tx = broker.newWriteOnlyTransaction();
307 tx.delete(datastoreType, path);
308 Futures.addCallback(tx.submit(), callback, MoreExecutors.directExecutor());
311 public static InstanceIdentifier<ElanInstance> getElanInstanceIdentifier() {
312 return InstanceIdentifier.builder(ElanInstances.class).child(ElanInstance.class).build();
315 // elan-interfaces Config Container
316 public static ElanInterface getElanInterfaceByElanInterfaceName(DataBroker broker, String elanInterfaceName) {
317 ElanInterface elanInterfaceObj = getElanInterfaceFromCache(elanInterfaceName);
318 if (elanInterfaceObj != null) {
319 return elanInterfaceObj;
321 InstanceIdentifier<ElanInterface> elanInterfaceId = getElanInterfaceConfigurationDataPathId(elanInterfaceName);
322 return MDSALUtil.read(broker, LogicalDatastoreType.CONFIGURATION, elanInterfaceId).orNull();
325 public static EtreeInterface getEtreeInterfaceByElanInterfaceName(DataBroker broker, String elanInterfaceName) {
326 ElanInterface elanInterface = getElanInterfaceByElanInterfaceName(broker, elanInterfaceName);
327 if (elanInterface == null) {
330 return elanInterface.getAugmentation(EtreeInterface.class);
334 public static InstanceIdentifier<ElanInterface> getElanInterfaceConfigurationDataPathId(String interfaceName) {
335 return InstanceIdentifier.builder(ElanInterfaces.class)
336 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).build();
339 // elan-state Operational container
340 public static Elan getElanByName(DataBroker broker, String elanInstanceName) {
341 InstanceIdentifier<Elan> elanIdentifier = getElanInstanceOperationalDataPath(elanInstanceName);
342 return MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL, elanIdentifier).orNull();
345 public static InstanceIdentifier<Elan> getElanInstanceOperationalDataPath(String elanInstanceName) {
346 return InstanceIdentifier.builder(ElanState.class).child(Elan.class, new ElanKey(elanInstanceName)).build();
349 // grouping of forwarding-entries
350 public MacEntry getInterfaceMacEntriesOperationalDataPath(String interfaceName, PhysAddress physAddress) {
351 InstanceIdentifier<MacEntry> existingMacEntryId = getInterfaceMacEntriesIdentifierOperationalDataPath(
352 interfaceName, physAddress);
353 return read(broker, LogicalDatastoreType.OPERATIONAL, existingMacEntryId).orNull();
356 public MacEntry getInterfaceMacEntriesOperationalDataPathFromId(InstanceIdentifier identifier) {
357 Optional<MacEntry> existingInterfaceMacEntry = read(broker,
358 LogicalDatastoreType.OPERATIONAL, identifier);
359 return existingInterfaceMacEntry.orNull();
362 public static InstanceIdentifier<MacEntry> getInterfaceMacEntriesIdentifierOperationalDataPath(String interfaceName,
363 PhysAddress physAddress) {
364 return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class)
365 .child(ElanInterfaceMac.class, new ElanInterfaceMacKey(interfaceName))
366 .child(MacEntry.class, new MacEntryKey(physAddress)).build();
370 // elan-forwarding-tables Operational container
371 public Optional<MacEntry> getMacEntryForElanInstance(String elanName, PhysAddress physAddress) {
372 InstanceIdentifier<MacEntry> macId = getMacEntryOperationalDataPath(elanName, physAddress);
373 return read(broker, LogicalDatastoreType.OPERATIONAL, macId);
376 public MacEntry getMacEntryFromElanMacId(InstanceIdentifier identifier) {
377 Optional<MacEntry> existingInterfaceMacEntry = read(broker,
378 LogicalDatastoreType.OPERATIONAL, identifier);
379 return existingInterfaceMacEntry.orNull();
382 public static InstanceIdentifier<MacEntry> getMacEntryOperationalDataPath(String elanName,
383 PhysAddress physAddress) {
384 return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class, new MacTableKey(elanName))
385 .child(MacEntry.class, new MacEntryKey(physAddress)).build();
388 public static InstanceIdentifier<MacTable> getElanMacTableOperationalDataPath(String elanName) {
389 return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class, new MacTableKey(elanName))
393 // elan-interface-forwarding-entries Operational container
394 public ElanInterfaceMac getElanInterfaceMacByInterfaceName(String interfaceName) {
395 return getElanInterfaceMacByInterfaceName(broker, interfaceName);
399 public static ElanInterfaceMac getElanInterfaceMacByInterfaceName(DataBroker dataBroker, String interfaceName) {
400 InstanceIdentifier<ElanInterfaceMac> elanInterfaceId = getElanInterfaceMacEntriesOperationalDataPath(
402 return read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanInterfaceId).orNull();
406 * Gets the elan interface mac addresses.
408 * @param interfaceName
410 * @return the elan interface mac addresses
412 public List<PhysAddress> getElanInterfaceMacAddresses(String interfaceName) {
413 List<PhysAddress> macAddresses = new ArrayList<>();
414 ElanInterfaceMac elanInterfaceMac = getElanInterfaceMacByInterfaceName(interfaceName);
415 if (elanInterfaceMac != null && elanInterfaceMac.getMacEntry() != null) {
416 List<MacEntry> macEntries = elanInterfaceMac.getMacEntry();
417 for (MacEntry macEntry : macEntries) {
418 macAddresses.add(macEntry.getMacAddress());
424 public static InstanceIdentifier<ElanInterfaceMac> getElanInterfaceMacEntriesOperationalDataPath(
425 String interfaceName) {
426 return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class)
427 .child(ElanInterfaceMac.class, new ElanInterfaceMacKey(interfaceName)).build();
431 * Returns the list of Interfaces that belong to an Elan on an specific DPN.
432 * Data retrieved from Elan's operational DS: elan-dpn-interfaces container
434 * @param elanInstanceName
435 * name of the Elan to which the interfaces must belong to
437 * Id of the DPN where the interfaces are located
438 * @return the elan interface Info
440 public DpnInterfaces getElanInterfaceInfoByElanDpn(String elanInstanceName, BigInteger dpId) {
441 InstanceIdentifier<DpnInterfaces> elanDpnInterfacesId = getElanDpnInterfaceOperationalDataPath(elanInstanceName,
443 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfacesId).orNull();
447 * Returns the InstanceIdentifier that points to the Interfaces of an Elan
448 * in a given DPN in the Operational DS. Data retrieved from Elans's
449 * operational DS: dpn-interfaces list
451 * @param elanInstanceName
452 * name of the Elan to which the interfaces must belong to
454 * Id of the DPN where the interfaces are located
455 * @return the elan dpn interface
457 public static InstanceIdentifier<DpnInterfaces> getElanDpnInterfaceOperationalDataPath(String elanInstanceName,
459 return InstanceIdentifier.builder(ElanDpnInterfaces.class)
460 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName))
461 .child(DpnInterfaces.class, new DpnInterfacesKey(dpId)).build();
464 // elan-tag-name-map Operational Container
465 public ElanTagName getElanInfoByElanTag(long elanTag) {
466 InstanceIdentifier<ElanTagName> elanId = getElanInfoEntriesOperationalDataPath(elanTag);
467 Optional<ElanTagName> existingElanInfo = read(broker,
468 LogicalDatastoreType.OPERATIONAL, elanId);
469 return existingElanInfo.orNull();
472 public static InstanceIdentifier<ElanTagName> getElanInfoEntriesOperationalDataPath(long elanTag) {
473 return InstanceIdentifier.builder(ElanTagNameMap.class).child(ElanTagName.class, new ElanTagNameKey(elanTag))
477 // interface-index-tag operational container
478 public Optional<IfIndexInterface> getInterfaceInfoByInterfaceTag(long interfaceTag) {
479 InstanceIdentifier<IfIndexInterface> interfaceId = getInterfaceInfoEntriesOperationalDataPath(interfaceTag);
480 return read(broker, LogicalDatastoreType.OPERATIONAL, interfaceId);
483 public static InstanceIdentifier<IfIndexInterface> getInterfaceInfoEntriesOperationalDataPath(long interfaceTag) {
484 return InstanceIdentifier.builder(IfIndexesInterfaceMap.class)
485 .child(IfIndexInterface.class, new IfIndexInterfaceKey((int) interfaceTag)).build();
488 public static InstanceIdentifier<ElanDpnInterfacesList> getElanDpnOperationDataPath(String elanInstanceName) {
489 return InstanceIdentifier.builder(ElanDpnInterfaces.class)
490 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName)).build();
493 public ElanDpnInterfacesList getElanDpnInterfacesList(String elanName) {
494 InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanName);
495 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orNull();
498 public ElanDpnInterfaces getElanDpnInterfacesList() {
499 InstanceIdentifier<ElanDpnInterfaces> elanDpnInterfaceId = InstanceIdentifier.builder(ElanDpnInterfaces.class)
501 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orNull();
505 * This method is useful get all ELAN participating CSS dpIds to install
506 * program remote dmac entries and updating remote bc groups for tor
509 * @param elanInstanceName
510 * the elan instance name
511 * @return list of dpIds
514 public List<BigInteger> getParticipatingDpnsInElanInstance(String elanInstanceName) {
515 List<BigInteger> dpIds = new ArrayList<>();
516 InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
517 Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = read(broker,
518 LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
519 if (!existingElanDpnInterfaces.isPresent()) {
522 List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().getDpnInterfaces();
523 for (DpnInterfaces dpnInterface : dpnInterfaces) {
524 dpIds.add(dpnInterface.getDpId());
530 * To check given dpId is already present in Elan instance. This can be used
531 * to program flow entry in external tunnel table when a new access port
532 * added for first time into the ELAN instance
536 * @param elanInstanceName
537 * the elan instance name
538 * @return true if dpId is already present, otherwise return false
540 public boolean isDpnAlreadyPresentInElanInstance(BigInteger dpId, String elanInstanceName) {
541 InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
542 Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = read(broker,
543 LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
544 if (!existingElanDpnInterfaces.isPresent()) {
547 List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().getDpnInterfaces();
548 for (DpnInterfaces dpnInterface : dpnInterfaces) {
549 if (dpnInterface.getDpId().equals(dpId)) {
556 public ElanForwardingTables getElanForwardingList() {
557 InstanceIdentifier<ElanForwardingTables> elanForwardingTableId = InstanceIdentifier
558 .builder(ElanForwardingTables.class).build();
559 return read(broker, LogicalDatastoreType.OPERATIONAL, elanForwardingTableId).orNull();
562 public static long getElanRemoteBroadCastGroupID(long elanTag) {
563 return ElanConstants.ELAN_GID_MIN + elanTag % ElanConstants.ELAN_GID_MIN * 2;
567 * Gets the elan mac table.
571 * @return the elan mac table
573 public MacTable getElanMacTable(String elanName) {
574 return getElanMacTable(broker, elanName);
578 public static MacTable getElanMacTable(DataBroker dataBroker, String elanName) {
579 InstanceIdentifier<MacTable> elanMacTableId = getElanMacTableOperationalDataPath(elanName);
580 return read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanMacTableId).orNull();
583 public static long getElanLocalBCGId(long elanTag) {
584 return ElanConstants.ELAN_GID_MIN + (elanTag % ElanConstants.ELAN_GID_MIN * 2 - 1);
587 public static long getElanRemoteBCGId(long elanTag) {
588 return ElanConstants.ELAN_GID_MIN + elanTag % ElanConstants.ELAN_GID_MIN * 2;
591 public static long getEtreeLeafLocalBCGId(long etreeLeafTag) {
592 return ElanConstants.ELAN_GID_MIN + (etreeLeafTag % ElanConstants.ELAN_GID_MIN * 2 - 1);
595 public static long getEtreeLeafRemoteBCGId(long etreeLeafTag) {
596 return ElanConstants.ELAN_GID_MIN + etreeLeafTag % ElanConstants.ELAN_GID_MIN * 2;
599 public static BigInteger getElanMetadataLabel(long elanTag, boolean isSHFlagSet) {
600 int shBit = isSHFlagSet ? 1 : 0;
601 return BigInteger.valueOf(elanTag).shiftLeft(24).or(BigInteger.valueOf(shBit));
605 * Setting SMAC, DMAC, UDMAC in this DPN and optionally in other DPNs.
609 * @param interfaceInfo
615 * @param configureRemoteFlows
616 * true if remote dmac flows should be configured as well
617 * @param writeFlowGroupTx
619 * @throws ElanException in case of issues creating the flow objects
621 public void setupMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo,
622 long macTimeout, String macAddress, boolean configureRemoteFlows,
623 WriteTransaction writeFlowGroupTx) throws ElanException {
624 synchronized (getElanMacDPNKey(elanInfo.getElanTag(), macAddress, interfaceInfo.getDpId())) {
625 setupKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress, mdsalManager,
627 setupOrigDmacFlows(elanInfo, interfaceInfo, macAddress, configureRemoteFlows, mdsalManager,
632 public void setupDMacFlowOnRemoteDpn(ElanInstance elanInfo, InterfaceInfo interfaceInfo, BigInteger dstDpId,
633 String macAddress, WriteTransaction writeFlowTx) throws ElanException {
634 String elanInstanceName = elanInfo.getElanInstanceName();
635 setupRemoteDmacFlow(dstDpId, interfaceInfo.getDpId(), interfaceInfo.getInterfaceTag(), elanInfo.getElanTag(),
636 macAddress, elanInstanceName, writeFlowTx, interfaceInfo.getInterfaceName(), elanInfo);
637 LOG.info("Remote Dmac flow entry created for elan Name:{}, logical port Name:{} and"
638 + " mac address {} on dpn:{}", elanInstanceName, interfaceInfo.getPortName(),
639 macAddress, dstDpId);
643 * Inserts a Flow in SMAC table to state that the MAC has already been
646 private void setupKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
647 String macAddress, IMdsalApiManager mdsalApiManager, WriteTransaction writeFlowGroupTx) {
648 FlowEntity flowEntity = buildKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress);
649 mdsalApiManager.addFlowToTx(flowEntity, writeFlowGroupTx);
650 LOG.debug("Known Smac flow entry created for elan Name:{}, logical Interface port:{} and mac address:{}",
651 elanInfo.getElanInstanceName(), elanInfo.getDescription(), macAddress);
654 public FlowEntity buildKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
656 int lportTag = interfaceInfo.getInterfaceTag();
657 // Matching metadata and eth_src fields
658 List<MatchInfo> mkMatches = new ArrayList<>();
659 mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanInfo.getElanTag(), lportTag),
660 ElanHelper.getElanMetadataMask()));
661 mkMatches.add(new MatchEthernetSource(new MacAddress(macAddress)));
662 List<InstructionInfo> mkInstructions = new ArrayList<>();
663 mkInstructions.add(new InstructionGotoTable(NwConstants.ELAN_DMAC_TABLE));
664 BigInteger dpId = interfaceInfo.getDpId();
665 long elanTag = getElanTag(broker, elanInfo, interfaceInfo);
666 return new FlowEntityBuilder()
668 .setTableId(NwConstants.ELAN_SMAC_TABLE)
669 .setFlowId(getKnownDynamicmacFlowRef(NwConstants.ELAN_SMAC_TABLE, dpId, lportTag, macAddress, elanTag))
671 .setFlowName(elanInfo.getDescription())
672 .setIdleTimeOut((int) macTimeout)
674 .setCookie(ElanConstants.COOKIE_ELAN_KNOWN_SMAC.add(BigInteger.valueOf(elanTag)))
675 .setMatchInfoList(mkMatches)
676 .setInstructionInfoList(mkInstructions)
678 // If Mac timeout is 0, the flow won't be deleted automatically, so no need to get notified
679 .setSendFlowRemFlag(macTimeout != 0)
683 private static Long getElanTag(DataBroker broker, ElanInstance elanInfo, InterfaceInfo interfaceInfo) {
684 EtreeInterface etreeInterface = getEtreeInterfaceByElanInterfaceName(broker, interfaceInfo.getInterfaceName());
685 if (etreeInterface == null || etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
686 return elanInfo.getElanTag();
688 EtreeInstance etreeInstance = elanInfo.getAugmentation(EtreeInstance.class);
689 if (etreeInstance == null) {
690 LOG.warn("EtreeInterface {} is connected to a non-Etree network: {}",
691 interfaceInfo.getInterfaceName(), elanInfo.getElanInstanceName());
692 return elanInfo.getElanTag();
694 return etreeInstance.getEtreeLeafTagVal().getValue();
700 * Installs a Flow in INTERNAL_TUNNEL_TABLE of the affected DPN that sends
701 * the packet through the specified interface if the tunnel_id matches the
702 * interface's lportTag.
704 * @param interfaceInfo
706 * @param mdsalApiManager
707 * the mdsal API manager
708 * @param writeFlowGroupTx
709 * the writeFLowGroup tx
711 public void setupTermDmacFlows(InterfaceInfo interfaceInfo, IMdsalApiManager mdsalApiManager,
712 WriteTransaction writeFlowGroupTx) {
713 BigInteger dpId = interfaceInfo.getDpId();
714 int lportTag = interfaceInfo.getInterfaceTag();
715 Flow flow = MDSALUtil.buildFlowNew(NwConstants.INTERNAL_TUNNEL_TABLE,
716 getIntTunnelTableFlowRef(NwConstants.INTERNAL_TUNNEL_TABLE, lportTag), 5,
717 String.format("%s:%d", "ITM Flow Entry ", lportTag), 0, 0,
718 ITMConstants.COOKIE_ITM.add(BigInteger.valueOf(lportTag)),
719 getTunnelIdMatchForFilterEqualsLPortTag(lportTag),
720 getInstructionsInPortForOutGroup(interfaceInfo.getInterfaceName()));
721 mdsalApiManager.addFlowToTx(dpId, flow, writeFlowGroupTx);
722 LOG.debug("Terminating service table flow entry created on dpn:{} for logical Interface port:{}", dpId,
723 interfaceInfo.getPortName());
727 * Constructs the FlowName for flows installed in the Internal Tunnel Table,
728 * consisting in tableId + elanTag.
734 * @return the Internal tunnel
736 public static String getIntTunnelTableFlowRef(short tableId, int elanTag) {
737 return new StringBuffer().append(tableId).append(elanTag).toString();
741 * Constructs the Matches that checks that the tunnel_id field contains a
745 * lportTag that must be checked against the tunnel_id field
746 * @return the list of match Info
748 public static List<MatchInfo> getTunnelIdMatchForFilterEqualsLPortTag(int lportTag) {
749 List<MatchInfo> mkMatches = new ArrayList<>();
751 mkMatches.add(new MatchTunnelId(BigInteger.valueOf(lportTag)));
756 * Constructs the Instructions that take the packet over a given interface.
759 * Name of the interface where the packet must be sent over. It
760 * can be a local interface or a tunnel interface (internal or
762 * @return the Instruction
764 public List<Instruction> getInstructionsInPortForOutGroup(String ifName) {
765 List<Instruction> mkInstructions = new ArrayList<>();
766 List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
768 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
769 return mkInstructions;
773 * Returns the list of Actions to be taken when sending the packet through
774 * an Elan interface. Note that this interface can refer to an ElanInterface
775 * where the Elan VM is attached to a DPN or an ITM tunnel interface where
776 * Elan traffic can be sent through. In this latter case, the tunnelKey is
777 * mandatory and it can hold serviceId for internal tunnels or the VNI for
784 * @return the egress actions for interface
786 @SuppressWarnings("checkstyle:IllegalCatch")
787 public List<Action> getEgressActionsForInterface(String ifName, Long tunnelKey) {
788 List<Action> listAction = new ArrayList<>();
790 GetEgressActionsForInterfaceInput getEgressActionInput = new GetEgressActionsForInterfaceInputBuilder()
791 .setIntfName(ifName).setTunnelKey(tunnelKey).build();
792 Future<RpcResult<GetEgressActionsForInterfaceOutput>> result = interfaceManagerRpcService
793 .getEgressActionsForInterface(getEgressActionInput);
794 RpcResult<GetEgressActionsForInterfaceOutput> rpcResult = result.get();
795 if (!rpcResult.isSuccessful()) {
796 LOG.debug("RPC Call to Get egress actions for interface {} returned with Errors {}", ifName,
797 rpcResult.getErrors());
799 List<Action> actions = rpcResult.getResult().getAction();
800 listAction = actions;
802 } catch (Exception e) {
803 LOG.warn("Exception when egress actions for interface {}", ifName, e);
808 private void setupOrigDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
809 boolean configureRemoteFlows, IMdsalApiManager mdsalApiManager,
810 WriteTransaction writeFlowGroupTx)
811 throws ElanException {
812 BigInteger dpId = interfaceInfo.getDpId();
813 String ifName = interfaceInfo.getInterfaceName();
814 long ifTag = interfaceInfo.getInterfaceTag();
815 String elanInstanceName = elanInfo.getElanInstanceName();
817 Long elanTag = elanInfo.getElanTag();
819 setupLocalDmacFlow(elanTag, dpId, ifName, macAddress, elanInfo, mdsalApiManager, ifTag,
821 LOG.debug("Dmac flow entry created for elan Name:{}, logical port Name:{} mand mac address:{} "
822 + "on dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, dpId);
824 if (!configureRemoteFlows) {
828 List<DpnInterfaces> elanDpns = getInvolvedDpnsInElan(elanInstanceName);
829 for (DpnInterfaces elanDpn : elanDpns) {
831 if (elanDpn.getDpId().equals(dpId)) {
835 // Check for the Remote DPN present in Inventory Manager
836 if (!isDpnPresent(elanDpn.getDpId())) {
840 // For remote DPNs a flow is needed to indicate that packets of this ELAN going to this MAC need to be
841 // forwarded through the appropriate ITM tunnel
842 setupRemoteDmacFlow(elanDpn.getDpId(), // srcDpn (the remote DPN in this case)
843 dpId, // dstDpn (the local DPN)
844 interfaceInfo.getInterfaceTag(), // lportTag of the local interface
845 elanTag, // identifier of the Elan
846 macAddress, // MAC to be programmed in remote DPN
847 elanInstanceName, writeFlowGroupTx, ifName, elanInfo
849 LOG.debug("Remote Dmac flow entry created for elan Name:{}, logical port Name:{} and mac address:{} on"
850 + " dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, elanDpn.getDpId());
853 // TODO: Make sure that the same is performed against the ElanDevices.
857 public List<DpnInterfaces> getInvolvedDpnsInElan(String elanName) {
858 return getElanDPNByName(elanName);
862 public List<DpnInterfaces> getElanDPNByName(String elanInstanceName) {
863 InstanceIdentifier<ElanDpnInterfacesList> elanIdentifier = getElanDpnOperationDataPath(elanInstanceName);
864 return MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL, elanIdentifier).toJavaUtil().map(
865 ElanDpnInterfacesList::getDpnInterfaces).orElse(Collections.emptyList());
868 private void setupLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
869 ElanInstance elanInfo, IMdsalApiManager mdsalApiManager, long ifTag, WriteTransaction writeFlowGroupTx) {
870 Flow flowEntity = buildLocalDmacFlowEntry(elanTag, dpId, ifName, macAddress, elanInfo, ifTag);
871 mdsalApiManager.addFlowToTx(dpId, flowEntity, writeFlowGroupTx);
872 installEtreeLocalDmacFlow(elanTag, dpId, ifName, macAddress, elanInfo,
873 mdsalApiManager, ifTag, writeFlowGroupTx);
876 private void installEtreeLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
877 ElanInstance elanInfo, IMdsalApiManager mdsalApiManager, long ifTag, WriteTransaction writeFlowGroupTx) {
878 EtreeInterface etreeInterface = getEtreeInterfaceByElanInterfaceName(broker, ifName);
879 if (etreeInterface != null) {
880 if (etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
881 EtreeLeafTagName etreeTagName = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
882 if (etreeTagName == null) {
883 LOG.warn("Interface {} seems like it belongs to Etree but etreeTagName from elanTag {} is null",
886 Flow flowEntity = buildLocalDmacFlowEntry(etreeTagName.getEtreeLeafTag().getValue(), dpId, ifName,
887 macAddress, elanInfo, ifTag);
888 mdsalApiManager.addFlowToTx(dpId, flowEntity, writeFlowGroupTx);
894 public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, long lporTag, String macAddress,
896 return new StringBuffer().append(tableId).append(elanTag).append(dpId).append(lporTag).append(macAddress)
900 public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, BigInteger remoteDpId,
901 String macAddress, long elanTag) {
902 return new StringBuffer().append(tableId).append(elanTag).append(dpId).append(remoteDpId).append(macAddress)
906 public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, String macAddress, long elanTag) {
907 return new StringBuffer().append(tableId).append(elanTag).append(dpId).append(macAddress).toString();
910 public static String getKnownDynamicmacFlowRef(short elanDmacTable, BigInteger dpId, String extDeviceNodeId,
911 String dstMacAddress, long elanTag, boolean shFlag) {
912 return new StringBuffer().append(elanDmacTable).append(elanTag).append(dpId).append(extDeviceNodeId)
913 .append(dstMacAddress).append(shFlag).toString();
917 * Builds the flow to be programmed in the DMAC table of the local DPN (that
918 * is, where the MAC is attached to). This flow consists in:
920 * <p>Match: + elanTag in metadata + packet goes to a MAC locally attached
921 * Actions: + optionally, pop-vlan + set-vlan-id + output to ifName's
938 public Flow buildLocalDmacFlowEntry(long elanTag, BigInteger dpId, String ifName, String macAddress,
939 ElanInstance elanInfo, long ifTag) {
941 List<MatchInfo> mkMatches = new ArrayList<>();
942 mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
943 mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddress)));
945 List<Instruction> mkInstructions = new ArrayList<>();
946 List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
947 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
948 Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
949 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, ifTag, macAddress, elanTag), 20,
950 elanInfo.getElanInstanceName(), 0, 0, ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(
951 BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
956 public void setupRemoteDmacFlow(BigInteger srcDpId, BigInteger destDpId, int lportTag, long elanTag, String
957 macAddress, String displayName, WriteTransaction writeFlowGroupTx, String interfaceName, ElanInstance
958 elanInstance) throws ElanException {
959 if (interfaceManager.isExternalInterface(interfaceName)) {
960 LOG.debug("Ignoring install remote DMAC {} flow on provider interface {} elan {}",
961 macAddress, interfaceName, elanInstance.getElanInstanceName());
965 // if openstack-vni-semantics are enforced, segmentation ID is passed as network VNI for VxLAN based provider
966 // networks, 0 otherwise
967 long lportTagOrVni = !isOpenstackVniSemanticsEnforced() ? lportTag : isVxlan(elanInstance)
968 ? elanInstance.getSegmentationId() : 0;
969 flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTagOrVni, elanTag, macAddress, displayName,
971 mdsalManager.addFlowToTx(srcDpId, flowEntity, writeFlowGroupTx);
972 setupEtreeRemoteDmacFlow(srcDpId, destDpId, lportTagOrVni, elanTag, macAddress, displayName, interfaceName,
973 writeFlowGroupTx, elanInstance);
976 private void setupEtreeRemoteDmacFlow(BigInteger srcDpId, BigInteger destDpId, long lportTagOrVni, long elanTag,
977 String macAddress, String displayName, String interfaceName,
978 WriteTransaction writeFlowGroupTx, ElanInstance elanInstance)
979 throws ElanException {
981 EtreeInterface etreeInterface = getEtreeInterfaceByElanInterfaceName(broker, interfaceName);
982 if (etreeInterface != null) {
983 if (etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
984 EtreeLeafTagName etreeTagName = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
985 if (etreeTagName == null) {
986 LOG.warn("Interface " + interfaceName
987 + " seems like it belongs to Etree but etreeTagName from elanTag " + elanTag + " is null.");
989 flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTagOrVni,
990 etreeTagName.getEtreeLeafTag().getValue(), macAddress, displayName, elanInstance);
991 mdsalManager.addFlowToTx(srcDpId, flowEntity, writeFlowGroupTx);
998 * Builds a Flow to be programmed in a remote DPN's DMAC table. This flow
999 * consists in: Match: + elanTag in packet's metadata + packet going to a
1000 * MAC known to be located in another DPN Actions: + set_tunnel_id
1001 * + output ITM internal tunnel interface with the other DPN
1007 * @param lportTagOrVni
1008 * lportTag or network VNI
1013 * @param displayName
1015 * @param elanInstance
1017 * @return the flow remote Dmac
1018 * @throws ElanException in case of issues creating the flow objects
1020 @SuppressWarnings("checkstyle:IllegalCatch")
1021 public Flow buildRemoteDmacFlowEntry(BigInteger srcDpId, BigInteger destDpId, long lportTagOrVni, long elanTag,
1022 String macAddress, String displayName, ElanInstance elanInstance) throws ElanException {
1023 List<MatchInfo> mkMatches = new ArrayList<>();
1024 mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
1025 mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddress)));
1027 List<Instruction> mkInstructions = new ArrayList<>();
1029 // List of Action for the provided Source and Destination DPIDs
1031 List<Action> actions = null;
1032 if (isVlan(elanInstance) || isFlat(elanInstance)) {
1033 String interfaceName = getExternalElanInterface(elanInstance.getElanInstanceName(), srcDpId);
1034 if (null == interfaceName) {
1035 LOG.info("buildRemoteDmacFlowEntry: Could not find interfaceName for {} {}", srcDpId,
1038 actions = getEgressActionsForInterface(interfaceName, null);
1039 } else if (isVxlan(elanInstance)) {
1040 actions = elanItmUtils.getInternalTunnelItmEgressAction(srcDpId, destDpId, lportTagOrVni);
1042 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
1043 } catch (Exception e) {
1044 LOG.error("Could not get egress actions to add to flow for srcDpId=" + srcDpId + ", destDpId=" + destDpId
1045 + ", lportTag/VNI=" + lportTagOrVni, e);
1048 Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
1049 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, srcDpId, destDpId, macAddress, elanTag),
1051 displayName, 0, /* idleTimeout */
1052 0, /* hardTimeout */
1053 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
1059 public void deleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, MacEntry macEntry,
1060 WriteTransaction deleteFlowGroupTx) {
1061 if (elanInfo == null || interfaceInfo == null) {
1064 String macAddress = macEntry.getMacAddress().getValue();
1065 synchronized (getElanMacDPNKey(elanInfo.getElanTag(), macAddress, interfaceInfo.getDpId())) {
1066 deleteMacFlows(elanInfo, interfaceInfo, macAddress, /* alsoDeleteSMAC */ true, deleteFlowGroupTx);
1070 public void deleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1071 boolean deleteSmac, WriteTransaction deleteFlowGroupTx) {
1072 String elanInstanceName = elanInfo.getElanInstanceName();
1073 List<DpnInterfaces> remoteFEs = getInvolvedDpnsInElan(elanInstanceName);
1074 BigInteger srcdpId = interfaceInfo.getDpId();
1075 boolean isFlowsRemovedInSrcDpn = false;
1076 for (DpnInterfaces dpnInterface : remoteFEs) {
1077 Long elanTag = elanInfo.getElanTag();
1078 BigInteger dstDpId = dpnInterface.getDpId();
1079 if (executeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1080 elanTag, dstDpId, deleteFlowGroupTx)) {
1081 isFlowsRemovedInSrcDpn = true;
1083 executeEtreeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1084 elanTag, dstDpId, deleteFlowGroupTx);
1086 if (!isFlowsRemovedInSrcDpn) {
1087 deleteSmacAndDmacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, deleteFlowGroupTx);
1091 private void executeEtreeDeleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1092 boolean deleteSmac, String elanInstanceName, BigInteger srcdpId, Long elanTag, BigInteger dstDpId,
1093 WriteTransaction deleteFlowGroupTx) {
1094 EtreeLeafTagName etreeLeafTag = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
1095 if (etreeLeafTag != null) {
1096 executeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1097 etreeLeafTag.getEtreeLeafTag().getValue(), dstDpId, deleteFlowGroupTx);
1101 private boolean executeDeleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1102 boolean deleteSmac, String elanInstanceName, BigInteger srcdpId, Long elanTag, BigInteger dstDpId,
1103 WriteTransaction deleteFlowGroupTx) {
1104 boolean isFlowsRemovedInSrcDpn = false;
1105 if (dstDpId.equals(srcdpId)) {
1106 isFlowsRemovedInSrcDpn = true;
1107 deleteSmacAndDmacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, deleteFlowGroupTx);
1108 } else if (isDpnPresent(dstDpId)) {
1110 .removeFlowToTx(dstDpId,
1111 MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, getKnownDynamicmacFlowRef(
1112 NwConstants.ELAN_DMAC_TABLE, dstDpId, srcdpId, macAddress, elanTag)),
1114 LOG.debug("Dmac flow entry deleted for elan:{}, logical interface port:{} and mac address:{} on dpn:{}",
1115 elanInstanceName, interfaceInfo.getPortName(), macAddress, dstDpId);
1117 return isFlowsRemovedInSrcDpn;
1120 private void deleteSmacAndDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1121 boolean deleteSmac, WriteTransaction deleteFlowGroupTx) {
1122 String elanInstanceName = elanInfo.getElanInstanceName();
1123 long ifTag = interfaceInfo.getInterfaceTag();
1124 BigInteger srcdpId = interfaceInfo.getDpId();
1125 Long elanTag = elanInfo.getElanTag();
1128 .removeFlowToTx(srcdpId,
1129 MDSALUtil.buildFlow(NwConstants.ELAN_SMAC_TABLE, getKnownDynamicmacFlowRef(
1130 NwConstants.ELAN_SMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)),
1133 mdsalManager.removeFlowToTx(srcdpId,
1134 MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE,
1135 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)),
1137 LOG.debug("All the required flows deleted for elan:{}, logical Interface port:{} and MAC address:{} on dpn:{}",
1138 elanInstanceName, interfaceInfo.getPortName(), macAddress, srcdpId);
1142 * Updates the Elan information in the Operational DS. It also updates the
1143 * ElanInstance in the Config DS by setting the adquired elanTag.
1149 * @param elanInstanceAdded
1150 * the elan instance added
1151 * @param elanInterfaces
1152 * the elan interfaces
1156 * @return the updated ELAN instance.
1158 public static ElanInstance updateOperationalDataStore(DataBroker broker, IdManagerService idManager,
1159 ElanInstance elanInstanceAdded, List<String> elanInterfaces, WriteTransaction tx) {
1160 String elanInstanceName = elanInstanceAdded.getElanInstanceName();
1161 Long elanTag = elanInstanceAdded.getElanTag();
1162 if (elanTag == null || elanTag == 0L) {
1163 elanTag = retrieveNewElanTag(idManager, elanInstanceName);
1165 Elan elanInfo = new ElanBuilder().setName(elanInstanceName).setElanInterfaces(elanInterfaces)
1166 .setKey(new ElanKey(elanInstanceName)).build();
1168 // Add the ElanState in the elan-state operational data-store
1169 tx.put(LogicalDatastoreType.OPERATIONAL, getElanInstanceOperationalDataPath(elanInstanceName),
1170 elanInfo, WriteTransaction.CREATE_MISSING_PARENTS);
1172 // Add the ElanMacTable in the elan-mac-table operational data-store
1173 MacTable elanMacTable = new MacTableBuilder().setKey(new MacTableKey(elanInstanceName)).build();
1174 tx.put(LogicalDatastoreType.OPERATIONAL, getElanMacTableOperationalDataPath(elanInstanceName),
1175 elanMacTable, WriteTransaction.CREATE_MISSING_PARENTS);
1177 ElanTagNameBuilder elanTagNameBuilder = new ElanTagNameBuilder().setElanTag(elanTag)
1178 .setKey(new ElanTagNameKey(elanTag)).setName(elanInstanceName);
1179 long etreeLeafTag = -1;
1180 if (isEtreeInstance(elanInstanceAdded)) {
1181 etreeLeafTag = retrieveNewElanTag(idManager,elanInstanceName + ElanConstants
1183 EtreeLeafTagName etreeLeafTagName = new EtreeLeafTagNameBuilder()
1184 .setEtreeLeafTag(new EtreeLeafTag(etreeLeafTag)).build();
1185 elanTagNameBuilder.addAugmentation(EtreeLeafTagName.class, etreeLeafTagName);
1186 addTheLeafTagAsElanTag(broker, elanInstanceName, etreeLeafTag, tx);
1188 ElanTagName elanTagName = elanTagNameBuilder.build();
1190 // Add the ElanTag to ElanName in the elan-tag-name Operational
1192 tx.put(LogicalDatastoreType.OPERATIONAL,
1193 getElanInfoEntriesOperationalDataPath(elanTag), elanTagName);
1195 // Updates the ElanInstance Config DS by setting the just acquired
1197 ElanInstanceBuilder elanInstanceBuilder = new ElanInstanceBuilder().setElanInstanceName(elanInstanceName)
1198 .setDescription(elanInstanceAdded.getDescription())
1199 .setMacTimeout(elanInstanceAdded.getMacTimeout() == null
1200 ? Long.valueOf(ElanConstants.DEFAULT_MAC_TIME_OUT) : elanInstanceAdded.getMacTimeout())
1201 .setKey(elanInstanceAdded.getKey()).setElanTag(elanTag);
1202 if (isEtreeInstance(elanInstanceAdded)) {
1203 EtreeInstance etreeInstance = new EtreeInstanceBuilder().setEtreeLeafTagVal(new EtreeLeafTag(etreeLeafTag))
1205 elanInstanceBuilder.addAugmentation(EtreeInstance.class, etreeInstance);
1207 ElanInstance elanInstanceWithTag = elanInstanceBuilder.build();
1208 tx.merge(LogicalDatastoreType.CONFIGURATION, ElanHelper.getElanInstanceConfigurationDataPath(elanInstanceName),
1209 elanInstanceWithTag, WriteTransaction.CREATE_MISSING_PARENTS);
1210 return elanInstanceWithTag;
1213 private static void addTheLeafTagAsElanTag(DataBroker broker, String elanInstanceName, long etreeLeafTag,
1214 WriteTransaction tx) {
1215 ElanTagName etreeTagAsElanTag = new ElanTagNameBuilder().setElanTag(etreeLeafTag)
1216 .setKey(new ElanTagNameKey(etreeLeafTag)).setName(elanInstanceName).build();
1217 tx.put(LogicalDatastoreType.OPERATIONAL,
1218 getElanInfoEntriesOperationalDataPath(etreeLeafTag), etreeTagAsElanTag);
1221 private static boolean isEtreeInstance(ElanInstance elanInstanceAdded) {
1222 return elanInstanceAdded.getAugmentation(EtreeInstance.class) != null;
1225 public boolean isDpnPresent(BigInteger dpnId) {
1226 String dpn = String.format("%s:%s", "openflow", dpnId);
1227 NodeId nodeId = new NodeId(dpn);
1229 InstanceIdentifier<Node> node = InstanceIdentifier.builder(Nodes.class).child(Node.class, new NodeKey(nodeId))
1231 return read(broker, LogicalDatastoreType.CONFIGURATION, node).isPresent();
1234 public static ServicesInfo getServiceInfo(String elanInstanceName, String interfaceName) {
1235 return InterfaceServiceUtil.buildServiceInfo(elanInstanceName + "." + interfaceName,
1236 ElanConstants.ELAN_SERVICE_PRIORITY);
1239 public static String getElanServiceName(String elanName, String interfaceName) {
1240 return "elan." + elanName + interfaceName;
1243 public static BoundServices getBoundServices(String serviceName, short servicePriority, int flowPriority,
1244 BigInteger cookie, List<Instruction> instructions) {
1245 StypeOpenflowBuilder augBuilder = new StypeOpenflowBuilder().setFlowCookie(cookie).setFlowPriority(flowPriority)
1246 .setInstruction(instructions);
1247 return new BoundServicesBuilder().setKey(new BoundServicesKey(servicePriority)).setServiceName(serviceName)
1248 .setServicePriority(servicePriority).setServiceType(ServiceTypeFlowBased.class)
1249 .addAugmentation(StypeOpenflow.class, augBuilder.build()).build();
1252 public static InstanceIdentifier<BoundServices> buildServiceId(String interfaceName, short serviceIndex) {
1253 return InstanceIdentifier.builder(ServiceBindings.class)
1254 .child(ServicesInfo.class, new ServicesInfoKey(interfaceName, ServiceModeIngress.class))
1255 .child(BoundServices.class, new BoundServicesKey(serviceIndex)).build();
1258 public static List<MatchInfo> getTunnelMatchesForServiceId(int elanTag) {
1259 List<MatchInfo> mkMatches = new ArrayList<>();
1260 // Matching metadata
1261 mkMatches.add(new MatchTunnelId(BigInteger.valueOf(elanTag)));
1266 public void removeTerminatingServiceAction(BigInteger destDpId, int serviceId) {
1267 RemoveTerminatingServiceActionsInput input = new RemoveTerminatingServiceActionsInputBuilder()
1268 .setDpnId(destDpId).setServiceId(serviceId).build();
1269 Future<RpcResult<Void>> futureObject = itmRpcService.removeTerminatingServiceActions(input);
1271 RpcResult<Void> result = futureObject.get();
1272 if (result.isSuccessful()) {
1273 LOG.debug("Successfully completed removeTerminatingServiceActions for ELAN with serviceId {} on "
1274 + "dpn {}", serviceId, destDpId);
1276 LOG.debug("Failure in removeTerminatingServiceAction RPC call for ELAN with serviceId {} on "
1277 + "dpn {}", serviceId, destDpId);
1279 } catch (InterruptedException | ExecutionException e) {
1280 LOG.error("Error in RPC call removeTerminatingServiceActions for ELAN with serviceId {} on "
1281 + "dpn {}: {}", serviceId, destDpId, e);
1286 * Gets the external tunnel.
1288 * @param sourceDevice
1290 * @param destinationDevice
1291 * the destination device
1292 * @param datastoreType
1293 * the datastore type
1294 * @return the external tunnel
1296 public ExternalTunnel getExternalTunnel(String sourceDevice, String destinationDevice,
1297 LogicalDatastoreType datastoreType) {
1298 Class<? extends TunnelTypeBase> tunType = TunnelTypeVxlan.class;
1299 InstanceIdentifier<ExternalTunnel> iid = InstanceIdentifier.builder(ExternalTunnelList.class)
1300 .child(ExternalTunnel.class, new ExternalTunnelKey(destinationDevice, sourceDevice, tunType)).build();
1301 return read(broker, datastoreType, iid).orNull();
1305 * Gets the external tunnel.
1307 * @param interfaceName
1308 * the interface name
1309 * @param datastoreType
1310 * the datastore type
1311 * @return the external tunnel
1313 public ExternalTunnel getExternalTunnel(String interfaceName, LogicalDatastoreType datastoreType) {
1314 ExternalTunnel externalTunnel = null;
1315 List<ExternalTunnel> externalTunnels = getAllExternalTunnels(datastoreType);
1316 for (ExternalTunnel tunnel : externalTunnels) {
1317 if (StringUtils.equalsIgnoreCase(interfaceName, tunnel.getTunnelInterfaceName())) {
1318 externalTunnel = tunnel;
1322 return externalTunnel;
1326 * Gets the all external tunnels.
1328 * @param datastoreType
1329 * the data store type
1330 * @return the all external tunnels
1332 public List<ExternalTunnel> getAllExternalTunnels(LogicalDatastoreType datastoreType) {
1333 InstanceIdentifier<ExternalTunnelList> iid = InstanceIdentifier.builder(ExternalTunnelList.class).build();
1334 return read(broker, datastoreType, iid).toJavaUtil().map(ExternalTunnelList::getExternalTunnel).orElse(
1335 Collections.emptyList());
1338 public static List<MatchInfo> buildMatchesForElanTagShFlagAndDstMac(long elanTag, boolean shFlag, String macAddr) {
1339 List<MatchInfo> mkMatches = new ArrayList<>();
1341 new MatchMetadata(getElanMetadataLabel(elanTag, shFlag), MetaDataUtil.METADATA_MASK_SERVICE_SH_FLAG));
1342 mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddr)));
1347 * Checks if is interface operational.
1349 * @param interfaceName
1350 * the interface name
1353 * @return true, if is interface operational
1355 public static boolean isInterfaceOperational(String interfaceName, DataBroker dataBroker) {
1356 if (StringUtils.isBlank(interfaceName)) {
1359 Interface ifState = getInterfaceStateFromOperDS(interfaceName, dataBroker);
1360 if (ifState == null) {
1363 return ifState.getOperStatus() == OperStatus.Up && ifState.getAdminStatus() == AdminStatus.Up;
1367 * Gets the interface state from operational ds.
1369 * @param interfaceName
1370 * the interface name
1373 * @return the interface state from oper ds
1375 public static org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1376 .ietf.interfaces.rev140508.interfaces.state.Interface getInterfaceStateFromOperDS(
1377 String interfaceName, DataBroker dataBroker) {
1378 InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1379 .ietf.interfaces.rev140508.interfaces.state.Interface> ifStateId = createInterfaceStateInstanceIdentifier(
1381 return MDSALUtil.read(dataBroker, LogicalDatastoreType.OPERATIONAL, ifStateId).orNull();
1385 * Creates the interface state instance identifier.
1387 * @param interfaceName
1388 * the interface name
1389 * @return the instance identifier
1391 public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1392 .ietf.interfaces.rev140508.interfaces.state.Interface> createInterfaceStateInstanceIdentifier(
1393 String interfaceName) {
1394 InstanceIdentifierBuilder<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1395 .ietf.interfaces.rev140508.interfaces.state.Interface> idBuilder = InstanceIdentifier
1396 .builder(InterfacesState.class)
1397 .child(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1398 .ietf.interfaces.rev140508.interfaces.state.Interface.class,
1399 new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1400 .ietf.interfaces.rev140508.interfaces.state.InterfaceKey(
1402 return idBuilder.build();
1405 public static CheckedFuture<Void, TransactionCommitFailedException> waitForTransactionToComplete(
1406 WriteTransaction tx) {
1407 CheckedFuture<Void, TransactionCommitFailedException> futures = tx.submit();
1410 } catch (InterruptedException | ExecutionException e) {
1411 LOG.error("Error writing to datastore {}", e);
1416 public static boolean isVxlan(ElanInstance elanInstance) {
1417 return elanInstance != null && elanInstance.getSegmentType() != null
1418 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1419 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId() != 0;
1422 private static boolean isVxlanSegment(ElanInstance elanInstance) {
1423 if (elanInstance != null) {
1424 List<ElanSegments> elanSegments = elanInstance.getElanSegments();
1425 if (elanSegments != null) {
1426 for (ElanSegments segment : elanSegments) {
1427 if (segment != null && segment.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1428 && segment.getSegmentationId() != null
1429 && segment.getSegmentationId().longValue() != 0) {
1438 public static boolean isVxlanNetworkOrVxlanSegment(ElanInstance elanInstance) {
1439 return isVxlan(elanInstance) || isVxlanSegment(elanInstance);
1442 public static Long getVxlanSegmentationId(ElanInstance elanInstance) {
1443 Long segmentationId = 0L;
1444 if (elanInstance == null) {
1445 return segmentationId;
1448 if (elanInstance.getSegmentType() != null
1449 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1450 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId().longValue() != 0) {
1451 segmentationId = elanInstance.getSegmentationId();
1453 for (ElanSegments segment: elanInstance.getElanSegments()) {
1454 if (segment != null && segment.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1455 && segment.getSegmentationId() != null
1456 && segment.getSegmentationId().longValue() != 0) {
1457 segmentationId = segment.getSegmentationId();
1461 return segmentationId;
1464 public static boolean isVlan(ElanInstance elanInstance) {
1465 return elanInstance != null && elanInstance.getSegmentType() != null
1466 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVlan.class)
1467 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId() != 0;
1470 public static boolean isFlat(ElanInstance elanInstance) {
1471 return elanInstance != null && elanInstance.getSegmentType() != null
1472 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeFlat.class);
1475 public void addDmacRedirectToDispatcherFlows(Long elanTag, String displayName,
1476 String macAddress, List<BigInteger> dpnIds) {
1477 for (BigInteger dpId : dpnIds) {
1478 WriteTransaction writeTx = broker.newWriteOnlyTransaction();
1479 mdsalManager.addFlowToTx(buildDmacRedirectToDispatcherFlow(dpId, macAddress, displayName, elanTag),
1485 public void removeDmacRedirectToDispatcherFlows(Long elanTag, String macAddress, List<BigInteger> dpnIds) {
1486 for (BigInteger dpId : dpnIds) {
1487 String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, macAddress, elanTag);
1488 mdsalManager.removeFlow(dpId, MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, flowId));
1492 public static FlowEntity buildDmacRedirectToDispatcherFlow(BigInteger dpId, String dstMacAddress,
1493 String displayName, long elanTag) {
1494 List<MatchInfo> matches = new ArrayList<>();
1495 matches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
1496 matches.add(new MatchEthernetDestination(new MacAddress(dstMacAddress)));
1497 List<InstructionInfo> instructions = new ArrayList<>();
1498 List<ActionInfo> actions = new ArrayList<>();
1499 actions.add(new ActionNxResubmit(NwConstants.LPORT_DISPATCHER_TABLE));
1501 instructions.add(new InstructionApplyActions(actions));
1502 String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, dstMacAddress, elanTag);
1503 FlowEntity flow = MDSALUtil.buildFlowEntity(dpId, NwConstants.ELAN_DMAC_TABLE, flowId, 20, displayName, 0, 0,
1504 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)),
1505 matches, instructions);
1509 public String getExternalElanInterface(String elanInstanceName, BigInteger dpnId) {
1510 DpnInterfaces dpnInterfaces = getElanInterfaceInfoByElanDpn(elanInstanceName, dpnId);
1511 if (dpnInterfaces == null || dpnInterfaces.getInterfaces() == null) {
1512 LOG.trace("Elan {} does not have interfaces in DPN {}", elanInstanceName, dpnId);
1516 for (String dpnInterface : dpnInterfaces.getInterfaces()) {
1517 if (interfaceManager.isExternalInterface(dpnInterface)) {
1518 return dpnInterface;
1522 LOG.trace("Elan {} does not have any external interace attached to DPN {}", elanInstanceName, dpnId);
1526 public static String getElanMacDPNKey(long elanTag, String macAddress, BigInteger dpnId) {
1527 String elanMacDmacDpnKey = "MAC-" + macAddress + " ELAN_TAG-" + elanTag + "DPN_ID-" + dpnId;
1528 return elanMacDmacDpnKey.intern();
1531 public static String getElanMacKey(long elanTag, String macAddress) {
1532 String elanMacKey = "MAC-" + macAddress + " ELAN_TAG-" + elanTag;
1533 return elanMacKey.intern();
1536 // TODO This should return a collection of futures
1537 public static void addToListenableFutureIfTxException(RuntimeException exception,
1538 List<ListenableFuture<Void>> futures) {
1539 Throwable cause = exception.getCause();
1540 if (cause != null && cause instanceof TransactionCommitFailedException) {
1541 futures.add(Futures.immediateFailedCheckedFuture((TransactionCommitFailedException) cause));
1545 public static List<PhysAddress> getPhysAddress(List<String> macAddress) {
1546 Preconditions.checkNotNull(macAddress, "macAddress cannot be null");
1547 List<PhysAddress> physAddresses = new ArrayList<>();
1548 for (String mac : macAddress) {
1549 physAddresses.add(new PhysAddress(mac));
1551 return physAddresses;
1554 public static List<StaticMacEntries> getStaticMacEntries(List<String> staticMacAddresses) {
1555 if (isEmpty(staticMacAddresses)) {
1556 return Collections.EMPTY_LIST;
1558 StaticMacEntriesBuilder staticMacEntriesBuilder = new StaticMacEntriesBuilder();
1559 List<StaticMacEntries> staticMacEntries = new ArrayList<>();
1560 List<PhysAddress> physAddressList = getPhysAddress(staticMacAddresses);
1561 for (PhysAddress physAddress : physAddressList) {
1562 staticMacEntries.add(staticMacEntriesBuilder.setMacAddress(physAddress).build());
1564 return staticMacEntries;
1567 public static InstanceIdentifier<StaticMacEntries> getStaticMacEntriesCfgDataPathIdentifier(String interfaceName,
1568 String macAddress) {
1569 return InstanceIdentifier.builder(ElanInterfaces.class)
1570 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).child(StaticMacEntries.class,
1571 new StaticMacEntriesKey(new PhysAddress(macAddress))).build();
1574 public static List<StaticMacEntries> getDeletedEntries(List<StaticMacEntries> originalStaticMacEntries,
1575 List<StaticMacEntries> updatedStaticMacEntries) {
1576 if (isEmpty(originalStaticMacEntries)) {
1577 return Collections.EMPTY_LIST;
1579 List<StaticMacEntries> deleted = Lists.newArrayList(originalStaticMacEntries);
1580 if (isNotEmpty(updatedStaticMacEntries)) {
1581 deleted.removeAll(updatedStaticMacEntries);
1586 public static <T> List<T> diffOf(List<T> orig, List<T> updated) {
1587 if (isEmpty(orig)) {
1588 return Collections.EMPTY_LIST;
1590 List<T> diff = Lists.newArrayList(orig);
1591 if (isNotEmpty(updated)) {
1592 diff.removeAll(updated);
1597 public static void segregateToBeDeletedAndAddEntries(List<StaticMacEntries> originalStaticMacEntries,
1598 List<StaticMacEntries> updatedStaticMacEntries) {
1599 if (isNotEmpty(updatedStaticMacEntries)) {
1600 List<StaticMacEntries> existingClonedStaticMacEntries = new ArrayList<>();
1601 if (isNotEmpty(originalStaticMacEntries)) {
1602 existingClonedStaticMacEntries.addAll(0, originalStaticMacEntries);
1603 originalStaticMacEntries.removeAll(updatedStaticMacEntries);
1604 updatedStaticMacEntries.removeAll(existingClonedStaticMacEntries);
1609 public static boolean isEmpty(Collection collection) {
1610 return collection == null || collection.isEmpty();
1613 public static boolean isNotEmpty(Collection collection) {
1614 return !isEmpty(collection);
1617 public Optional<IpAddress> getSourceIpAddress(Ethernet ethernet) {
1618 Optional<IpAddress> srcIpAddress = Optional.absent();
1619 if (ethernet.getPayload() == null) {
1620 return srcIpAddress;
1622 byte[] ipAddrBytes = null;
1623 if (ethernet.getPayload() instanceof IPv4) {
1624 IPv4 ipv4 = (IPv4) ethernet.getPayload();
1625 ipAddrBytes = Ints.toByteArray(ipv4.getSourceAddress());
1626 } else if (ethernet.getPayload() instanceof ARP) {
1627 ipAddrBytes = ((ARP) ethernet.getPayload()).getSenderProtocolAddress();
1629 if (ipAddrBytes != null) {
1630 String ipAddr = NWUtil.toStringIpAddress(ipAddrBytes);
1631 return Optional.of(IpAddressBuilder.getDefaultInstance(ipAddr));
1633 return srcIpAddress;
1636 public List<MacEntry> getElanMacEntries(String elanName) {
1637 MacTable macTable = getElanMacTable(elanName);
1638 if (macTable == null) {
1639 return Collections.emptyList();
1641 return macTable.getMacEntry();
1644 public boolean isTunnelInLogicalGroup(String interfaceName) {
1645 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1646 .ietf.interfaces.rev140508.interfaces.Interface configIface =
1647 interfaceManager.getInterfaceInfoFromConfigDataStore(interfaceName);
1648 IfTunnel ifTunnel = configIface.getAugmentation(IfTunnel.class);
1649 if (ifTunnel != null && ifTunnel.getTunnelInterfaceType().isAssignableFrom(TunnelTypeVxlan.class)) {
1650 ParentRefs refs = configIface.getAugmentation(ParentRefs.class);
1651 if (refs != null && !Strings.isNullOrEmpty(refs.getParentInterface())) {
1652 return true; //multiple VxLAN tunnels enabled, i.e. only logical tunnel should be treated
1658 public static void addElanInterfaceToElanInstanceCache(String elanInstanceName, String elanInterfaceName) {
1659 elanInstanceToInterfacesCache.computeIfAbsent(elanInstanceName, key -> new HashSet<>()).add(elanInterfaceName);
1662 public static void removeElanInterfaceToElanInstanceCache(String elanInstanceName, String interfaceName) {
1663 Set<String> elanInterfaces = elanInstanceToInterfacesCache.get(elanInstanceName);
1664 if (elanInterfaces == null || elanInterfaces.isEmpty()) {
1667 elanInterfaces.remove(interfaceName);
1670 @Nonnull public static Set<String> removeAndGetElanInterfaces(String elanInstanceName) {
1671 Set<String> removed = elanInstanceToInterfacesCache.remove(elanInstanceName);
1672 return removed != null ? removed : Collections.emptySet();
1675 public static InstanceIdentifier<Flow> getFlowIid(Flow flow, BigInteger dpnId) {
1676 FlowKey flowKey = new FlowKey(new FlowId(flow.getId()));
1677 org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId nodeId =
1678 new org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId("openflow:" + dpnId);
1679 org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node nodeDpn =
1680 new NodeBuilder().setId(nodeId).setKey(new NodeKey(nodeId)).build();
1681 return InstanceIdentifier.builder(Nodes.class)
1682 .child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node.class,
1683 nodeDpn.getKey()).augmentation(FlowCapableNode.class)
1684 .child(Table.class, new TableKey(flow.getTableId())).child(Flow.class, flowKey).build();
1687 public static String getElanInterfaceJobKey(String interfaceName) {
1688 return "elaninterface-" + interfaceName;
1691 public void removeArpResponderFlow(BigInteger dpnId, String ingressInterfaceName, String ipAddress,
1693 LOG.info("Removing the ARP responder flow on DPN {} of Interface {} with IP {}", dpnId, ingressInterfaceName,
1695 ArpResponderUtil.removeFlow(mdsalManager, dpnId, ArpResponderUtil.getFlowId(lportTag, ipAddress));