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.collect.Lists;
13 import com.google.common.util.concurrent.CheckedFuture;
14 import com.google.common.util.concurrent.FutureCallback;
15 import com.google.common.util.concurrent.Futures;
16 import com.google.common.util.concurrent.ListenableFuture;
18 import java.math.BigInteger;
19 import java.util.ArrayList;
20 import java.util.Collection;
21 import java.util.Collections;
22 import java.util.HashSet;
23 import java.util.List;
26 import java.util.concurrent.ConcurrentHashMap;
27 import java.util.concurrent.ExecutionException;
28 import java.util.concurrent.Future;
29 import javax.inject.Inject;
30 import javax.inject.Singleton;
31 import org.apache.commons.lang3.StringUtils;
32 import org.opendaylight.controller.liblldp.NetUtils;
33 import org.opendaylight.controller.liblldp.PacketException;
34 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
35 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
36 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
37 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService;
38 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
39 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
40 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
41 import org.opendaylight.genius.interfacemanager.globals.InterfaceInfo;
42 import org.opendaylight.genius.interfacemanager.globals.InterfaceServiceUtil;
43 import org.opendaylight.genius.interfacemanager.interfaces.IInterfaceManager;
44 import org.opendaylight.genius.itm.globals.ITMConstants;
45 import org.opendaylight.genius.mdsalutil.ActionInfo;
46 import org.opendaylight.genius.mdsalutil.FlowEntity;
47 import org.opendaylight.genius.mdsalutil.InstructionInfo;
48 import org.opendaylight.genius.mdsalutil.MDSALUtil;
49 import org.opendaylight.genius.mdsalutil.MDSALUtil.MdsalOp;
50 import org.opendaylight.genius.mdsalutil.MatchInfo;
51 import org.opendaylight.genius.mdsalutil.MetaDataUtil;
52 import org.opendaylight.genius.mdsalutil.NWUtil;
53 import org.opendaylight.genius.mdsalutil.NwConstants;
54 import org.opendaylight.genius.mdsalutil.actions.ActionNxResubmit;
55 import org.opendaylight.genius.mdsalutil.instructions.InstructionApplyActions;
56 import org.opendaylight.genius.mdsalutil.instructions.InstructionGotoTable;
57 import org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager;
58 import org.opendaylight.genius.mdsalutil.matches.MatchEthernetDestination;
59 import org.opendaylight.genius.mdsalutil.matches.MatchEthernetSource;
60 import org.opendaylight.genius.mdsalutil.matches.MatchMetadata;
61 import org.opendaylight.genius.mdsalutil.matches.MatchTunnelId;
62 import org.opendaylight.genius.mdsalutil.packet.ARP;
63 import org.opendaylight.genius.mdsalutil.packet.Ethernet;
64 import org.opendaylight.genius.mdsalutil.packet.IPv4;
65 import org.opendaylight.genius.utils.ServiceIndex;
66 import org.opendaylight.netvirt.elan.ElanException;
67 import org.opendaylight.netvirt.elan.internal.ElanInstanceManager;
68 import org.opendaylight.netvirt.elan.internal.ElanInterfaceManager;
69 import org.opendaylight.netvirt.elan.l2gw.utils.ElanL2GatewayMulticastUtils;
70 import org.opendaylight.netvirt.elan.l2gw.utils.ElanL2GatewayUtils;
71 import org.opendaylight.netvirt.elan.l2gw.utils.L2GatewayConnectionUtils;
72 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
73 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddressBuilder;
74 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfacesState;
75 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface;
76 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.AdminStatus;
77 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.OperStatus;
78 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
79 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.PhysAddress;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInput;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInputBuilder;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdOutput;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdManagerService;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInput;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInputBuilder;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406.IfIndexesInterfaceMap;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._if.indexes._interface.map.IfIndexInterface;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._if.indexes._interface.map.IfIndexInterfaceKey;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeBase;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeVxlan;
96 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetDpidFromInterfaceInputBuilder;
97 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetDpidFromInterfaceOutput;
98 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceInput;
99 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceInputBuilder;
100 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceOutput;
101 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.OdlInterfaceRpcService;
102 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceBindings;
103 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceModeIngress;
104 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceTypeFlowBased;
105 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflow;
106 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflowBuilder;
107 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.ServicesInfo;
108 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.ServicesInfoKey;
109 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServices;
110 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesBuilder;
111 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesKey;
112 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.ExternalTunnelList;
113 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnel;
114 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnelKey;
115 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.CreateTerminatingServiceActionsInput;
116 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.CreateTerminatingServiceActionsInputBuilder;
117 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.GetExternalTunnelInterfaceNameInput;
118 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.GetExternalTunnelInterfaceNameInputBuilder;
119 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.GetExternalTunnelInterfaceNameOutput;
120 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.GetTunnelInterfaceNameInput;
121 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.GetTunnelInterfaceNameInputBuilder;
122 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.GetTunnelInterfaceNameOutput;
123 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.ItmRpcService;
124 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsInput;
125 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsInputBuilder;
126 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
127 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
128 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
129 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
130 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInstance;
131 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInstanceBuilder;
132 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInterface;
133 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInterface.EtreeInterfaceType;
134 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTag;
135 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTagName;
136 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTagNameBuilder;
137 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanDpnInterfaces;
138 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanForwardingTables;
139 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInstances;
140 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaceForwardingEntries;
141 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaces;
142 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanState;
143 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanTagNameMap;
144 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeFlat;
145 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeVlan;
146 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeVxlan;
147 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan._interface.forwarding.entries.ElanInterfaceMac;
148 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan._interface.forwarding.entries.ElanInterfaceMacKey;
149 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesList;
150 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesListKey;
151 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfaces;
152 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfacesKey;
153 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTable;
154 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTableBuilder;
155 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTableKey;
156 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstance;
157 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstanceBuilder;
158 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstanceKey;
159 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.elan.instance.ElanSegments;
160 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterface;
161 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterfaceKey;
162 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntries;
163 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntriesBuilder;
164 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntriesKey;
165 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.Elan;
166 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.ElanBuilder;
167 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.ElanKey;
168 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagName;
169 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagNameBuilder;
170 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagNameKey;
171 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntry;
172 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntryBuilder;
173 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntryKey;
174 import org.opendaylight.yangtools.yang.binding.DataObject;
175 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
176 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.InstanceIdentifierBuilder;
177 import org.opendaylight.yangtools.yang.common.RpcResult;
178 import org.slf4j.Logger;
179 import org.slf4j.LoggerFactory;
182 public class ElanUtils {
184 private static final Logger LOG = LoggerFactory.getLogger(ElanUtils.class);
186 private static Map<String, ElanInstance> elanInstanceLocalCache = new ConcurrentHashMap<>();
187 private static Map<String, ElanInterface> elanInterfaceLocalCache = new ConcurrentHashMap<>();
188 private static Map<String, Set<DpnInterfaces>> elanInstancToDpnsCache = new ConcurrentHashMap<>();
190 private final DataBroker broker;
191 private final IMdsalApiManager mdsalManager;
192 private final ElanInstanceManager elanInstanceManager;
193 private final OdlInterfaceRpcService interfaceManagerRpcService;
194 private final ItmRpcService itmRpcService;
195 private final ElanL2GatewayUtils elanL2GatewayUtils;
196 private final ElanL2GatewayMulticastUtils elanL2GatewayMulticastUtils;
197 private final L2GatewayConnectionUtils l2GatewayConnectionUtils;
198 private final IInterfaceManager interfaceManager;
200 public static final FutureCallback<Void> DEFAULT_CALLBACK = new FutureCallback<Void>() {
202 public void onSuccess(Void result) {
203 LOG.debug("Success in Datastore operation");
207 public void onFailure(Throwable error) {
208 LOG.error("Error in Datastore operation", error);
213 public ElanUtils(DataBroker dataBroker, IMdsalApiManager mdsalManager, ElanInstanceManager elanInstanceManager,
214 OdlInterfaceRpcService interfaceManagerRpcService, ItmRpcService itmRpcService,
215 ElanInterfaceManager elanInterfaceManager,
216 EntityOwnershipService entityOwnershipService, IInterfaceManager interfaceManager) {
217 this.broker = dataBroker;
218 this.mdsalManager = mdsalManager;
219 this.elanInstanceManager = elanInstanceManager;
220 this.interfaceManagerRpcService = interfaceManagerRpcService;
221 this.itmRpcService = itmRpcService;
222 this.interfaceManager = interfaceManager;
224 elanL2GatewayMulticastUtils =
225 new ElanL2GatewayMulticastUtils(broker, elanInstanceManager, elanInterfaceManager, this);
226 elanL2GatewayUtils = new ElanL2GatewayUtils(broker, itmRpcService, this,
227 entityOwnershipService, elanL2GatewayMulticastUtils);
228 elanL2GatewayMulticastUtils.setEElanL2GatewayUtils(elanL2GatewayUtils);
229 l2GatewayConnectionUtils = new L2GatewayConnectionUtils(broker,
230 elanInstanceManager, entityOwnershipService, this);
233 public void close() {
234 elanL2GatewayUtils.close();
237 public ElanL2GatewayUtils getElanL2GatewayUtils() {
238 return elanL2GatewayUtils;
241 public ElanL2GatewayMulticastUtils getElanL2GatewayMulticastUtils() {
242 return elanL2GatewayMulticastUtils;
245 public L2GatewayConnectionUtils getL2GatewayConnectionUtils() {
246 return l2GatewayConnectionUtils;
249 public static void addElanInstanceIntoCache(String elanInstanceName, ElanInstance elanInstance) {
250 elanInstanceLocalCache.put(elanInstanceName, elanInstance);
253 public static void removeElanInstanceFromCache(String elanInstanceName) {
254 elanInstanceLocalCache.remove(elanInstanceName);
257 public static ElanInstance getElanInstanceFromCache(String elanInstanceName) {
258 return elanInstanceLocalCache.get(elanInstanceName);
261 public static Set<String> getAllElanNames() {
262 return elanInstanceLocalCache.keySet();
265 public static void addElanInterfaceIntoCache(String interfaceName, ElanInterface elanInterface) {
266 elanInterfaceLocalCache.put(interfaceName, elanInterface);
269 public static void removeElanInterfaceFromCache(String interfaceName) {
270 elanInterfaceLocalCache.remove(interfaceName);
273 public static ElanInterface getElanInterfaceFromCache(String interfaceName) {
274 return elanInterfaceLocalCache.get(interfaceName);
278 * Uses the IdManager to retrieve a brand new ElanTag.
284 * @return the integer
286 public static Long retrieveNewElanTag(IdManagerService idManager, String idKey) {
288 AllocateIdInput getIdInput = new AllocateIdInputBuilder().setPoolName(ElanConstants.ELAN_ID_POOL_NAME)
289 .setIdKey(idKey).build();
292 Future<RpcResult<AllocateIdOutput>> result = idManager.allocateId(getIdInput);
293 RpcResult<AllocateIdOutput> rpcResult = result.get();
294 if (rpcResult.isSuccessful()) {
295 return rpcResult.getResult().getIdValue();
297 LOG.warn("RPC Call to Allocate Id returned with Errors {}", rpcResult.getErrors());
299 } catch (InterruptedException | ExecutionException e) {
300 LOG.warn("Exception when Allocating Id", e);
305 public static void releaseId(IdManagerService idManager, String poolName, String idKey) {
306 ReleaseIdInput releaseIdInput = new ReleaseIdInputBuilder().setPoolName(poolName).setIdKey(idKey).build();
307 Future<RpcResult<Void>> result = idManager.releaseId(releaseIdInput);
313 * @deprecated Consider using {@link #read2(LogicalDatastoreType, InstanceIdentifier)} with proper exception
317 @SuppressWarnings("checkstyle:IllegalCatch")
318 public <T extends DataObject> Optional<T> read(DataBroker broker, LogicalDatastoreType datastoreType,
319 InstanceIdentifier<T> path) {
320 try (ReadOnlyTransaction tx = broker != null ? broker.newReadOnlyTransaction()
321 : this.broker.newReadOnlyTransaction()) {
322 return tx.read(datastoreType, path).get();
323 } catch (Exception e) {
324 throw new RuntimeException(e);
328 public <T extends DataObject> Optional<T> read2(LogicalDatastoreType datastoreType, InstanceIdentifier<T> path)
329 throws ReadFailedException {
330 try (ReadOnlyTransaction tx = broker.newReadOnlyTransaction()) {
331 CheckedFuture<Optional<T>, ReadFailedException> checkedFuture = tx.read(datastoreType, path);
332 return checkedFuture.checkedGet();
336 public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
337 InstanceIdentifier<T> path) {
338 WriteTransaction tx = broker.newWriteOnlyTransaction();
339 tx.delete(datastoreType, path);
340 Futures.addCallback(tx.submit(), DEFAULT_CALLBACK);
343 public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
344 InstanceIdentifier<T> path, FutureCallback<Void> callback) {
345 WriteTransaction tx = broker.newWriteOnlyTransaction();
346 tx.delete(datastoreType, path);
347 Futures.addCallback(tx.submit(), callback);
350 public static InstanceIdentifier<ElanInstance> getElanInstanceIdentifier() {
351 return InstanceIdentifier.builder(ElanInstances.class).child(ElanInstance.class).build();
354 // elan-instances config container
355 public static ElanInstance getElanInstanceByName(DataBroker broker, String elanInstanceName) {
356 ElanInstance elanObj = getElanInstanceFromCache(elanInstanceName);
357 if (elanObj != null) {
360 InstanceIdentifier<ElanInstance> elanIdentifierId = getElanInstanceConfigurationDataPath(elanInstanceName);
361 return MDSALUtil.read(broker, LogicalDatastoreType.CONFIGURATION, elanIdentifierId).orNull();
364 public static InstanceIdentifier<ElanInstance> getElanInstanceConfigurationDataPath(String elanInstanceName) {
365 return InstanceIdentifier.builder(ElanInstances.class)
366 .child(ElanInstance.class, new ElanInstanceKey(elanInstanceName)).build();
369 // elan-interfaces Config Container
370 public static ElanInterface getElanInterfaceByElanInterfaceName(DataBroker broker, String elanInterfaceName) {
371 ElanInterface elanInterfaceObj = getElanInterfaceFromCache(elanInterfaceName);
372 if (elanInterfaceObj != null) {
373 return elanInterfaceObj;
375 InstanceIdentifier<ElanInterface> elanInterfaceId = getElanInterfaceConfigurationDataPathId(elanInterfaceName);
376 return MDSALUtil.read(broker, LogicalDatastoreType.CONFIGURATION, elanInterfaceId).orNull();
379 public static EtreeInterface getEtreeInterfaceByElanInterfaceName(DataBroker broker, String elanInterfaceName) {
380 ElanInterface elanInterface = getElanInterfaceByElanInterfaceName(broker, elanInterfaceName);
381 if (elanInterface == null) {
384 return elanInterface.getAugmentation(EtreeInterface.class);
388 public static InstanceIdentifier<ElanInterface> getElanInterfaceConfigurationDataPathId(String interfaceName) {
389 return InstanceIdentifier.builder(ElanInterfaces.class)
390 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).build();
393 // elan-state Operational container
394 public static Elan getElanByName(DataBroker broker, String elanInstanceName) {
395 InstanceIdentifier<Elan> elanIdentifier = getElanInstanceOperationalDataPath(elanInstanceName);
396 return MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL, elanIdentifier).orNull();
399 public static InstanceIdentifier<Elan> getElanInstanceOperationalDataPath(String elanInstanceName) {
400 return InstanceIdentifier.builder(ElanState.class).child(Elan.class, new ElanKey(elanInstanceName)).build();
403 // grouping of forwarding-entries
404 public MacEntry getInterfaceMacEntriesOperationalDataPath(String interfaceName, PhysAddress physAddress) {
405 InstanceIdentifier<MacEntry> existingMacEntryId = getInterfaceMacEntriesIdentifierOperationalDataPath(
406 interfaceName, physAddress);
407 return read(broker, LogicalDatastoreType.OPERATIONAL, existingMacEntryId).orNull();
410 public MacEntry getInterfaceMacEntriesOperationalDataPathFromId(InstanceIdentifier identifier) {
411 Optional<MacEntry> existingInterfaceMacEntry = read(broker,
412 LogicalDatastoreType.OPERATIONAL, identifier);
413 return existingInterfaceMacEntry.orNull();
416 public static InstanceIdentifier<MacEntry> getInterfaceMacEntriesIdentifierOperationalDataPath(String interfaceName,
417 PhysAddress physAddress) {
418 return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class)
419 .child(ElanInterfaceMac.class, new ElanInterfaceMacKey(interfaceName))
420 .child(MacEntry.class, new MacEntryKey(physAddress)).build();
424 // elan-forwarding-tables Operational container
425 public Optional<MacEntry> getMacEntryForElanInstance(String elanName, PhysAddress physAddress) {
426 InstanceIdentifier<MacEntry> macId = getMacEntryOperationalDataPath(elanName, physAddress);
427 return read(broker, LogicalDatastoreType.OPERATIONAL, macId);
430 public MacEntry getMacEntryFromElanMacId(InstanceIdentifier identifier) {
431 Optional<MacEntry> existingInterfaceMacEntry = read(broker,
432 LogicalDatastoreType.OPERATIONAL, identifier);
433 return existingInterfaceMacEntry.orNull();
436 public static InstanceIdentifier<MacEntry> getMacEntryOperationalDataPath(String elanName,
437 PhysAddress physAddress) {
438 return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class, new MacTableKey(elanName))
439 .child(MacEntry.class, new MacEntryKey(physAddress)).build();
442 public static InstanceIdentifier<MacTable> getElanMacTableOperationalDataPath(String elanName) {
443 return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class, new MacTableKey(elanName))
447 // elan-interface-forwarding-entries Operational container
448 public ElanInterfaceMac getElanInterfaceMacByInterfaceName(String interfaceName) {
449 InstanceIdentifier<ElanInterfaceMac> elanInterfaceId = getElanInterfaceMacEntriesOperationalDataPath(
451 return read(broker, LogicalDatastoreType.OPERATIONAL, elanInterfaceId).orNull();
455 * Gets the elan interface mac addresses.
457 * @param interfaceName
459 * @return the elan interface mac addresses
461 public List<PhysAddress> getElanInterfaceMacAddresses(String interfaceName) {
462 List<PhysAddress> macAddresses = new ArrayList<>();
463 ElanInterfaceMac elanInterfaceMac = getElanInterfaceMacByInterfaceName(interfaceName);
464 if (elanInterfaceMac != null && elanInterfaceMac.getMacEntry() != null) {
465 List<MacEntry> macEntries = elanInterfaceMac.getMacEntry();
466 for (MacEntry macEntry : macEntries) {
467 macAddresses.add(macEntry.getMacAddress());
473 public static InstanceIdentifier<ElanInterfaceMac> getElanInterfaceMacEntriesOperationalDataPath(
474 String interfaceName) {
475 return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class)
476 .child(ElanInterfaceMac.class, new ElanInterfaceMacKey(interfaceName)).build();
480 * Returns the list of Interfaces that belong to an Elan on an specific DPN.
481 * Data retrieved from Elan's operational DS: elan-dpn-interfaces container
483 * @param elanInstanceName
484 * name of the Elan to which the interfaces must belong to
486 * Id of the DPN where the interfaces are located
487 * @return the elan interface Info
489 public DpnInterfaces getElanInterfaceInfoByElanDpn(String elanInstanceName, BigInteger dpId) {
490 InstanceIdentifier<DpnInterfaces> elanDpnInterfacesId = getElanDpnInterfaceOperationalDataPath(elanInstanceName,
492 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfacesId).orNull();
496 * Returns the InstanceIdentifier that points to the Interfaces of an Elan
497 * in a given DPN in the Operational DS. Data retrieved from Elans's
498 * operational DS: dpn-interfaces list
500 * @param elanInstanceName
501 * name of the Elan to which the interfaces must belong to
503 * Id of the DPN where the interfaces are located
504 * @return the elan dpn interface
506 public static InstanceIdentifier<DpnInterfaces> getElanDpnInterfaceOperationalDataPath(String elanInstanceName,
508 return InstanceIdentifier.builder(ElanDpnInterfaces.class)
509 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName))
510 .child(DpnInterfaces.class, new DpnInterfacesKey(dpId)).build();
513 // elan-tag-name-map Operational Container
514 public ElanTagName getElanInfoByElanTag(long elanTag) {
515 InstanceIdentifier<ElanTagName> elanId = getElanInfoEntriesOperationalDataPath(elanTag);
516 Optional<ElanTagName> existingElanInfo = read(broker,
517 LogicalDatastoreType.OPERATIONAL, elanId);
518 return existingElanInfo.orNull();
521 public EtreeLeafTagName getEtreeLeafTagByElanTag(long elanTag) {
522 InstanceIdentifier<ElanTagName> elanId = getElanInfoEntriesOperationalDataPath(elanTag);
523 Optional<ElanTagName> existingElanInfo = read(broker,
524 LogicalDatastoreType.OPERATIONAL, elanId);
525 if (existingElanInfo.isPresent()) {
526 ElanTagName elanTagName = existingElanInfo.get();
527 return elanTagName.getAugmentation(EtreeLeafTagName.class);
532 public static InstanceIdentifier<ElanTagName> getElanInfoEntriesOperationalDataPath(long elanTag) {
533 return InstanceIdentifier.builder(ElanTagNameMap.class).child(ElanTagName.class, new ElanTagNameKey(elanTag))
537 // interface-index-tag operational container
538 public Optional<IfIndexInterface> getInterfaceInfoByInterfaceTag(long interfaceTag) {
539 InstanceIdentifier<IfIndexInterface> interfaceId = getInterfaceInfoEntriesOperationalDataPath(interfaceTag);
540 return read(broker, LogicalDatastoreType.OPERATIONAL, interfaceId);
543 public static InstanceIdentifier<IfIndexInterface> getInterfaceInfoEntriesOperationalDataPath(long interfaceTag) {
544 return InstanceIdentifier.builder(IfIndexesInterfaceMap.class)
545 .child(IfIndexInterface.class, new IfIndexInterfaceKey((int) interfaceTag)).build();
548 public static InstanceIdentifier<ElanDpnInterfacesList> getElanDpnOperationDataPath(String elanInstanceName) {
549 return InstanceIdentifier.builder(ElanDpnInterfaces.class)
550 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName)).build();
553 public ElanDpnInterfacesList getElanDpnInterfacesList(String elanName) {
554 InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanName);
555 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orNull();
558 public ElanDpnInterfaces getElanDpnInterfacesList() {
559 InstanceIdentifier<ElanDpnInterfaces> elanDpnInterfaceId = InstanceIdentifier.builder(ElanDpnInterfaces.class)
561 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orNull();
565 * This method is useful get all ELAN participating CSS dpIds to install
566 * program remote dmac entries and updating remote bc groups for tor
569 * @param elanInstanceName
570 * the elan instance name
571 * @return list of dpIds
573 public List<BigInteger> getParticipatingDpnsInElanInstance(String elanInstanceName) {
574 List<BigInteger> dpIds = new ArrayList<>();
575 InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
576 Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = read(broker,
577 LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
578 if (!existingElanDpnInterfaces.isPresent()) {
581 List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().getDpnInterfaces();
582 for (DpnInterfaces dpnInterface : dpnInterfaces) {
583 dpIds.add(dpnInterface.getDpId());
589 * To check given dpId is already present in Elan instance. This can be used
590 * to program flow entry in external tunnel table when a new access port
591 * added for first time into the ELAN instance
595 * @param elanInstanceName
596 * the elan instance name
597 * @return true if dpId is already present, otherwise return false
599 public boolean isDpnAlreadyPresentInElanInstance(BigInteger dpId, String elanInstanceName) {
600 InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
601 Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = read(broker,
602 LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
603 if (!existingElanDpnInterfaces.isPresent()) {
606 List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().getDpnInterfaces();
607 for (DpnInterfaces dpnInterface : dpnInterfaces) {
608 if (dpnInterface.getDpId().equals(dpId)) {
615 public ElanForwardingTables getElanForwardingList() {
616 InstanceIdentifier<ElanForwardingTables> elanForwardingTableId = InstanceIdentifier
617 .builder(ElanForwardingTables.class).build();
618 return read(broker, LogicalDatastoreType.OPERATIONAL, elanForwardingTableId).orNull();
621 public static long getElanRemoteBroadCastGroupID(long elanTag) {
622 return ElanConstants.ELAN_GID_MIN + elanTag % ElanConstants.ELAN_GID_MIN * 2;
626 * Gets the elan mac table.
630 * @return the elan mac table
632 public MacTable getElanMacTable(String elanName) {
633 InstanceIdentifier<MacTable> elanMacTableId = getElanMacTableOperationalDataPath(elanName);
634 return read(broker, LogicalDatastoreType.OPERATIONAL, elanMacTableId).orNull();
637 public static long getElanLocalBCGId(long elanTag) {
638 return ElanConstants.ELAN_GID_MIN + (elanTag % ElanConstants.ELAN_GID_MIN * 2 - 1);
641 public static long getElanRemoteBCGId(long elanTag) {
642 return ElanConstants.ELAN_GID_MIN + elanTag % ElanConstants.ELAN_GID_MIN * 2;
645 public static long getEtreeLeafLocalBCGId(long etreeLeafTag) {
646 return ElanConstants.ELAN_GID_MIN + (etreeLeafTag % ElanConstants.ELAN_GID_MIN * 2 - 1);
649 public static long getEtreeLeafRemoteBCGId(long etreeLeafTag) {
650 return ElanConstants.ELAN_GID_MIN + etreeLeafTag % ElanConstants.ELAN_GID_MIN * 2;
653 public static BigInteger getElanMetadataLabel(long elanTag) {
654 return MetaDataUtil.getElanTagMetadata(elanTag);
657 public static BigInteger getElanMetadataLabel(long elanTag, boolean isSHFlagSet) {
658 int shBit = isSHFlagSet ? 1 : 0;
659 return BigInteger.valueOf(elanTag).shiftLeft(24).or(BigInteger.valueOf(shBit));
662 public static BigInteger getElanMetadataLabel(long elanTag, int lportTag) {
663 return getElanMetadataLabel(elanTag).or(MetaDataUtil.getLportTagMetaData(lportTag));
666 public static BigInteger getElanMetadataMask() {
667 return MetaDataUtil.METADATA_MASK_SERVICE.or(MetaDataUtil.METADATA_MASK_LPORT_TAG);
671 * Setting INTERNAL_TUNNEL_TABLE, SMAC, DMAC, UDMAC in this DPN and optionally in other DPNs.
675 * @param interfaceInfo
681 * @param configureRemoteFlows
682 * true if remote dmac flows should be configured as well
683 * @param writeFlowGroupTx
685 * @throws ElanException in case of issues creating the flow objects
687 public void setupMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo,
688 long macTimeout, String macAddress, boolean configureRemoteFlows,
689 WriteTransaction writeFlowGroupTx) throws ElanException {
690 synchronized (getElanMacDPNKey(elanInfo.getElanTag(), macAddress, interfaceInfo.getDpId())) {
691 setupKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress, mdsalManager,
693 setupOrigDmacFlows(elanInfo, interfaceInfo, macAddress, configureRemoteFlows, mdsalManager,
694 broker, writeFlowGroupTx);
698 public void setupDMacFlowonRemoteDpn(ElanInstance elanInfo, InterfaceInfo interfaceInfo, BigInteger dstDpId,
699 String macAddress, WriteTransaction writeFlowTx) throws ElanException {
700 String elanInstanceName = elanInfo.getElanInstanceName();
701 setupRemoteDmacFlow(dstDpId, interfaceInfo.getDpId(), interfaceInfo.getInterfaceTag(),
702 elanInfo.getElanTag(), macAddress, elanInstanceName, writeFlowTx,
703 interfaceInfo.getInterfaceName(), elanInfo);
704 LOG.info("Remote Dmac flow entry created for elan Name:{}, logical port Name:{} and"
705 + " mac address {} on dpn:{}", elanInstanceName, interfaceInfo.getPortName(),
706 macAddress, dstDpId);
710 * Inserts a Flow in SMAC table to state that the MAC has already been
713 private void setupKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
714 String macAddress, IMdsalApiManager mdsalApiManager, WriteTransaction writeFlowGroupTx) {
715 FlowEntity flowEntity = buildKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress);
716 mdsalApiManager.addFlowToTx(flowEntity, writeFlowGroupTx);
717 LOG.debug("Known Smac flow entry created for elan Name:{}, logical Interface port:{} and mac address:{}",
718 elanInfo.getElanInstanceName(), elanInfo.getDescription(), macAddress);
721 public FlowEntity buildKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
723 int lportTag = interfaceInfo.getInterfaceTag();
724 // Matching metadata and eth_src fields
725 List<MatchInfo> mkMatches = new ArrayList<>();
726 mkMatches.add(new MatchMetadata(getElanMetadataLabel(elanInfo.getElanTag(), lportTag), getElanMetadataMask()));
727 mkMatches.add(new MatchEthernetSource(new MacAddress(macAddress)));
728 List<InstructionInfo> mkInstructions = new ArrayList<>();
729 mkInstructions.add(new InstructionGotoTable(NwConstants.ELAN_DMAC_TABLE));
731 BigInteger dpId = interfaceInfo.getDpId();
732 long elanTag = getElanTag(broker, elanInfo, interfaceInfo);
733 FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpId, NwConstants.ELAN_SMAC_TABLE,
734 getKnownDynamicmacFlowRef(NwConstants.ELAN_SMAC_TABLE, dpId, lportTag, macAddress, elanTag), 20,
735 elanInfo.getDescription(), (int) macTimeout, 0,
736 ElanConstants.COOKIE_ELAN_KNOWN_SMAC.add(BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
737 flowEntity.setStrictFlag(true);
738 flowEntity.setSendFlowRemFlag(macTimeout != 0); // If Mac timeout is 0,
741 // automatically, so no
742 // need to get notified
746 private static Long getElanTag(DataBroker broker, ElanInstance elanInfo, InterfaceInfo interfaceInfo) {
747 EtreeInterface etreeInterface = getEtreeInterfaceByElanInterfaceName(broker, interfaceInfo.getInterfaceName());
748 if (etreeInterface == null || etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
749 return elanInfo.getElanTag();
751 EtreeInstance etreeInstance = elanInfo.getAugmentation(EtreeInstance.class);
752 if (etreeInstance == null) {
753 LOG.warn("EtreeInterface {} is connected to a non-Etree network: {}",
754 interfaceInfo.getInterfaceName(), elanInfo.getElanInstanceName());
755 return elanInfo.getElanTag();
757 return etreeInstance.getEtreeLeafTagVal().getValue();
763 * Installs a Flow in INTERNAL_TUNNEL_TABLE of the affected DPN that sends
764 * the packet through the specified interface if the tunnel_id matches the
765 * interface's lportTag.
767 * @param interfaceInfo
769 * @param mdsalApiManager
770 * the mdsal API manager
771 * @param writeFlowGroupTx
772 * the writeFLowGroup tx
774 public void setupTermDmacFlows(InterfaceInfo interfaceInfo, IMdsalApiManager mdsalApiManager,
775 WriteTransaction writeFlowGroupTx) {
776 BigInteger dpId = interfaceInfo.getDpId();
777 int lportTag = interfaceInfo.getInterfaceTag();
778 Flow flow = MDSALUtil.buildFlowNew(NwConstants.INTERNAL_TUNNEL_TABLE,
779 getIntTunnelTableFlowRef(NwConstants.INTERNAL_TUNNEL_TABLE, lportTag), 5,
780 String.format("%s:%d", "ITM Flow Entry ", lportTag), 0, 0,
781 ITMConstants.COOKIE_ITM.add(BigInteger.valueOf(lportTag)),
782 getTunnelIdMatchForFilterEqualsLPortTag(lportTag),
783 getInstructionsInPortForOutGroup(interfaceInfo.getInterfaceName()));
784 mdsalApiManager.addFlowToTx(dpId, flow, writeFlowGroupTx);
785 LOG.debug("Terminating service table flow entry created on dpn:{} for logical Interface port:{}", dpId,
786 interfaceInfo.getPortName());
790 * Constructs the FlowName for flows installed in the Internal Tunnel Table,
791 * consisting in tableId + elanTag.
797 * @return the Internal tunnel
799 public static String getIntTunnelTableFlowRef(short tableId, int elanTag) {
800 return new StringBuffer().append(tableId).append(elanTag).toString();
804 * Constructs the Matches that checks that the tunnel_id field contains a
808 * lportTag that must be checked against the tunnel_id field
809 * @return the list of match Info
811 public static List<MatchInfo> getTunnelIdMatchForFilterEqualsLPortTag(int lportTag) {
812 List<MatchInfo> mkMatches = new ArrayList<>();
814 mkMatches.add(new MatchTunnelId(BigInteger.valueOf(lportTag)));
819 * Constructs the Instructions that take the packet over a given interface.
822 * Name of the interface where the packet must be sent over. It
823 * can be a local interface or a tunnel interface (internal or
825 * @return the Instruction
827 public List<Instruction> getInstructionsInPortForOutGroup(String ifName) {
828 List<Instruction> mkInstructions = new ArrayList<>();
829 List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
831 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
832 return mkInstructions;
836 * Returns the list of Actions to be taken when sending the packet through
837 * an Elan interface. Note that this interface can refer to an ElanInterface
838 * where the Elan VM is attached to a DPN or an ITM tunnel interface where
839 * Elan traffic can be sent through. In this latter case, the tunnelKey is
840 * mandatory and it can hold serviceId for internal tunnels or the VNI for
847 * @return the egress actions for interface
849 @SuppressWarnings("checkstyle:IllegalCatch")
850 public List<Action> getEgressActionsForInterface(String ifName, Long tunnelKey) {
851 List<Action> listAction = new ArrayList<>();
853 GetEgressActionsForInterfaceInput getEgressActionInput = new GetEgressActionsForInterfaceInputBuilder()
854 .setIntfName(ifName).setTunnelKey(tunnelKey).build();
855 Future<RpcResult<GetEgressActionsForInterfaceOutput>> result = interfaceManagerRpcService
856 .getEgressActionsForInterface(getEgressActionInput);
857 RpcResult<GetEgressActionsForInterfaceOutput> rpcResult = result.get();
858 if (!rpcResult.isSuccessful()) {
859 LOG.warn("RPC Call to Get egress actions for interface {} returned with Errors {}", ifName,
860 rpcResult.getErrors());
862 List<Action> actions = rpcResult.getResult().getAction();
863 listAction = actions;
865 } catch (Exception e) {
866 LOG.warn("Exception when egress actions for interface {}", ifName, e);
871 private void setupOrigDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
872 boolean configureRemoteFlows, IMdsalApiManager mdsalApiManager,
873 DataBroker broker, WriteTransaction writeFlowGroupTx)
874 throws ElanException {
875 BigInteger dpId = interfaceInfo.getDpId();
876 String ifName = interfaceInfo.getInterfaceName();
877 long ifTag = interfaceInfo.getInterfaceTag();
878 String elanInstanceName = elanInfo.getElanInstanceName();
880 Long elanTag = elanInfo.getElanTag();
882 setupLocalDmacFlow(elanTag, dpId, ifName, macAddress, elanInfo, mdsalApiManager, ifTag,
884 LOG.debug("Dmac flow entry created for elan Name:{}, logical port Name:{} mand mac address:{} "
885 + "on dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, dpId);
887 if (!configureRemoteFlows) {
891 List<DpnInterfaces> elanDpns = getInvolvedDpnsInElan(elanInstanceName);
892 if (elanDpns == null) {
896 for (DpnInterfaces elanDpn : elanDpns) {
898 if (elanDpn.getDpId().equals(dpId)) {
902 // Check for the Remote DPN present in Inventory Manager
903 if (!isDpnPresent(elanDpn.getDpId())) {
907 // For remote DPNs a flow is needed to indicate that
908 // packets of this ELAN going to this MAC
909 // need to be forwarded through the appropiated ITM
911 setupRemoteDmacFlow(elanDpn.getDpId(), // srcDpn (the remote DPN in this case)
912 dpId, // dstDpn (the local DPN)
913 interfaceInfo.getInterfaceTag(), // lportTag of the local interface
914 elanTag, // identifier of the Elan
915 macAddress, // MAC to be programmed in remote DPN
916 elanInstanceName, writeFlowGroupTx, ifName, elanInfo);
917 LOG.debug("Dmac flow entry created for elan Name:{}, logical port Name:{} and mac address:{} on"
918 + " dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, elanDpn.getDpId());
921 // TODO: Make sure that the same is performed against the ElanDevices.
924 @SuppressWarnings("unchecked")
925 public List<DpnInterfaces> getInvolvedDpnsInElan(String elanName) {
926 List<DpnInterfaces> dpns = elanInstanceManager.getElanDPNByName(elanName);
928 return Collections.emptyList();
933 private void setupLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
934 ElanInstance elanInfo, IMdsalApiManager mdsalApiManager, long ifTag, WriteTransaction writeFlowGroupTx) {
935 Flow flowEntity = buildLocalDmacFlowEntry(elanTag, dpId, ifName, macAddress, elanInfo, ifTag);
936 mdsalApiManager.addFlowToTx(dpId, flowEntity, writeFlowGroupTx);
937 installEtreeLocalDmacFlow(elanTag, dpId, ifName, macAddress, elanInfo,
938 mdsalApiManager, ifTag, writeFlowGroupTx);
941 private void installEtreeLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
942 ElanInstance elanInfo, IMdsalApiManager mdsalApiManager, long ifTag, WriteTransaction writeFlowGroupTx) {
943 EtreeInterface etreeInterface = getEtreeInterfaceByElanInterfaceName(broker, ifName);
944 if (etreeInterface != null) {
945 if (etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
946 EtreeLeafTagName etreeTagName = getEtreeLeafTagByElanTag(elanTag);
947 if (etreeTagName == null) {
948 LOG.warn("Interface {} seems like it belongs to Etree but etreeTagName from elanTag {} is null",
951 Flow flowEntity = buildLocalDmacFlowEntry(etreeTagName.getEtreeLeafTag().getValue(), dpId, ifName,
952 macAddress, elanInfo, ifTag);
953 mdsalApiManager.addFlowToTx(dpId, flowEntity, writeFlowGroupTx);
959 public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, long lporTag, String macAddress,
961 return new StringBuffer().append(tableId).append(elanTag).append(dpId).append(lporTag).append(macAddress)
965 public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, BigInteger remoteDpId,
966 String macAddress, long elanTag) {
967 return new StringBuffer().append(tableId).append(elanTag).append(dpId).append(remoteDpId).append(macAddress)
971 public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, String macAddress, long elanTag) {
972 return new StringBuffer().append(tableId).append(elanTag).append(dpId).append(macAddress).toString();
975 private static String getKnownDynamicmacFlowRef(short elanDmacTable, BigInteger dpId, String extDeviceNodeId,
976 String dstMacAddress, long elanTag, boolean shFlag) {
977 return new StringBuffer().append(elanDmacTable).append(elanTag).append(dpId).append(extDeviceNodeId)
978 .append(dstMacAddress).append(shFlag).toString();
982 * Builds the flow to be programmed in the DMAC table of the local DPN (that
983 * is, where the MAC is attached to). This flow consists in:
985 * <p>Match: + elanTag in metadata + packet goes to a MAC locally attached
986 * Actions: + optionally, pop-vlan + set-vlan-id + output to ifName's
1003 public Flow buildLocalDmacFlowEntry(long elanTag, BigInteger dpId, String ifName, String macAddress,
1004 ElanInstance elanInfo, long ifTag) {
1006 List<MatchInfo> mkMatches = new ArrayList<>();
1007 mkMatches.add(new MatchMetadata(getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
1008 mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddress)));
1010 List<Instruction> mkInstructions = new ArrayList<>();
1011 List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
1012 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
1013 Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
1014 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, ifTag, macAddress, elanTag), 20,
1015 elanInfo.getElanInstanceName(), 0, 0, ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(
1016 BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
1021 public void setupRemoteDmacFlow(BigInteger srcDpId, BigInteger destDpId, int lportTag, long elanTag,
1022 String macAddress, String displayName, WriteTransaction writeFlowGroupTx, String interfaceName,
1023 ElanInstance elanInstance) throws ElanException {
1024 if (interfaceManager.isExternalInterface(interfaceName)) {
1025 LOG.debug("Ignoring install remote DMAC {} flow on provider interface {} elan {}",
1026 macAddress, interfaceName, elanInstance.getElanInstanceName());
1029 Flow flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTag, elanTag, macAddress, displayName,
1031 mdsalManager.addFlowToTx(srcDpId, flowEntity, writeFlowGroupTx);
1032 setupEtreeRemoteDmacFlow(srcDpId, destDpId, lportTag, elanTag, macAddress, displayName, interfaceName,
1033 writeFlowGroupTx, elanInstance);
1036 private void setupEtreeRemoteDmacFlow(BigInteger srcDpId, BigInteger destDpId, int lportTag, long elanTag,
1037 String macAddress, String displayName, String interfaceName,
1038 WriteTransaction writeFlowGroupTx, ElanInstance elanInstance) throws ElanException {
1040 EtreeInterface etreeInterface = getEtreeInterfaceByElanInterfaceName(broker, interfaceName);
1041 if (etreeInterface != null) {
1042 if (etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
1043 EtreeLeafTagName etreeTagName = getEtreeLeafTagByElanTag(elanTag);
1044 if (etreeTagName == null) {
1045 LOG.warn("Interface " + interfaceName
1046 + " seems like it belongs to Etree but etreeTagName from elanTag " + elanTag + " is null.");
1048 flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTag,
1049 etreeTagName.getEtreeLeafTag().getValue(), macAddress, displayName, elanInstance);
1050 mdsalManager.addFlowToTx(srcDpId, flowEntity, writeFlowGroupTx);
1057 * Builds a Flow to be programmed in a remote DPN's DMAC table. This flow
1058 * consists in: Match: + elanTag in packet's metadata + packet going to a
1059 * MAC known to be located in another DPN Actions: + set_tunnel_id(lportTag)
1060 * + output ITM internal tunnel interface with the other DPN
1072 * @param displayName
1074 * @return the flow remote Dmac
1075 * @throws ElanException in case of issues creating the flow objects
1077 @SuppressWarnings("checkstyle:IllegalCatch")
1078 public Flow buildRemoteDmacFlowEntry(BigInteger srcDpId, BigInteger destDpId, int lportTag, long elanTag,
1079 String macAddress, String displayName, ElanInstance elanInstance) throws ElanException {
1080 List<MatchInfo> mkMatches = new ArrayList<>();
1081 mkMatches.add(new MatchMetadata(getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
1082 mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddress)));
1084 List<Instruction> mkInstructions = new ArrayList<>();
1086 // List of Action for the provided Source and Destination DPIDs
1088 List<Action> actions = null;
1089 if (isVlan(elanInstance) || isFlat(elanInstance)) {
1090 String interfaceName = getExternalElanInterface(elanInstance.getElanInstanceName(), srcDpId);
1091 if (null == interfaceName) {
1092 LOG.error("buildRemoteDmacFlowEntry: Could not find interfaceName for {} {}", srcDpId,
1095 actions = getEgressActionsForInterface(interfaceName, null);
1097 actions = getInternalTunnelItmEgressAction(srcDpId, destDpId, lportTag);
1099 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
1100 } catch (Exception e) {
1101 LOG.error("Could not get egress actions to add to flow for srcDpId=" + srcDpId + ", destDpId=" + destDpId
1102 + ", lportTag=" + lportTag, e);
1105 Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
1106 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, srcDpId, destDpId, macAddress, elanTag),
1108 displayName, 0, /* idleTimeout */
1109 0, /* hardTimeout */
1110 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
1116 public void deleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, MacEntry macEntry,
1117 WriteTransaction deleteFlowGroupTx) {
1118 if (elanInfo == null || interfaceInfo == null) {
1121 String macAddress = macEntry.getMacAddress().getValue();
1122 synchronized (getElanMacDPNKey(elanInfo.getElanTag(), macAddress, interfaceInfo.getDpId())) {
1123 deleteMacFlows(elanInfo, interfaceInfo, macAddress, /* alsoDeleteSMAC */ true, deleteFlowGroupTx);
1127 public void deleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1128 boolean deleteSmac, WriteTransaction deleteFlowGroupTx) {
1129 String elanInstanceName = elanInfo.getElanInstanceName();
1130 List<DpnInterfaces> remoteFEs = getInvolvedDpnsInElan(elanInstanceName);
1131 BigInteger srcdpId = interfaceInfo.getDpId();
1132 boolean isFlowsRemovedInSrcDpn = false;
1133 for (DpnInterfaces dpnInterface : remoteFEs) {
1134 Long elanTag = elanInfo.getElanTag();
1135 BigInteger dstDpId = dpnInterface.getDpId();
1136 if (executeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1137 elanTag, dstDpId, deleteFlowGroupTx)) {
1138 isFlowsRemovedInSrcDpn = true;
1140 executeEtreeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1141 elanTag, dstDpId, deleteFlowGroupTx);
1143 if (!isFlowsRemovedInSrcDpn) {
1144 deleteSmacAndDmacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, deleteFlowGroupTx);
1148 private void executeEtreeDeleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1149 boolean deleteSmac, String elanInstanceName, BigInteger srcdpId, Long elanTag, BigInteger dstDpId,
1150 WriteTransaction deleteFlowGroupTx) {
1151 EtreeLeafTagName etreeLeafTag = getEtreeLeafTagByElanTag(elanTag);
1152 if (etreeLeafTag != null) {
1153 executeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1154 etreeLeafTag.getEtreeLeafTag().getValue(), dstDpId, deleteFlowGroupTx);
1158 private boolean executeDeleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1159 boolean deleteSmac, String elanInstanceName, BigInteger srcdpId, Long elanTag, BigInteger dstDpId,
1160 WriteTransaction deleteFlowGroupTx) {
1161 boolean isFlowsRemovedInSrcDpn = false;
1162 if (dstDpId.equals(srcdpId)) {
1163 isFlowsRemovedInSrcDpn = true;
1164 deleteSmacAndDmacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, deleteFlowGroupTx);
1165 } else if (isDpnPresent(dstDpId)) {
1167 .removeFlowToTx(dstDpId,
1168 MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, getKnownDynamicmacFlowRef(
1169 NwConstants.ELAN_DMAC_TABLE, dstDpId, srcdpId, macAddress, elanTag)),
1171 LOG.debug("Dmac flow entry deleted for elan:{}, logical interface port:{} and mac address:{} on dpn:{}",
1172 elanInstanceName, interfaceInfo.getPortName(), macAddress, dstDpId);
1174 return isFlowsRemovedInSrcDpn;
1177 private void deleteSmacAndDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1178 boolean deleteSmac, WriteTransaction deleteFlowGroupTx) {
1179 String elanInstanceName = elanInfo.getElanInstanceName();
1180 long ifTag = interfaceInfo.getInterfaceTag();
1181 BigInteger srcdpId = interfaceInfo.getDpId();
1182 Long elanTag = elanInfo.getElanTag();
1185 .removeFlowToTx(srcdpId,
1186 MDSALUtil.buildFlow(NwConstants.ELAN_SMAC_TABLE, getKnownDynamicmacFlowRef(
1187 NwConstants.ELAN_SMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)),
1190 mdsalManager.removeFlowToTx(srcdpId,
1191 MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE,
1192 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)),
1194 LOG.debug("All the required flows deleted for elan:{}, logical Interface port:{} and MAC address:{} on dpn:{}",
1195 elanInstanceName, interfaceInfo.getPortName(), macAddress, srcdpId);
1199 * Updates the Elan information in the Operational DS. It also updates the
1200 * ElanInstance in the Config DS by setting the adquired elanTag.
1206 * @param elanInstanceAdded
1207 * the elan instance added
1208 * @param elanInterfaces
1209 * the elan interfaces
1213 public static void updateOperationalDataStore(DataBroker broker, IdManagerService idManager,
1214 ElanInstance elanInstanceAdded, List<String> elanInterfaces, WriteTransaction tx) {
1215 String elanInstanceName = elanInstanceAdded.getElanInstanceName();
1216 Long elanTag = elanInstanceAdded.getElanTag();
1217 if (elanTag == null || elanTag == 0L) {
1218 elanTag = retrieveNewElanTag(idManager, elanInstanceName);
1220 Elan elanInfo = new ElanBuilder().setName(elanInstanceName).setElanInterfaces(elanInterfaces)
1221 .setKey(new ElanKey(elanInstanceName)).build();
1223 // Add the ElanState in the elan-state operational data-store
1224 tx.put(LogicalDatastoreType.OPERATIONAL, getElanInstanceOperationalDataPath(elanInstanceName),
1227 // Add the ElanMacTable in the elan-mac-table operational data-store
1228 MacTable elanMacTable = new MacTableBuilder().setKey(new MacTableKey(elanInstanceName)).build();
1229 tx.put(LogicalDatastoreType.OPERATIONAL, getElanMacTableOperationalDataPath(elanInstanceName),
1230 elanMacTable, true);
1232 ElanTagNameBuilder elanTagNameBuilder = new ElanTagNameBuilder().setElanTag(elanTag)
1233 .setKey(new ElanTagNameKey(elanTag)).setName(elanInstanceName);
1234 long etreeLeafTag = -1;
1235 if (isEtreeInstance(elanInstanceAdded)) {
1236 etreeLeafTag = retrieveNewElanTag(idManager, elanInstanceName + ElanConstants.LEAVES_POSTFIX);
1237 EtreeLeafTagName etreeLeafTagName = new EtreeLeafTagNameBuilder()
1238 .setEtreeLeafTag(new EtreeLeafTag(etreeLeafTag)).build();
1239 elanTagNameBuilder.addAugmentation(EtreeLeafTagName.class, etreeLeafTagName);
1240 addTheLeafTagAsElanTag(broker, elanInstanceName, etreeLeafTag, tx);
1242 ElanTagName elanTagName = elanTagNameBuilder.build();
1244 // Add the ElanTag to ElanName in the elan-tag-name Operational
1246 tx.put(LogicalDatastoreType.OPERATIONAL,
1247 getElanInfoEntriesOperationalDataPath(elanTag), elanTagName);
1249 // Updates the ElanInstance Config DS by setting the just acquired
1251 ElanInstanceBuilder elanInstanceBuilder = new ElanInstanceBuilder().setElanInstanceName(elanInstanceName)
1252 .setDescription(elanInstanceAdded.getDescription())
1253 .setMacTimeout(elanInstanceAdded.getMacTimeout() == null ? ElanConstants.DEFAULT_MAC_TIME_OUT
1254 : elanInstanceAdded.getMacTimeout())
1255 .setKey(elanInstanceAdded.getKey()).setElanTag(elanTag);
1256 if (isEtreeInstance(elanInstanceAdded)) {
1257 EtreeInstance etreeInstance = new EtreeInstanceBuilder().setEtreeLeafTagVal(new EtreeLeafTag(etreeLeafTag))
1259 elanInstanceBuilder.addAugmentation(EtreeInstance.class, etreeInstance);
1261 ElanInstance elanInstanceWithTag = elanInstanceBuilder.build();
1262 tx.merge(LogicalDatastoreType.CONFIGURATION, getElanInstanceConfigurationDataPath(elanInstanceName),
1263 elanInstanceWithTag, true);
1266 private static void addTheLeafTagAsElanTag(DataBroker broker, String elanInstanceName, long etreeLeafTag,
1267 WriteTransaction tx) {
1268 ElanTagName etreeTagAsElanTag = new ElanTagNameBuilder().setElanTag(etreeLeafTag)
1269 .setKey(new ElanTagNameKey(etreeLeafTag)).setName(elanInstanceName).build();
1270 tx.put(LogicalDatastoreType.OPERATIONAL,
1271 getElanInfoEntriesOperationalDataPath(etreeLeafTag), etreeTagAsElanTag);
1274 private static boolean isEtreeInstance(ElanInstance elanInstanceAdded) {
1275 return elanInstanceAdded.getAugmentation(EtreeInstance.class) != null;
1278 public boolean isDpnPresent(BigInteger dpnId) {
1279 String dpn = String.format("%s:%s", "openflow", dpnId);
1280 NodeId nodeId = new NodeId(dpn);
1282 InstanceIdentifier<Node> node = InstanceIdentifier.builder(Nodes.class).child(Node.class, new NodeKey(nodeId))
1284 return read(broker, LogicalDatastoreType.CONFIGURATION, node).isPresent();
1287 public static ServicesInfo getServiceInfo(String elanInstanceName, long elanTag, String interfaceName) {
1288 int priority = ElanConstants.ELAN_SERVICE_PRIORITY;
1289 int instructionKey = 0;
1290 List<Instruction> instructions = new ArrayList<>();
1291 instructions.add(MDSALUtil.buildAndGetWriteMetadaInstruction(getElanMetadataLabel(elanTag),
1292 MetaDataUtil.METADATA_MASK_SERVICE, ++instructionKey));
1293 instructions.add(MDSALUtil.buildAndGetGotoTableInstruction(NwConstants.ELAN_SMAC_TABLE, ++instructionKey));
1295 short serviceIndex = ServiceIndex.getIndex(NwConstants.ELAN_SERVICE_NAME, NwConstants.ELAN_SERVICE_INDEX);
1296 ServicesInfo serviceInfo = InterfaceServiceUtil.buildServiceInfo(
1297 String.format("%s.%s", elanInstanceName, interfaceName), serviceIndex, priority,
1298 NwConstants.COOKIE_ELAN_INGRESS_TABLE, instructions);
1302 public static <T extends DataObject> void syncWrite(DataBroker broker, LogicalDatastoreType datastoreType,
1303 InstanceIdentifier<T> path, T data) {
1304 WriteTransaction tx = broker.newWriteOnlyTransaction();
1305 tx.put(datastoreType, path, data, true);
1306 CheckedFuture<Void, TransactionCommitFailedException> futures = tx.submit();
1309 } catch (InterruptedException | ExecutionException e) {
1310 LOG.error("Error writing to datastore (path, data) : ({}, {})", path, data);
1311 throw new RuntimeException(e.getMessage());
1315 public static BoundServices getBoundServices(String serviceName, short servicePriority, int flowPriority,
1316 BigInteger cookie, List<Instruction> instructions) {
1317 StypeOpenflowBuilder augBuilder = new StypeOpenflowBuilder().setFlowCookie(cookie).setFlowPriority(flowPriority)
1318 .setInstruction(instructions);
1319 return new BoundServicesBuilder().setKey(new BoundServicesKey(servicePriority)).setServiceName(serviceName)
1320 .setServicePriority(servicePriority).setServiceType(ServiceTypeFlowBased.class)
1321 .addAugmentation(StypeOpenflow.class, augBuilder.build()).build();
1324 public static InstanceIdentifier<BoundServices> buildServiceId(String vpnInterfaceName, short serviceIndex) {
1325 return InstanceIdentifier.builder(ServiceBindings.class)
1326 .child(ServicesInfo.class, new ServicesInfoKey(vpnInterfaceName, ServiceModeIngress.class))
1327 .child(BoundServices.class, new BoundServicesKey(serviceIndex)).build();
1331 * Builds the list of actions to be taken when sending the packet over a
1332 * VxLan Tunnel Interface, such as setting the tunnel_id field, the vlanId
1333 * if proceeds and output the packet over the right port.
1335 * @param tunnelIfaceName
1336 * the tunnel iface name
1341 public List<Action> buildTunnelItmEgressActions(String tunnelIfaceName, Long tunnelKey) {
1342 if (tunnelIfaceName != null && !tunnelIfaceName.isEmpty()) {
1343 return buildItmEgressActions(tunnelIfaceName, tunnelKey);
1346 return Collections.emptyList();
1350 * Builds the list of actions to be taken when sending the packet over
1351 * external port such as tunnel, physical port etc.
1353 * @param interfaceName
1354 * the interface name
1356 * can be VNI for VxLAN tunnel interfaces, Gre Key for GRE
1360 @SuppressWarnings("checkstyle:IllegalCatch")
1361 public List<Action> buildItmEgressActions(String interfaceName, Long tunnelKey) {
1362 List<Action> result = Collections.emptyList();
1364 GetEgressActionsForInterfaceInput getEgressActInput = new GetEgressActionsForInterfaceInputBuilder()
1365 .setIntfName(interfaceName).setTunnelKey(tunnelKey).build();
1367 Future<RpcResult<GetEgressActionsForInterfaceOutput>> egressActionsOutputFuture = interfaceManagerRpcService
1368 .getEgressActionsForInterface(getEgressActInput);
1369 if (egressActionsOutputFuture.get().isSuccessful()) {
1370 GetEgressActionsForInterfaceOutput egressActionsOutput = egressActionsOutputFuture.get().getResult();
1371 result = egressActionsOutput.getAction();
1373 } catch (Exception e) {
1374 LOG.error("Error in RPC call getEgressActionsForInterface {}", e);
1377 if (result == null || result.size() == 0) {
1378 LOG.warn("Could not build Egress actions for interface {} and tunnelId {}", interfaceName, tunnelKey);
1384 * Builds the list of actions to be taken when sending the packet over an
1385 * external VxLan tunnel interface, such as stamping the VNI on the VxLAN
1386 * header, setting the vlanId if it proceeds and output the packet over the
1390 * Dpn where the tunnelInterface is located
1392 * NodeId of the ExternalDevice where the packet must be sent to.
1394 * Vni to be stamped on the VxLAN Header.
1395 * @return the external itm egress action
1397 public List<Action> getExternalTunnelItmEgressAction(BigInteger srcDpnId, NodeId torNode, long vni) {
1398 List<Action> result = Collections.emptyList();
1400 GetExternalTunnelInterfaceNameInput input = new GetExternalTunnelInterfaceNameInputBuilder()
1401 .setDestinationNode(torNode.getValue()).setSourceNode(srcDpnId.toString())
1402 .setTunnelType(TunnelTypeVxlan.class).build();
1403 Future<RpcResult<GetExternalTunnelInterfaceNameOutput>> output = itmRpcService
1404 .getExternalTunnelInterfaceName(input);
1406 if (output.get().isSuccessful()) {
1407 GetExternalTunnelInterfaceNameOutput tunnelInterfaceNameOutput = output.get().getResult();
1408 String tunnelIfaceName = tunnelInterfaceNameOutput.getInterfaceName();
1409 LOG.debug("Received tunnelInterfaceName from getTunnelInterfaceName RPC {}", tunnelIfaceName);
1411 result = buildTunnelItmEgressActions(tunnelIfaceName, vni);
1414 } catch (InterruptedException | ExecutionException e) {
1415 LOG.error("Error in RPC call getTunnelInterfaceName {}", e);
1422 * Builds the list of actions to be taken when sending the packet over an
1423 * internal VxLan tunnel interface, such as setting the serviceTag on the
1424 * VNI field of the VxLAN header, setting the vlanId if it proceeds and
1425 * output the packet over the right port.
1427 * @param sourceDpnId
1428 * Dpn where the tunnelInterface is located
1429 * @param destinationDpnId
1430 * Dpn where the packet must be sent to. It is used here in order
1431 * to select the right tunnel interface.
1433 * serviceId to be sent on the VxLAN header.
1434 * @return the internal itm egress action
1436 public List<Action> getInternalTunnelItmEgressAction(BigInteger sourceDpnId, BigInteger destinationDpnId,
1438 List<Action> result = Collections.emptyList();
1440 LOG.info("In getInternalItmEgressAction Action source {}, destination {}, elanTag {}", sourceDpnId,
1441 destinationDpnId, serviceTag);
1442 Class<? extends TunnelTypeBase> tunType = TunnelTypeVxlan.class;
1443 GetTunnelInterfaceNameInput input = new GetTunnelInterfaceNameInputBuilder()
1444 .setDestinationDpid(destinationDpnId).setSourceDpid(sourceDpnId).setTunnelType(tunType).build();
1445 Future<RpcResult<GetTunnelInterfaceNameOutput>> output = itmRpcService
1446 .getTunnelInterfaceName(input);
1448 if (output.get().isSuccessful()) {
1449 GetTunnelInterfaceNameOutput tunnelInterfaceNameOutput = output.get().getResult();
1450 String tunnelIfaceName = tunnelInterfaceNameOutput.getInterfaceName();
1451 LOG.info("Received tunnelInterfaceName from getTunnelInterfaceName RPC {}", tunnelIfaceName);
1453 result = buildTunnelItmEgressActions(tunnelIfaceName, serviceTag);
1455 } catch (InterruptedException | ExecutionException e) {
1456 LOG.error("Error in RPC call getTunnelInterfaceName {}", e);
1463 * Build the list of actions to be taken when sending the packet to external
1466 * @param interfaceName
1468 * @return the external port itm egress actions
1470 public List<Action> getExternalPortItmEgressAction(String interfaceName) {
1471 return buildItmEgressActions(interfaceName, null);
1474 public static List<MatchInfo> getTunnelMatchesForServiceId(int elanTag) {
1475 List<MatchInfo> mkMatches = new ArrayList<>();
1476 // Matching metadata
1477 mkMatches.add(new MatchTunnelId(BigInteger.valueOf(elanTag)));
1482 public void removeTerminatingServiceAction(BigInteger destDpId, int serviceId) {
1483 RemoveTerminatingServiceActionsInput input = new RemoveTerminatingServiceActionsInputBuilder()
1484 .setDpnId(destDpId).setServiceId(serviceId).build();
1485 Future<RpcResult<Void>> futureObject = itmRpcService
1486 .removeTerminatingServiceActions(input);
1488 RpcResult<Void> result = futureObject.get();
1489 if (result.isSuccessful()) {
1490 LOG.debug("Successfully completed removeTerminatingServiceActions");
1492 LOG.debug("Failure in removeTerminatingServiceAction RPC call");
1494 } catch (InterruptedException | ExecutionException e) {
1495 LOG.error("Error in RPC call removeTerminatingServiceActions {}", e);
1499 public void createTerminatingServiceActions(BigInteger destDpId, int serviceId, List<Action> actions) {
1500 List<Instruction> mkInstructions = new ArrayList<>();
1501 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
1502 CreateTerminatingServiceActionsInput input = new CreateTerminatingServiceActionsInputBuilder()
1503 .setDpnId(destDpId).setServiceId(serviceId).setInstruction(mkInstructions).build();
1505 itmRpcService.createTerminatingServiceActions(input);
1509 * Gets the external tunnel.
1511 * @param sourceDevice
1513 * @param destinationDevice
1514 * the destination device
1515 * @param datastoreType
1516 * the datastore type
1517 * @return the external tunnel
1519 public ExternalTunnel getExternalTunnel(String sourceDevice, String destinationDevice,
1520 LogicalDatastoreType datastoreType) {
1521 Class<? extends TunnelTypeBase> tunType = TunnelTypeVxlan.class;
1522 InstanceIdentifier<ExternalTunnel> iid = InstanceIdentifier.builder(ExternalTunnelList.class)
1523 .child(ExternalTunnel.class, new ExternalTunnelKey(destinationDevice, sourceDevice, tunType)).build();
1524 return read(broker, datastoreType, iid).orNull();
1528 * Gets the external tunnel.
1530 * @param interfaceName
1531 * the interface name
1532 * @param datastoreType
1533 * the datastore type
1534 * @return the external tunnel
1536 public ExternalTunnel getExternalTunnel(String interfaceName, LogicalDatastoreType datastoreType) {
1537 ExternalTunnel externalTunnel = null;
1538 List<ExternalTunnel> externalTunnels = getAllExternalTunnels(datastoreType);
1539 for (ExternalTunnel tunnel : externalTunnels) {
1540 if (StringUtils.equalsIgnoreCase(interfaceName, tunnel.getTunnelInterfaceName())) {
1541 externalTunnel = tunnel;
1545 return externalTunnel;
1549 * Gets the all external tunnels.
1551 * @param datastoreType
1552 * the data store type
1553 * @return the all external tunnels
1555 public List<ExternalTunnel> getAllExternalTunnels(LogicalDatastoreType datastoreType) {
1556 InstanceIdentifier<ExternalTunnelList> iid = InstanceIdentifier.builder(ExternalTunnelList.class).build();
1557 return read(broker, datastoreType, iid).transform(ExternalTunnelList::getExternalTunnel).or(
1558 Collections.emptyList());
1562 * Installs a Flow in a DPN's DMAC table. The Flow is for a MAC that is
1563 * connected remotely in another CSS and accessible through an internal
1564 * tunnel. It also installs the flow for dropping the packet if it came over
1565 * an ITM tunnel (that is, if the Split-Horizon flag is set)
1568 * Id of the DPN where the MAC Addr is accessible locally
1570 * Id of the DPN where the flow must be installed
1572 * lportTag of the interface where the mac is connected to.
1574 * Identifier of the ELAN
1576 * MAC to be installed in remoteDpId's DMAC table
1577 * @param displayName
1579 * @throws ElanException in case of issues creating the flow objects
1581 public void installDmacFlowsToInternalRemoteMac(BigInteger localDpId, BigInteger remoteDpId, int lportTag,
1582 long elanTag, String macAddress, String displayName) throws ElanException {
1583 Flow flow = buildDmacFlowForInternalRemoteMac(localDpId, remoteDpId, lportTag, elanTag, macAddress,
1585 mdsalManager.installFlow(remoteDpId, flow);
1589 * Installs a Flow in the specified DPN's DMAC table. The flow is for a MAC
1590 * that is connected remotely in an External Device (TOR) and that is
1591 * accessible through an external tunnel. It also installs the flow for
1592 * dropping the packet if it came over an ITM tunnel (that is, if the
1593 * Split-Horizon flag is set)
1596 * Id of the DPN where the flow must be installed
1597 * @param extDeviceNodeId
1598 * the ext device node id
1605 * @param displayName
1607 * @param interfaceName
1608 * the interface name
1610 * @return the dmac flows
1611 * @throws ElanException in case of issues creating the flow objects
1613 public List<ListenableFuture<Void>> installDmacFlowsToExternalRemoteMac(BigInteger dpnId,
1614 String extDeviceNodeId, Long elanTag, Long vni, String macAddress, String displayName,
1615 String interfaceName) throws ElanException {
1616 List<ListenableFuture<Void>> futures = new ArrayList<>();
1617 synchronized (getElanMacDPNKey(elanTag, macAddress, dpnId)) {
1618 Flow flow = buildDmacFlowForExternalRemoteMac(dpnId, extDeviceNodeId, elanTag, vni, macAddress,
1620 futures.add(mdsalManager.installFlow(dpnId, flow));
1622 Flow dropFlow = buildDmacFlowDropIfPacketComingFromTunnel(dpnId, extDeviceNodeId, elanTag, macAddress);
1623 futures.add(mdsalManager.installFlow(dpnId, dropFlow));
1624 installEtreeDmacFlowsToExternalRemoteMac(dpnId, extDeviceNodeId, elanTag, vni, macAddress, displayName,
1625 interfaceName, futures);
1630 private void installEtreeDmacFlowsToExternalRemoteMac(BigInteger dpnId, String extDeviceNodeId, Long elanTag,
1631 Long vni, String macAddress, String displayName, String interfaceName,
1632 List<ListenableFuture<Void>> futures) throws ElanException {
1633 EtreeLeafTagName etreeLeafTag = getEtreeLeafTagByElanTag(elanTag);
1634 if (etreeLeafTag != null) {
1635 buildEtreeDmacFlowDropIfPacketComingFromTunnel(dpnId, extDeviceNodeId, elanTag, macAddress, futures,
1637 buildEtreeDmacFlowForExternalRemoteMac(dpnId, extDeviceNodeId, vni, macAddress, displayName, interfaceName,
1638 futures, etreeLeafTag);
1642 private void buildEtreeDmacFlowForExternalRemoteMac(BigInteger dpnId, String extDeviceNodeId, Long vni,
1643 String macAddress, String displayName, String interfaceName, List<ListenableFuture<Void>> futures,
1644 EtreeLeafTagName etreeLeafTag) throws ElanException {
1645 boolean isRoot = false;
1646 if (interfaceName == null) {
1649 EtreeInterface etreeInterface = getEtreeInterfaceByElanInterfaceName(broker, interfaceName);
1650 if (etreeInterface != null) {
1651 if (etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
1657 Flow flow = buildDmacFlowForExternalRemoteMac(dpnId, extDeviceNodeId,
1658 etreeLeafTag.getEtreeLeafTag().getValue(), vni, macAddress, displayName);
1659 futures.add(mdsalManager.installFlow(dpnId, flow));
1663 private void buildEtreeDmacFlowDropIfPacketComingFromTunnel(BigInteger dpnId, String extDeviceNodeId,
1664 Long elanTag, String macAddress, List<ListenableFuture<Void>> futures, EtreeLeafTagName etreeLeafTag) {
1665 if (etreeLeafTag != null) {
1666 Flow dropFlow = buildDmacFlowDropIfPacketComingFromTunnel(dpnId, extDeviceNodeId,
1667 etreeLeafTag.getEtreeLeafTag().getValue(), macAddress);
1668 futures.add(mdsalManager.installFlow(dpnId, dropFlow));
1672 public static List<MatchInfo> buildMatchesForElanTagShFlagAndDstMac(long elanTag, boolean shFlag, String macAddr) {
1673 List<MatchInfo> mkMatches = new ArrayList<>();
1675 new MatchMetadata(getElanMetadataLabel(elanTag, shFlag), MetaDataUtil.METADATA_MASK_SERVICE_SH_FLAG));
1676 mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddr)));
1682 * Builds a Flow to be programmed in a DPN's DMAC table. This method must be
1683 * used when the MAC is located in an External Device (TOR). The flow
1684 * matches on the specified MAC and 1) sends the packet over the CSS-TOR
1685 * tunnel if SHFlag is not set, or 2) drops it if SHFlag is set (what means
1686 * the packet came from an external tunnel)
1689 * DPN whose DMAC table is going to be modified
1690 * @param extDeviceNodeId
1691 * Hwvtep node where the mac is attached to
1693 * ElanId to which the MAC is being added to
1696 * @param dstMacAddress
1697 * The mac address to be programmed
1698 * @param displayName
1701 * @throws ElanException in case of issues creating the flow objects
1703 @SuppressWarnings("checkstyle:IllegalCatch")
1704 public Flow buildDmacFlowForExternalRemoteMac(BigInteger dpId, String extDeviceNodeId, long elanTag,
1705 Long vni, String dstMacAddress, String displayName) throws ElanException {
1706 List<MatchInfo> mkMatches = buildMatchesForElanTagShFlagAndDstMac(elanTag, /* shFlag */ false, dstMacAddress);
1707 List<Instruction> mkInstructions = new ArrayList<>();
1709 List<Action> actions = getExternalTunnelItmEgressAction(dpId, new NodeId(extDeviceNodeId), vni);
1710 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
1711 } catch (Exception e) {
1712 LOG.error("Could not get Egress Actions for DpId=" + dpId + ", externalNode=" + extDeviceNodeId, e);
1715 Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
1716 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, extDeviceNodeId, dstMacAddress, elanTag,
1719 displayName, 0, /* idleTimeout */
1720 0, /* hardTimeout */
1721 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
1727 * Builds the flow that drops the packet if it came through an external
1728 * tunnel, that is, if the Split-Horizon flag is set.
1731 * DPN whose DMAC table is going to be modified
1732 * @param extDeviceNodeId
1733 * Hwvtep node where the mac is attached to
1735 * ElanId to which the MAC is being added to
1736 * @param dstMacAddress
1737 * The mac address to be programmed
1739 private static Flow buildDmacFlowDropIfPacketComingFromTunnel(BigInteger dpnId, String extDeviceNodeId,
1740 Long elanTag, String dstMacAddress) {
1741 List<MatchInfo> mkMatches = buildMatchesForElanTagShFlagAndDstMac(elanTag, /* shFlag */ true, dstMacAddress);
1742 List<Instruction> mkInstructions = MDSALUtil.buildInstructionsDrop();
1743 String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpnId, extDeviceNodeId, dstMacAddress,
1745 Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE, flowId, 20, /* prio */
1746 "Drop", 0, /* idleTimeout */
1747 0, /* hardTimeout */
1748 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
1753 private static String getDmacDropFlowId(Long elanTag, String dstMacAddress) {
1754 return new StringBuilder(NwConstants.ELAN_DMAC_TABLE).append(elanTag).append(dstMacAddress).append("Drop")
1759 * Builds a Flow to be programmed in a remote DPN's DMAC table. This method
1760 * must be used when the MAC is located in another CSS.
1762 * <p>This flow consists in: Match: + elanTag in packet's metadata + packet
1763 * going to a MAC known to be located in another DPN Actions: +
1764 * set_tunnel_id(lportTag) + output on ITM internal tunnel interface with
1777 * @param displayName
1780 * @throws ElanException in case of issues creating the flow objects
1782 @SuppressWarnings("checkstyle:IllegalCatch")
1783 public Flow buildDmacFlowForInternalRemoteMac(BigInteger localDpId, BigInteger remoteDpId, int lportTag,
1784 long elanTag, String macAddress, String displayName) throws ElanException {
1785 List<MatchInfo> mkMatches = buildMatchesForElanTagShFlagAndDstMac(elanTag, /* shFlag */ false, macAddress);
1787 List<Instruction> mkInstructions = new ArrayList<>();
1790 // List of Action for the provided Source and Destination DPIDs
1791 List<Action> actions = getInternalTunnelItmEgressAction(localDpId, remoteDpId, lportTag);
1792 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
1793 } catch (Exception e) {
1794 LOG.error("Could not get Egress Actions for localDpId=" + localDpId + ", remoteDpId="
1795 + remoteDpId + ", lportTag=" + lportTag, e);
1798 Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
1799 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, localDpId, remoteDpId, macAddress, elanTag),
1801 displayName, 0, /* idleTimeout */
1802 0, /* hardTimeout */
1803 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
1810 * Installs or removes flows in DMAC table for MACs that are/were located in
1811 * an external Elan Device.
1814 * Id of the DPN where the DMAC table is going to be modified
1816 * Id of the External Device where the MAC is located
1820 * VNI of the LogicalSwitch to which the MAC belongs to, and that
1821 * is associated with the ELAN
1824 * @param elanInstanceName
1825 * the elan instance name
1826 * @param addOrRemove
1827 * Indicates if flows must be installed or removed.
1828 * @param interfaceName
1829 * the interface name
1830 * @throws ElanException in case of issues creating the flow objects
1831 * @see org.opendaylight.genius.mdsalutil.MDSALUtil.MdsalOp
1833 public void setupDmacFlowsToExternalRemoteMac(BigInteger dpId, String extNodeId, Long elanTag, Long vni,
1834 String macAddress, String elanInstanceName, MdsalOp addOrRemove, String interfaceName)
1835 throws ElanException {
1836 if (addOrRemove == MdsalOp.CREATION_OP) {
1837 installDmacFlowsToExternalRemoteMac(dpId, extNodeId, elanTag, vni, macAddress, elanInstanceName,
1839 } else if (addOrRemove == MdsalOp.REMOVAL_OP) {
1840 deleteDmacFlowsToExternalMac(elanTag, dpId, extNodeId, macAddress);
1845 * Delete dmac flows to external mac.
1851 * @param extDeviceNodeId
1852 * the ext device node id
1853 * @param macToRemove
1857 public List<ListenableFuture<Void>> deleteDmacFlowsToExternalMac(long elanTag, BigInteger dpId,
1858 String extDeviceNodeId, String macToRemove) {
1859 List<ListenableFuture<Void>> futures = new ArrayList<>();
1860 synchronized (getElanMacDPNKey(elanTag, macToRemove, dpId)) {
1861 // Removing the flows that sends the packet on an external tunnel
1862 removeFlowThatSendsThePacketOnAnExternalTunnel(elanTag, dpId, extDeviceNodeId, macToRemove, futures);
1864 // And now removing the drop flow
1865 removeTheDropFlow(elanTag, dpId, extDeviceNodeId, macToRemove, futures);
1867 deleteEtreeDmacFlowsToExternalMac(elanTag, dpId, extDeviceNodeId, macToRemove, futures);
1872 private void deleteEtreeDmacFlowsToExternalMac(long elanTag, BigInteger dpId, String extDeviceNodeId,
1873 String macToRemove, List<ListenableFuture<Void>> futures) {
1874 EtreeLeafTagName etreeLeafTag = getEtreeLeafTagByElanTag(elanTag);
1875 if (etreeLeafTag != null) {
1876 removeFlowThatSendsThePacketOnAnExternalTunnel(etreeLeafTag.getEtreeLeafTag().getValue(), dpId,
1877 extDeviceNodeId, macToRemove, futures);
1878 removeTheDropFlow(etreeLeafTag.getEtreeLeafTag().getValue(), dpId, extDeviceNodeId, macToRemove, futures);
1882 private void removeTheDropFlow(long elanTag, BigInteger dpId, String extDeviceNodeId, String macToRemove,
1883 List<ListenableFuture<Void>> futures) {
1884 String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, extDeviceNodeId, macToRemove,
1886 Flow flowToRemove = new FlowBuilder().setId(new FlowId(flowId)).setTableId(NwConstants.ELAN_DMAC_TABLE).build();
1887 futures.add(mdsalManager.removeFlow(dpId, flowToRemove));
1890 private void removeFlowThatSendsThePacketOnAnExternalTunnel(long elanTag, BigInteger dpId,
1891 String extDeviceNodeId, String macToRemove, List<ListenableFuture<Void>> futures) {
1892 String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, extDeviceNodeId, macToRemove,
1894 Flow flowToRemove = new FlowBuilder().setId(new FlowId(flowId)).setTableId(NwConstants.ELAN_DMAC_TABLE).build();
1895 futures.add(mdsalManager.removeFlow(dpId, flowToRemove));
1899 * Gets the dpid from interface.
1901 * @param interfaceName
1902 * the interface name
1903 * @return the dpid from interface
1905 public BigInteger getDpidFromInterface(String interfaceName) {
1906 BigInteger dpId = null;
1907 Future<RpcResult<GetDpidFromInterfaceOutput>> output = interfaceManagerRpcService
1908 .getDpidFromInterface(new GetDpidFromInterfaceInputBuilder().setIntfName(interfaceName).build());
1910 RpcResult<GetDpidFromInterfaceOutput> rpcResult = output.get();
1911 if (rpcResult.isSuccessful()) {
1912 dpId = rpcResult.getResult().getDpid();
1914 } catch (NullPointerException | InterruptedException | ExecutionException e) {
1915 LOG.error("Failed to get the DPN ID: {} for interface {}: {} ", dpId, interfaceName, e);
1921 * Checks if is interface operational.
1923 * @param interfaceName
1924 * the interface name
1927 * @return true, if is interface operational
1929 public static boolean isInterfaceOperational(String interfaceName, DataBroker dataBroker) {
1930 if (StringUtils.isBlank(interfaceName)) {
1933 Interface ifState = getInterfaceStateFromOperDS(interfaceName, dataBroker);
1934 if (ifState == null) {
1937 return ifState.getOperStatus() == OperStatus.Up && ifState.getAdminStatus() == AdminStatus.Up;
1941 * Gets the interface state from operational ds.
1943 * @param interfaceName
1944 * the interface name
1947 * @return the interface state from oper ds
1949 public static org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1950 .ietf.interfaces.rev140508.interfaces.state.Interface getInterfaceStateFromOperDS(
1951 String interfaceName, DataBroker dataBroker) {
1952 InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1953 .ietf.interfaces.rev140508.interfaces.state.Interface> ifStateId = createInterfaceStateInstanceIdentifier(
1955 return MDSALUtil.read(dataBroker, LogicalDatastoreType.OPERATIONAL, ifStateId).orNull();
1959 * Creates the interface state instance identifier.
1961 * @param interfaceName
1962 * the interface name
1963 * @return the instance identifier
1965 public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1966 .ietf.interfaces.rev140508.interfaces.state.Interface> createInterfaceStateInstanceIdentifier(
1967 String interfaceName) {
1968 InstanceIdentifierBuilder<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1969 .ietf.interfaces.rev140508.interfaces.state.Interface> idBuilder = InstanceIdentifier
1970 .builder(InterfacesState.class)
1971 .child(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1972 .ietf.interfaces.rev140508.interfaces.state.Interface.class,
1973 new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1974 .ietf.interfaces.rev140508.interfaces.state.InterfaceKey(
1976 return idBuilder.build();
1979 public static CheckedFuture<Void, TransactionCommitFailedException> waitForTransactionToComplete(
1980 WriteTransaction tx) {
1981 CheckedFuture<Void, TransactionCommitFailedException> futures = tx.submit();
1984 } catch (InterruptedException | ExecutionException e) {
1985 LOG.error("Error writing to datastore {}", e);
1990 public static boolean isVxlan(ElanInstance elanInstance) {
1991 return elanInstance != null && elanInstance.getSegmentType() != null
1992 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1993 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId() != 0;
1996 public static boolean isVxlanNetwork(DataBroker broker, String elanInstanceName) {
1997 ElanInstance elanInstance = getElanInstanceByName(broker, elanInstanceName);
1998 return (elanInstance != null && isVxlan(elanInstance));
2001 public static boolean isVxlanSegment(ElanInstance elanInstance) {
2002 if (elanInstance != null) {
2003 List<ElanSegments> elanSegments = elanInstance.getElanSegments();
2004 if (elanSegments != null) {
2005 for (ElanSegments segment : elanSegments) {
2006 if (segment != null && (segment.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
2007 && segment.getSegmentationId() != null
2008 && segment.getSegmentationId().longValue() != 0)) {
2017 public static Long getVxlanSegmentationId(ElanInstance elanInstance) {
2018 Long segmentationId = 0L;
2020 if (elanInstance != null && elanInstance.getSegmentType() != null
2021 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
2022 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId().longValue() != 0) {
2023 segmentationId = elanInstance.getSegmentationId();
2025 for (ElanSegments segment: elanInstance.getElanSegments()) {
2026 if (segment != null && segment.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
2027 && segment.getSegmentationId() != null
2028 && segment.getSegmentationId().longValue() != 0) {
2029 segmentationId = segment.getSegmentationId();
2033 return segmentationId;
2036 public static boolean isVlan(ElanInstance elanInstance) {
2037 return elanInstance != null && elanInstance.getSegmentType() != null
2038 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVlan.class)
2039 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId() != 0;
2042 public static boolean isFlat(ElanInstance elanInstance) {
2043 return elanInstance != null && elanInstance.getSegmentType() != null
2044 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeFlat.class);
2047 public static boolean isEtreeRootInterfaceByInterfaceName(DataBroker broker, String interfaceName) {
2048 EtreeInterface etreeInterface = getEtreeInterfaceByElanInterfaceName(broker, interfaceName);
2049 return etreeInterface != null && etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root;
2052 public void handleDmacRedirectToDispatcherFlows(Long elanTag, String displayName,
2053 String macAddress, int addOrRemove, List<BigInteger> dpnIds) {
2054 for (BigInteger dpId : dpnIds) {
2055 if (addOrRemove == NwConstants.ADD_FLOW) {
2056 WriteTransaction writeTx = broker.newWriteOnlyTransaction();
2057 mdsalManager.addFlowToTx(buildDmacRedirectToDispatcherFlow(dpId, macAddress, displayName, elanTag),
2061 String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, macAddress, elanTag);
2062 mdsalManager.removeFlow(dpId, MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, flowId));
2067 public static FlowEntity buildDmacRedirectToDispatcherFlow(BigInteger dpId, String dstMacAddress,
2068 String displayName, long elanTag) {
2069 List<MatchInfo> matches = new ArrayList<>();
2070 matches.add(new MatchMetadata(getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
2071 matches.add(new MatchEthernetDestination(new MacAddress(dstMacAddress)));
2072 List<InstructionInfo> instructions = new ArrayList<>();
2073 List<ActionInfo> actions = new ArrayList<>();
2074 actions.add(new ActionNxResubmit(NwConstants.LPORT_DISPATCHER_TABLE));
2076 instructions.add(new InstructionApplyActions(actions));
2077 String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, dstMacAddress, elanTag);
2078 FlowEntity flow = MDSALUtil.buildFlowEntity(dpId, NwConstants.ELAN_DMAC_TABLE, flowId, 20, displayName, 0, 0,
2079 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)),
2080 matches, instructions);
2084 public static FlowEntity buildDmacRedirectToDispatcherFlowMacNoActions(BigInteger dpId, String dstMacAddress,
2085 String displayName, long elanTag) {
2086 List<MatchInfo> matches = new ArrayList<>();
2087 matches.add(new MatchMetadata(getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
2088 matches.add(new MatchEthernetDestination(new MacAddress(dstMacAddress)));
2090 String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, dstMacAddress, elanTag);
2091 FlowEntity flow = MDSALUtil.buildFlowEntity(dpId, NwConstants.ELAN_DMAC_TABLE, flowId, 20, displayName, 0, 0,
2092 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)),
2093 matches, new ArrayList<>());
2098 * Add Mac Address to ElanInterfaceForwardingEntries and ElanForwardingTables
2099 * Install SMAC and DMAC flows.
2101 public void addMacEntryToDsAndSetupFlows(IInterfaceManager interfaceManager, String interfaceName,
2102 String macAddress, String elanName, WriteTransaction tx, WriteTransaction flowWritetx, int macTimeOut)
2103 throws ElanException {
2104 LOG.trace("Adding mac address {} and interface name {} to ElanInterfaceForwardingEntries and "
2105 + "ElanForwardingTables DS", macAddress, interfaceName);
2106 BigInteger timeStamp = new BigInteger(String.valueOf(System.currentTimeMillis()));
2107 PhysAddress physAddress = new PhysAddress(macAddress);
2108 MacEntry macEntry = new MacEntryBuilder().setInterface(interfaceName).setMacAddress(physAddress)
2109 .setKey(new MacEntryKey(physAddress)).setControllerLearnedForwardingEntryTimestamp(timeStamp)
2110 .setIsStaticAddress(false).build();
2111 InstanceIdentifier<MacEntry> macEntryId = ElanUtils
2112 .getInterfaceMacEntriesIdentifierOperationalDataPath(interfaceName, physAddress);
2113 tx.put(LogicalDatastoreType.OPERATIONAL, macEntryId, macEntry);
2114 InstanceIdentifier<MacEntry> elanMacEntryId = ElanUtils.getMacEntryOperationalDataPath(elanName, physAddress);
2115 tx.put(LogicalDatastoreType.OPERATIONAL, elanMacEntryId, macEntry);
2116 ElanInstance elanInstance = ElanUtils.getElanInstanceByName(broker, elanName);
2117 setupMacFlows(elanInstance, interfaceManager.getInterfaceInfo(interfaceName), macTimeOut, macAddress, true,
2122 * Remove Mac Address from ElanInterfaceForwardingEntries and ElanForwardingTables
2123 * Remove SMAC and DMAC flows.
2125 public void deleteMacEntryFromDsAndRemoveFlows(IInterfaceManager interfaceManager, String interfaceName,
2126 String macAddress, String elanName, WriteTransaction tx, WriteTransaction deleteFlowTx) {
2127 LOG.trace("Deleting mac address {} and interface name {} from ElanInterfaceForwardingEntries "
2128 + "and ElanForwardingTables DS", macAddress, interfaceName);
2129 PhysAddress physAddress = new PhysAddress(macAddress);
2130 MacEntry macEntry = getInterfaceMacEntriesOperationalDataPath(interfaceName, physAddress);
2131 InterfaceInfo interfaceInfo = interfaceManager.getInterfaceInfo(interfaceName);
2132 if (macEntry != null && interfaceInfo != null) {
2133 deleteMacFlows(ElanUtils.getElanInstanceByName(broker, elanName), interfaceInfo, macEntry, deleteFlowTx);
2135 tx.delete(LogicalDatastoreType.OPERATIONAL,
2136 ElanUtils.getInterfaceMacEntriesIdentifierOperationalDataPath(interfaceName, physAddress));
2137 tx.delete(LogicalDatastoreType.OPERATIONAL,
2138 ElanUtils.getMacEntryOperationalDataPath(elanName, physAddress));
2141 public String getExternalElanInterface(String elanInstanceName, BigInteger dpnId) {
2142 DpnInterfaces dpnInterfaces = getElanInterfaceInfoByElanDpn(elanInstanceName, dpnId);
2143 if (dpnInterfaces == null || dpnInterfaces.getInterfaces() == null) {
2144 LOG.trace("Elan {} does not have interfaces in DPN {}", elanInstanceName, dpnId);
2148 for (String dpnInterface : dpnInterfaces.getInterfaces()) {
2149 if (interfaceManager.isExternalInterface(dpnInterface)) {
2150 return dpnInterface;
2154 LOG.trace("Elan {} does not have any external interace attached to DPN {}", elanInstanceName, dpnId);
2158 public static String getElanMacDPNKey(long elanTag, String macAddress, BigInteger dpnId) {
2159 String elanMacDmacDpnKey = "MAC-" + macAddress + " ELAN_TAG-" + elanTag + "DPN_ID-" + dpnId;
2160 return elanMacDmacDpnKey.intern();
2163 public static String getElanMacKey(long elanTag, String macAddress) {
2164 String elanMacKey = "MAC-" + macAddress + " ELAN_TAG-" + elanTag;
2165 return elanMacKey.intern();
2169 public static void addToListenableFutureIfTxException(RuntimeException exception,
2170 List<ListenableFuture<Void>> futures) {
2171 Throwable cause = exception.getCause();
2172 if (cause != null && cause instanceof TransactionCommitFailedException) {
2173 futures.add(Futures.immediateFailedCheckedFuture((TransactionCommitFailedException) cause));
2177 public static List<PhysAddress> getPhysAddress(List<String> macAddress) {
2178 Preconditions.checkNotNull(macAddress, "macAddress cannot be null");
2179 List<PhysAddress> physAddresses = new ArrayList<>();
2180 for (String mac : macAddress) {
2181 physAddresses.add(new PhysAddress(mac));
2183 return physAddresses;
2186 public static List<StaticMacEntries> getStaticMacEntries(List<String> staticMacAddresses) {
2187 if (isEmpty(staticMacAddresses)) {
2188 return Collections.EMPTY_LIST;
2190 StaticMacEntriesBuilder staticMacEntriesBuilder = new StaticMacEntriesBuilder();
2191 List<StaticMacEntries> staticMacEntries = new ArrayList<>();
2192 List<PhysAddress> physAddressList = getPhysAddress(staticMacAddresses);
2193 for (PhysAddress physAddress : physAddressList) {
2194 staticMacEntries.add(staticMacEntriesBuilder.setMacAddress(physAddress).build());
2196 return staticMacEntries;
2199 public Optional<IpAddress> getSourceIpV4Address(byte[] data) {
2200 IPv4 ip = new IPv4();
2202 ip.deserialize(data, 0, data.length * NetUtils.NumBitsInAByte);
2203 } catch (PacketException e) {
2204 LOG.error("ip.deserialize throws exception {}", e);
2205 return Optional.absent();
2207 return Optional.of(IpAddressBuilder.getDefaultInstance(Integer.toString(ip.getSourceAddress())));
2210 public Optional<IpAddress> getSrcIpAddrFromArp(byte[] data) {
2211 ARP arp = new ARP();
2213 arp.deserialize(data, 0, data.length * NetUtils.NumBitsInAByte);
2214 } catch (PacketException e) {
2215 LOG.error("ip.deserialize throws exception {}", e);
2216 return Optional.absent();
2218 return Optional.of(IpAddressBuilder.getDefaultInstance(
2219 NWUtil.toStringIpAddress(arp.getSenderProtocolAddress())));
2222 //TODO: remove the try-catch once ip parsing is fixed properly (riyaz)
2223 @SuppressWarnings("checkstyle:IllegalCatch")
2224 public Optional<IpAddress> getSourceIpAddress(Ethernet ethernet, byte[] data) {
2225 /*IPV6 is not yet present in genius, hence V6 case ignored*/
2226 Optional<IpAddress> srcIpAddress = Optional.absent();
2228 if (NwConstants.ETHTYPE_IPV4 == ethernet.getEtherType()) {
2229 srcIpAddress = getSourceIpV4Address(data);
2230 } else if (NwConstants.ETHTYPE_ARP == ethernet.getEtherType()) {
2231 srcIpAddress = getSrcIpAddrFromArp(data);
2233 } catch (Exception e) {
2234 LOG.error("Error in getting ip address from packet", e);
2236 return srcIpAddress;
2239 public static InstanceIdentifier<StaticMacEntries> getStaticMacEntriesCfgDataPathIdentifier(String interfaceName,
2240 String macAddress) {
2241 return InstanceIdentifier.builder(ElanInterfaces.class)
2242 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).child(StaticMacEntries.class,
2243 new StaticMacEntriesKey(new PhysAddress(macAddress))).build();
2246 public static List<StaticMacEntries> getDeletedEntries(List<StaticMacEntries> originalStaticMacEntries,
2247 List<StaticMacEntries> updatedStaticMacEntries) {
2248 if (isEmpty(originalStaticMacEntries)) {
2249 return Collections.EMPTY_LIST;
2251 List<StaticMacEntries> deleted = Lists.newArrayList(originalStaticMacEntries);
2252 if (isNotEmpty(updatedStaticMacEntries)) {
2253 deleted.removeAll(updatedStaticMacEntries);
2258 public static <T> List<T> diffOf(List<T> orig, List<T> updated) {
2259 if (isEmpty(orig)) {
2260 return Collections.EMPTY_LIST;
2262 List<T> diff = Lists.newArrayList(orig);
2263 if (isNotEmpty(updated)) {
2264 diff.removeAll(updated);
2269 public static void segregateToBeDeletedAndAddEntries(List<StaticMacEntries> originalStaticMacEntries,
2270 List<StaticMacEntries> updatedStaticMacEntries) {
2271 if (isNotEmpty(updatedStaticMacEntries)) {
2272 List<StaticMacEntries> existingClonedStaticMacEntries = new ArrayList<>();
2273 if (isNotEmpty(originalStaticMacEntries)) {
2274 existingClonedStaticMacEntries.addAll(0, originalStaticMacEntries);
2275 originalStaticMacEntries.removeAll(updatedStaticMacEntries);
2276 updatedStaticMacEntries.removeAll(existingClonedStaticMacEntries);
2281 public static boolean isEmpty(Collection collection) {
2282 return collection == null || collection.isEmpty();
2285 public static boolean isNotEmpty(Collection collection) {
2286 return (!isEmpty(collection));
2289 public static void setElanInstancToDpnsCache(Map<String, Set<DpnInterfaces>> elanInstancToDpnsCache) {
2290 ElanUtils.elanInstancToDpnsCache = elanInstancToDpnsCache;
2293 public static Set<DpnInterfaces> getElanInvolvedDPNsFromCache(String elanName) {
2294 return elanInstancToDpnsCache.get(elanName);
2297 public static void addDPNInterfaceToElanInCache(String elanName, DpnInterfaces dpnInterfaces) {
2298 elanInstancToDpnsCache.computeIfAbsent(elanName, key -> new HashSet<>()).add(dpnInterfaces);
2301 public static void removeDPNInterfaceFromElanInCache(String elanName, DpnInterfaces dpnInterfaces) {
2302 elanInstancToDpnsCache.computeIfAbsent(elanName, key -> new HashSet<DpnInterfaces>()).remove(dpnInterfaces);