2 * Copyright © 2016, 2017 Ericsson India Global Services Pvt Ltd. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.netvirt.elan.utils;
10 import com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Strings;
13 import com.google.common.collect.Lists;
14 import com.google.common.primitives.Ints;
15 import com.google.common.util.concurrent.CheckedFuture;
16 import com.google.common.util.concurrent.FutureCallback;
17 import com.google.common.util.concurrent.Futures;
18 import com.google.common.util.concurrent.ListenableFuture;
19 import com.google.common.util.concurrent.MoreExecutors;
21 import java.math.BigInteger;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.Collections;
25 import java.util.HashSet;
26 import java.util.List;
29 import java.util.concurrent.ConcurrentHashMap;
30 import java.util.concurrent.ExecutionException;
31 import java.util.concurrent.Future;
33 import javax.annotation.Nonnull;
34 import javax.annotation.Nullable;
35 import javax.inject.Inject;
36 import javax.inject.Singleton;
37 import org.apache.commons.lang3.StringUtils;
38 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
39 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
40 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
41 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
42 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
43 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
44 import org.opendaylight.genius.interfacemanager.globals.InterfaceInfo;
45 import org.opendaylight.genius.interfacemanager.globals.InterfaceServiceUtil;
46 import org.opendaylight.genius.interfacemanager.interfaces.IInterfaceManager;
47 import org.opendaylight.genius.itm.globals.ITMConstants;
48 import org.opendaylight.genius.mdsalutil.ActionInfo;
49 import org.opendaylight.genius.mdsalutil.FlowEntity;
50 import org.opendaylight.genius.mdsalutil.FlowEntityBuilder;
51 import org.opendaylight.genius.mdsalutil.InstructionInfo;
52 import org.opendaylight.genius.mdsalutil.MDSALUtil;
53 import org.opendaylight.genius.mdsalutil.MatchInfo;
54 import org.opendaylight.genius.mdsalutil.MetaDataUtil;
55 import org.opendaylight.genius.mdsalutil.NWUtil;
56 import org.opendaylight.genius.mdsalutil.NwConstants;
57 import org.opendaylight.genius.mdsalutil.actions.ActionNxResubmit;
58 import org.opendaylight.genius.mdsalutil.instructions.InstructionApplyActions;
59 import org.opendaylight.genius.mdsalutil.instructions.InstructionGotoTable;
60 import org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager;
61 import org.opendaylight.genius.mdsalutil.matches.MatchEthernetDestination;
62 import org.opendaylight.genius.mdsalutil.matches.MatchEthernetSource;
63 import org.opendaylight.genius.mdsalutil.matches.MatchMetadata;
64 import org.opendaylight.genius.mdsalutil.matches.MatchTunnelId;
65 import org.opendaylight.genius.mdsalutil.packet.ARP;
66 import org.opendaylight.genius.mdsalutil.packet.Ethernet;
67 import org.opendaylight.genius.mdsalutil.packet.IPv4;
68 import org.opendaylight.netvirt.elan.ElanException;
69 import org.opendaylight.netvirt.elan.arp.responder.ArpResponderUtil;
70 import org.opendaylight.netvirt.elan.internal.ElanInstanceManager;
71 import org.opendaylight.netvirt.elan.l2gw.utils.ElanL2GatewayMulticastUtils;
72 import org.opendaylight.netvirt.elanmanager.api.ElanHelper;
73 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
74 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddressBuilder;
75 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfacesState;
76 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface;
77 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.AdminStatus;
78 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.OperStatus;
79 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
80 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.PhysAddress;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInput;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInputBuilder;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdOutput;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdManagerService;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInput;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInputBuilder;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406.IfIndexesInterfaceMap;
96 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._if.indexes._interface.map.IfIndexInterface;
97 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._if.indexes._interface.map.IfIndexInterfaceKey;
98 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfTunnel;
99 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.ParentRefs;
100 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeBase;
101 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeVxlan;
102 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceInput;
103 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceInputBuilder;
104 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceOutput;
105 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.OdlInterfaceRpcService;
106 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceBindings;
107 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceModeIngress;
108 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceTypeFlowBased;
109 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflow;
110 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflowBuilder;
111 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.ServicesInfo;
112 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.ServicesInfoKey;
113 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServices;
114 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesBuilder;
115 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesKey;
116 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.ExternalTunnelList;
117 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnel;
118 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnelKey;
119 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.ItmRpcService;
120 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsInput;
121 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsInputBuilder;
122 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
123 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
124 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
125 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
126 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
127 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.config.rev150710.ElanConfig;
128 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInstance;
129 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInstanceBuilder;
130 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInterface;
131 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInterface.EtreeInterfaceType;
132 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTag;
133 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTagName;
134 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTagNameBuilder;
135 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanDpnInterfaces;
136 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanForwardingTables;
137 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInstances;
138 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaceForwardingEntries;
139 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaces;
140 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanState;
141 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanTagNameMap;
142 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeFlat;
143 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeVlan;
144 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeVxlan;
145 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan._interface.forwarding.entries.ElanInterfaceMac;
146 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan._interface.forwarding.entries.ElanInterfaceMacKey;
147 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesList;
148 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesListKey;
149 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfaces;
150 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfacesKey;
151 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTable;
152 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTableBuilder;
153 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTableKey;
154 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstance;
155 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstanceBuilder;
156 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.elan.instance.ElanSegments;
157 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterface;
158 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterfaceKey;
159 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntries;
160 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntriesBuilder;
161 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntriesKey;
162 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.Elan;
163 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.ElanBuilder;
164 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.ElanKey;
165 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagName;
166 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagNameBuilder;
167 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagNameKey;
168 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntry;
169 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntryBuilder;
170 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntryKey;
171 import org.opendaylight.yangtools.yang.binding.DataObject;
172 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
173 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.InstanceIdentifierBuilder;
174 import org.opendaylight.yangtools.yang.common.RpcResult;
175 import org.slf4j.Logger;
176 import org.slf4j.LoggerFactory;
179 public class ElanUtils {
181 private static final Logger LOG = LoggerFactory.getLogger(ElanUtils.class);
183 private static Map<String, ElanInstance> elanInstanceLocalCache = new ConcurrentHashMap<>();
184 private static Map<String, ElanInterface> elanInterfaceLocalCache = new ConcurrentHashMap<>();
185 private static Map<String, Set<DpnInterfaces>> elanInstancToDpnsCache = new ConcurrentHashMap<>();
186 private static Map<String, Set<String>> elanInstanceToInterfacesCache = new ConcurrentHashMap<>();
188 private final DataBroker broker;
189 private final IMdsalApiManager mdsalManager;
190 private final ElanInstanceManager elanInstanceManager;
191 private final OdlInterfaceRpcService interfaceManagerRpcService;
192 private final ItmRpcService itmRpcService;
193 private final ElanL2GatewayMulticastUtils elanL2GatewayMulticastUtils;
194 private final IInterfaceManager interfaceManager;
195 private final ElanConfig elanConfig;
196 private final ElanItmUtils elanItmUtils;
197 private final ElanEtreeUtils elanEtreeUtils;
199 public static final FutureCallback<Void> DEFAULT_CALLBACK = new FutureCallback<Void>() {
201 public void onSuccess(Void result) {
202 LOG.debug("Success in Datastore operation");
206 public void onFailure(Throwable error) {
207 LOG.error("Error in Datastore operation", error);
212 public ElanUtils(DataBroker dataBroker, IMdsalApiManager mdsalManager, ElanInstanceManager elanInstanceManager,
213 OdlInterfaceRpcService interfaceManagerRpcService, ItmRpcService itmRpcService,
214 ElanConfig elanConfig,
215 IInterfaceManager interfaceManager,
216 ElanL2GatewayMulticastUtils elanL2GatewayMulticastUtils, ElanEtreeUtils elanEtreeUtils,
217 ElanItmUtils elanItmUtils) {
218 this.broker = dataBroker;
219 this.mdsalManager = mdsalManager;
220 this.elanInstanceManager = elanInstanceManager;
221 this.interfaceManagerRpcService = interfaceManagerRpcService;
222 this.itmRpcService = itmRpcService;
223 this.interfaceManager = interfaceManager;
224 this.elanConfig = elanConfig;
226 this.elanL2GatewayMulticastUtils = elanL2GatewayMulticastUtils;
227 this.elanEtreeUtils = elanEtreeUtils;
228 this.elanItmUtils = elanItmUtils;
231 public ElanL2GatewayMulticastUtils getElanL2GatewayMulticastUtils() {
232 return elanL2GatewayMulticastUtils;
235 public final Boolean isOpenStackVniSemanticsEnforced() {
236 return elanConfig.isOpenstackVniSemanticsEnforced();
239 public static void addElanInstanceIntoCache(String elanInstanceName, ElanInstance elanInstance) {
240 elanInstanceLocalCache.put(elanInstanceName, elanInstance);
243 public static void removeElanInstanceFromCache(String elanInstanceName) {
244 elanInstanceLocalCache.remove(elanInstanceName);
247 public static ElanInstance getElanInstanceFromCache(String elanInstanceName) {
248 return elanInstanceLocalCache.get(elanInstanceName);
251 public static Set<String> getAllElanNames() {
252 return elanInstanceLocalCache.keySet();
255 public static void addElanInterfaceIntoCache(String interfaceName, ElanInterface elanInterface) {
256 elanInterfaceLocalCache.put(interfaceName, elanInterface);
259 public static void removeElanInterfaceFromCache(String interfaceName) {
260 elanInterfaceLocalCache.remove(interfaceName);
263 public static ElanInterface getElanInterfaceFromCache(String interfaceName) {
264 return elanInterfaceLocalCache.get(interfaceName);
268 * Uses the IdManager to retrieve a brand new ElanTag.
274 * @return the integer
276 public static Long retrieveNewElanTag(IdManagerService idManager, String idKey) {
278 AllocateIdInput getIdInput = new AllocateIdInputBuilder().setPoolName(ElanConstants.ELAN_ID_POOL_NAME)
279 .setIdKey(idKey).build();
282 Future<RpcResult<AllocateIdOutput>> result = idManager.allocateId(getIdInput);
283 RpcResult<AllocateIdOutput> rpcResult = result.get();
284 if (rpcResult.isSuccessful()) {
285 return rpcResult.getResult().getIdValue();
287 LOG.warn("RPC Call to Allocate Id returned with Errors {}", rpcResult.getErrors());
289 } catch (InterruptedException | ExecutionException e) {
290 LOG.warn("Exception when Allocating Id", e);
295 public static void releaseId(IdManagerService idManager, String poolName, String idKey) {
296 ReleaseIdInput releaseIdInput = new ReleaseIdInputBuilder().setPoolName(poolName).setIdKey(idKey).build();
297 idManager.releaseId(releaseIdInput);
303 * @deprecated Consider using {@link #read2(LogicalDatastoreType, InstanceIdentifier)} with proper exception
307 @SuppressWarnings("checkstyle:IllegalCatch")
308 public static <T extends DataObject> Optional<T> read(@Nonnull DataBroker broker,
309 LogicalDatastoreType datastoreType, InstanceIdentifier<T> path) {
310 try (ReadOnlyTransaction tx = broker.newReadOnlyTransaction()) {
311 return tx.read(datastoreType, path).get();
312 } catch (Exception e) {
313 throw new RuntimeException(e);
317 public <T extends DataObject> Optional<T> read2(LogicalDatastoreType datastoreType, InstanceIdentifier<T> path)
318 throws ReadFailedException {
319 try (ReadOnlyTransaction tx = broker.newReadOnlyTransaction()) {
320 CheckedFuture<Optional<T>, ReadFailedException> checkedFuture = tx.read(datastoreType, path);
321 return checkedFuture.checkedGet();
325 public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
326 InstanceIdentifier<T> path) {
327 WriteTransaction tx = broker.newWriteOnlyTransaction();
328 tx.delete(datastoreType, path);
329 Futures.addCallback(tx.submit(), DEFAULT_CALLBACK, MoreExecutors.directExecutor());
332 public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
333 InstanceIdentifier<T> path, FutureCallback<Void> callback) {
334 WriteTransaction tx = broker.newWriteOnlyTransaction();
335 tx.delete(datastoreType, path);
336 Futures.addCallback(tx.submit(), callback, MoreExecutors.directExecutor());
339 public static InstanceIdentifier<ElanInstance> getElanInstanceIdentifier() {
340 return InstanceIdentifier.builder(ElanInstances.class).child(ElanInstance.class).build();
343 // elan-instances config container
344 public static ElanInstance getElanInstanceByName(DataBroker broker, String elanInstanceName) {
345 ElanInstance elanObj = getElanInstanceFromCache(elanInstanceName);
346 if (elanObj != null) {
349 InstanceIdentifier<ElanInstance> elanIdentifierId =
350 ElanHelper.getElanInstanceConfigurationDataPath(elanInstanceName);
351 return MDSALUtil.read(broker, LogicalDatastoreType.CONFIGURATION, elanIdentifierId).orNull();
354 // elan-interfaces Config Container
355 public static ElanInterface getElanInterfaceByElanInterfaceName(DataBroker broker, String elanInterfaceName) {
356 ElanInterface elanInterfaceObj = getElanInterfaceFromCache(elanInterfaceName);
357 if (elanInterfaceObj != null) {
358 return elanInterfaceObj;
360 InstanceIdentifier<ElanInterface> elanInterfaceId = getElanInterfaceConfigurationDataPathId(elanInterfaceName);
361 return MDSALUtil.read(broker, LogicalDatastoreType.CONFIGURATION, elanInterfaceId).orNull();
364 public static EtreeInterface getEtreeInterfaceByElanInterfaceName(DataBroker broker, String elanInterfaceName) {
365 ElanInterface elanInterface = getElanInterfaceByElanInterfaceName(broker, elanInterfaceName);
366 if (elanInterface == null) {
369 return elanInterface.getAugmentation(EtreeInterface.class);
373 public static InstanceIdentifier<ElanInterface> getElanInterfaceConfigurationDataPathId(String interfaceName) {
374 return InstanceIdentifier.builder(ElanInterfaces.class)
375 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).build();
378 // elan-state Operational container
379 public static Elan getElanByName(DataBroker broker, String elanInstanceName) {
380 InstanceIdentifier<Elan> elanIdentifier = getElanInstanceOperationalDataPath(elanInstanceName);
381 return MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL, elanIdentifier).orNull();
384 public static InstanceIdentifier<Elan> getElanInstanceOperationalDataPath(String elanInstanceName) {
385 return InstanceIdentifier.builder(ElanState.class).child(Elan.class, new ElanKey(elanInstanceName)).build();
388 // grouping of forwarding-entries
389 public MacEntry getInterfaceMacEntriesOperationalDataPath(String interfaceName, PhysAddress physAddress) {
390 InstanceIdentifier<MacEntry> existingMacEntryId = getInterfaceMacEntriesIdentifierOperationalDataPath(
391 interfaceName, physAddress);
392 return read(broker, LogicalDatastoreType.OPERATIONAL, existingMacEntryId).orNull();
395 public MacEntry getInterfaceMacEntriesOperationalDataPathFromId(InstanceIdentifier identifier) {
396 Optional<MacEntry> existingInterfaceMacEntry = read(broker,
397 LogicalDatastoreType.OPERATIONAL, identifier);
398 return existingInterfaceMacEntry.orNull();
401 public static InstanceIdentifier<MacEntry> getInterfaceMacEntriesIdentifierOperationalDataPath(String interfaceName,
402 PhysAddress physAddress) {
403 return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class)
404 .child(ElanInterfaceMac.class, new ElanInterfaceMacKey(interfaceName))
405 .child(MacEntry.class, new MacEntryKey(physAddress)).build();
409 // elan-forwarding-tables Operational container
410 public Optional<MacEntry> getMacEntryForElanInstance(String elanName, PhysAddress physAddress) {
411 InstanceIdentifier<MacEntry> macId = getMacEntryOperationalDataPath(elanName, physAddress);
412 return read(broker, LogicalDatastoreType.OPERATIONAL, macId);
415 public MacEntry getMacEntryFromElanMacId(InstanceIdentifier identifier) {
416 Optional<MacEntry> existingInterfaceMacEntry = read(broker,
417 LogicalDatastoreType.OPERATIONAL, identifier);
418 return existingInterfaceMacEntry.orNull();
421 public static InstanceIdentifier<MacEntry> getMacEntryOperationalDataPath(String elanName,
422 PhysAddress physAddress) {
423 return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class, new MacTableKey(elanName))
424 .child(MacEntry.class, new MacEntryKey(physAddress)).build();
427 public static InstanceIdentifier<MacTable> getElanMacTableOperationalDataPath(String elanName) {
428 return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class, new MacTableKey(elanName))
432 // elan-interface-forwarding-entries Operational container
433 public ElanInterfaceMac getElanInterfaceMacByInterfaceName(String interfaceName) {
434 return getElanInterfaceMacByInterfaceName(broker, interfaceName);
438 public static ElanInterfaceMac getElanInterfaceMacByInterfaceName(DataBroker dataBroker, String interfaceName) {
439 InstanceIdentifier<ElanInterfaceMac> elanInterfaceId = getElanInterfaceMacEntriesOperationalDataPath(
441 return read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanInterfaceId).orNull();
445 * Gets the elan interface mac addresses.
447 * @param interfaceName
449 * @return the elan interface mac addresses
451 public List<PhysAddress> getElanInterfaceMacAddresses(String interfaceName) {
452 List<PhysAddress> macAddresses = new ArrayList<>();
453 ElanInterfaceMac elanInterfaceMac = getElanInterfaceMacByInterfaceName(interfaceName);
454 if (elanInterfaceMac != null && elanInterfaceMac.getMacEntry() != null) {
455 List<MacEntry> macEntries = elanInterfaceMac.getMacEntry();
456 for (MacEntry macEntry : macEntries) {
457 macAddresses.add(macEntry.getMacAddress());
463 public static InstanceIdentifier<ElanInterfaceMac> getElanInterfaceMacEntriesOperationalDataPath(
464 String interfaceName) {
465 return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class)
466 .child(ElanInterfaceMac.class, new ElanInterfaceMacKey(interfaceName)).build();
470 * Returns the list of Interfaces that belong to an Elan on an specific DPN.
471 * Data retrieved from Elan's operational DS: elan-dpn-interfaces container
473 * @param elanInstanceName
474 * name of the Elan to which the interfaces must belong to
476 * Id of the DPN where the interfaces are located
477 * @return the elan interface Info
479 public DpnInterfaces getElanInterfaceInfoByElanDpn(String elanInstanceName, BigInteger dpId) {
480 InstanceIdentifier<DpnInterfaces> elanDpnInterfacesId = getElanDpnInterfaceOperationalDataPath(elanInstanceName,
482 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfacesId).orNull();
486 * Returns the InstanceIdentifier that points to the Interfaces of an Elan
487 * in a given DPN in the Operational DS. Data retrieved from Elans's
488 * operational DS: dpn-interfaces list
490 * @param elanInstanceName
491 * name of the Elan to which the interfaces must belong to
493 * Id of the DPN where the interfaces are located
494 * @return the elan dpn interface
496 public static InstanceIdentifier<DpnInterfaces> getElanDpnInterfaceOperationalDataPath(String elanInstanceName,
498 return InstanceIdentifier.builder(ElanDpnInterfaces.class)
499 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName))
500 .child(DpnInterfaces.class, new DpnInterfacesKey(dpId)).build();
503 // elan-tag-name-map Operational Container
504 public ElanTagName getElanInfoByElanTag(long elanTag) {
505 InstanceIdentifier<ElanTagName> elanId = getElanInfoEntriesOperationalDataPath(elanTag);
506 Optional<ElanTagName> existingElanInfo = read(broker,
507 LogicalDatastoreType.OPERATIONAL, elanId);
508 return existingElanInfo.orNull();
511 public static InstanceIdentifier<ElanTagName> getElanInfoEntriesOperationalDataPath(long elanTag) {
512 return InstanceIdentifier.builder(ElanTagNameMap.class).child(ElanTagName.class, new ElanTagNameKey(elanTag))
516 // interface-index-tag operational container
517 public Optional<IfIndexInterface> getInterfaceInfoByInterfaceTag(long interfaceTag) {
518 InstanceIdentifier<IfIndexInterface> interfaceId = getInterfaceInfoEntriesOperationalDataPath(interfaceTag);
519 return read(broker, LogicalDatastoreType.OPERATIONAL, interfaceId);
522 public static InstanceIdentifier<IfIndexInterface> getInterfaceInfoEntriesOperationalDataPath(long interfaceTag) {
523 return InstanceIdentifier.builder(IfIndexesInterfaceMap.class)
524 .child(IfIndexInterface.class, new IfIndexInterfaceKey((int) interfaceTag)).build();
527 public static InstanceIdentifier<ElanDpnInterfacesList> getElanDpnOperationDataPath(String elanInstanceName) {
528 return InstanceIdentifier.builder(ElanDpnInterfaces.class)
529 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName)).build();
532 public ElanDpnInterfacesList getElanDpnInterfacesList(String elanName) {
533 InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanName);
534 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orNull();
537 public ElanDpnInterfaces getElanDpnInterfacesList() {
538 InstanceIdentifier<ElanDpnInterfaces> elanDpnInterfaceId = InstanceIdentifier.builder(ElanDpnInterfaces.class)
540 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orNull();
544 * This method is useful get all ELAN participating CSS dpIds to install
545 * program remote dmac entries and updating remote bc groups for tor
548 * @param elanInstanceName
549 * the elan instance name
550 * @return list of dpIds
552 public List<BigInteger> getParticipatingDpnsInElanInstance(String elanInstanceName) {
553 List<BigInteger> dpIds = new ArrayList<>();
554 InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
555 Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = read(broker,
556 LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
557 if (!existingElanDpnInterfaces.isPresent()) {
560 List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().getDpnInterfaces();
561 for (DpnInterfaces dpnInterface : dpnInterfaces) {
562 dpIds.add(dpnInterface.getDpId());
568 * To check given dpId is already present in Elan instance. This can be used
569 * to program flow entry in external tunnel table when a new access port
570 * added for first time into the ELAN instance
574 * @param elanInstanceName
575 * the elan instance name
576 * @return true if dpId is already present, otherwise return false
578 public boolean isDpnAlreadyPresentInElanInstance(BigInteger dpId, String elanInstanceName) {
579 InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
580 Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = read(broker,
581 LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
582 if (!existingElanDpnInterfaces.isPresent()) {
585 List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().getDpnInterfaces();
586 for (DpnInterfaces dpnInterface : dpnInterfaces) {
587 if (dpnInterface.getDpId().equals(dpId)) {
594 public ElanForwardingTables getElanForwardingList() {
595 InstanceIdentifier<ElanForwardingTables> elanForwardingTableId = InstanceIdentifier
596 .builder(ElanForwardingTables.class).build();
597 return read(broker, LogicalDatastoreType.OPERATIONAL, elanForwardingTableId).orNull();
600 public static long getElanRemoteBroadCastGroupID(long elanTag) {
601 return ElanConstants.ELAN_GID_MIN + elanTag % ElanConstants.ELAN_GID_MIN * 2;
605 * Gets the elan mac table.
609 * @return the elan mac table
611 public MacTable getElanMacTable(String elanName) {
612 return getElanMacTable(broker, elanName);
616 public static MacTable getElanMacTable(DataBroker dataBroker, String elanName) {
617 InstanceIdentifier<MacTable> elanMacTableId = getElanMacTableOperationalDataPath(elanName);
618 return read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanMacTableId).orNull();
621 public static long getElanLocalBCGId(long elanTag) {
622 return ElanConstants.ELAN_GID_MIN + (elanTag % ElanConstants.ELAN_GID_MIN * 2 - 1);
625 public static long getElanRemoteBCGId(long elanTag) {
626 return ElanConstants.ELAN_GID_MIN + elanTag % ElanConstants.ELAN_GID_MIN * 2;
629 public static long getEtreeLeafLocalBCGId(long etreeLeafTag) {
630 return ElanConstants.ELAN_GID_MIN + (etreeLeafTag % ElanConstants.ELAN_GID_MIN * 2 - 1);
633 public static long getEtreeLeafRemoteBCGId(long etreeLeafTag) {
634 return ElanConstants.ELAN_GID_MIN + etreeLeafTag % ElanConstants.ELAN_GID_MIN * 2;
637 public static BigInteger getElanMetadataLabel(long elanTag, boolean isSHFlagSet) {
638 int shBit = isSHFlagSet ? 1 : 0;
639 return BigInteger.valueOf(elanTag).shiftLeft(24).or(BigInteger.valueOf(shBit));
643 * Setting SMAC, DMAC, UDMAC in this DPN and optionally in other DPNs.
647 * @param interfaceInfo
653 * @param configureRemoteFlows
654 * true if remote dmac flows should be configured as well
655 * @param writeFlowGroupTx
657 * @throws ElanException in case of issues creating the flow objects
659 public void setupMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo,
660 long macTimeout, String macAddress, boolean configureRemoteFlows,
661 WriteTransaction writeFlowGroupTx) throws ElanException {
662 synchronized (getElanMacDPNKey(elanInfo.getElanTag(), macAddress, interfaceInfo.getDpId())) {
663 setupKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress, mdsalManager,
665 setupOrigDmacFlows(elanInfo, interfaceInfo, macAddress, configureRemoteFlows, mdsalManager,
666 broker, writeFlowGroupTx);
670 public void setupDMacFlowOnRemoteDpn(ElanInstance elanInfo, InterfaceInfo interfaceInfo, BigInteger dstDpId,
671 String macAddress, WriteTransaction writeFlowTx) throws ElanException {
672 String elanInstanceName = elanInfo.getElanInstanceName();
673 setupRemoteDmacFlow(dstDpId, interfaceInfo.getDpId(), interfaceInfo.getInterfaceTag(), elanInfo.getElanTag(),
674 macAddress, elanInstanceName, writeFlowTx, interfaceInfo.getInterfaceName(), elanInfo);
675 LOG.info("Remote Dmac flow entry created for elan Name:{}, logical port Name:{} and"
676 + " mac address {} on dpn:{}", elanInstanceName, interfaceInfo.getPortName(),
677 macAddress, dstDpId);
681 * Inserts a Flow in SMAC table to state that the MAC has already been
684 private void setupKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
685 String macAddress, IMdsalApiManager mdsalApiManager, WriteTransaction writeFlowGroupTx) {
686 FlowEntity flowEntity = buildKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress);
687 mdsalApiManager.addFlowToTx(flowEntity, writeFlowGroupTx);
688 LOG.debug("Known Smac flow entry created for elan Name:{}, logical Interface port:{} and mac address:{}",
689 elanInfo.getElanInstanceName(), elanInfo.getDescription(), macAddress);
692 public FlowEntity buildKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
694 int lportTag = interfaceInfo.getInterfaceTag();
695 // Matching metadata and eth_src fields
696 List<MatchInfo> mkMatches = new ArrayList<>();
697 mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanInfo.getElanTag(), lportTag),
698 ElanHelper.getElanMetadataMask()));
699 mkMatches.add(new MatchEthernetSource(new MacAddress(macAddress)));
700 List<InstructionInfo> mkInstructions = new ArrayList<>();
701 mkInstructions.add(new InstructionGotoTable(NwConstants.ELAN_DMAC_TABLE));
702 BigInteger dpId = interfaceInfo.getDpId();
703 long elanTag = getElanTag(broker, elanInfo, interfaceInfo);
704 return new FlowEntityBuilder()
706 .setTableId(NwConstants.ELAN_SMAC_TABLE)
707 .setFlowId(getKnownDynamicmacFlowRef(NwConstants.ELAN_SMAC_TABLE, dpId, lportTag, macAddress, elanTag))
709 .setFlowName(elanInfo.getDescription())
710 .setIdleTimeOut((int) macTimeout)
712 .setCookie(ElanConstants.COOKIE_ELAN_KNOWN_SMAC.add(BigInteger.valueOf(elanTag)))
713 .setMatchInfoList(mkMatches)
714 .setInstructionInfoList(mkInstructions)
716 // If Mac timeout is 0, the flow won't be deleted automatically, so no need to get notified
717 .setSendFlowRemFlag(macTimeout != 0)
721 private static Long getElanTag(DataBroker broker, ElanInstance elanInfo, InterfaceInfo interfaceInfo) {
722 EtreeInterface etreeInterface = getEtreeInterfaceByElanInterfaceName(broker, interfaceInfo.getInterfaceName());
723 if (etreeInterface == null || etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
724 return elanInfo.getElanTag();
726 EtreeInstance etreeInstance = elanInfo.getAugmentation(EtreeInstance.class);
727 if (etreeInstance == null) {
728 LOG.warn("EtreeInterface {} is connected to a non-Etree network: {}",
729 interfaceInfo.getInterfaceName(), elanInfo.getElanInstanceName());
730 return elanInfo.getElanTag();
732 return etreeInstance.getEtreeLeafTagVal().getValue();
738 * Installs a Flow in INTERNAL_TUNNEL_TABLE of the affected DPN that sends
739 * the packet through the specified interface if the tunnel_id matches the
740 * interface's lportTag.
742 * @param interfaceInfo
744 * @param mdsalApiManager
745 * the mdsal API manager
746 * @param writeFlowGroupTx
747 * the writeFLowGroup tx
749 public void setupTermDmacFlows(InterfaceInfo interfaceInfo, IMdsalApiManager mdsalApiManager,
750 WriteTransaction writeFlowGroupTx) {
751 BigInteger dpId = interfaceInfo.getDpId();
752 int lportTag = interfaceInfo.getInterfaceTag();
753 Flow flow = MDSALUtil.buildFlowNew(NwConstants.INTERNAL_TUNNEL_TABLE,
754 getIntTunnelTableFlowRef(NwConstants.INTERNAL_TUNNEL_TABLE, lportTag), 5,
755 String.format("%s:%d", "ITM Flow Entry ", lportTag), 0, 0,
756 ITMConstants.COOKIE_ITM.add(BigInteger.valueOf(lportTag)),
757 getTunnelIdMatchForFilterEqualsLPortTag(lportTag),
758 getInstructionsInPortForOutGroup(interfaceInfo.getInterfaceName()));
759 mdsalApiManager.addFlowToTx(dpId, flow, writeFlowGroupTx);
760 LOG.debug("Terminating service table flow entry created on dpn:{} for logical Interface port:{}", dpId,
761 interfaceInfo.getPortName());
765 * Constructs the FlowName for flows installed in the Internal Tunnel Table,
766 * consisting in tableId + elanTag.
772 * @return the Internal tunnel
774 public static String getIntTunnelTableFlowRef(short tableId, int elanTag) {
775 return new StringBuffer().append(tableId).append(elanTag).toString();
779 * Constructs the Matches that checks that the tunnel_id field contains a
783 * lportTag that must be checked against the tunnel_id field
784 * @return the list of match Info
786 public static List<MatchInfo> getTunnelIdMatchForFilterEqualsLPortTag(int lportTag) {
787 List<MatchInfo> mkMatches = new ArrayList<>();
789 mkMatches.add(new MatchTunnelId(BigInteger.valueOf(lportTag)));
794 * Constructs the Instructions that take the packet over a given interface.
797 * Name of the interface where the packet must be sent over. It
798 * can be a local interface or a tunnel interface (internal or
800 * @return the Instruction
802 public List<Instruction> getInstructionsInPortForOutGroup(String ifName) {
803 List<Instruction> mkInstructions = new ArrayList<>();
804 List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
806 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
807 return mkInstructions;
811 * Returns the list of Actions to be taken when sending the packet through
812 * an Elan interface. Note that this interface can refer to an ElanInterface
813 * where the Elan VM is attached to a DPN or an ITM tunnel interface where
814 * Elan traffic can be sent through. In this latter case, the tunnelKey is
815 * mandatory and it can hold serviceId for internal tunnels or the VNI for
822 * @return the egress actions for interface
824 @SuppressWarnings("checkstyle:IllegalCatch")
825 public List<Action> getEgressActionsForInterface(String ifName, Long tunnelKey) {
826 List<Action> listAction = new ArrayList<>();
828 GetEgressActionsForInterfaceInput getEgressActionInput = new GetEgressActionsForInterfaceInputBuilder()
829 .setIntfName(ifName).setTunnelKey(tunnelKey).build();
830 Future<RpcResult<GetEgressActionsForInterfaceOutput>> result = interfaceManagerRpcService
831 .getEgressActionsForInterface(getEgressActionInput);
832 RpcResult<GetEgressActionsForInterfaceOutput> rpcResult = result.get();
833 if (!rpcResult.isSuccessful()) {
834 LOG.debug("RPC Call to Get egress actions for interface {} returned with Errors {}", ifName,
835 rpcResult.getErrors());
837 List<Action> actions = rpcResult.getResult().getAction();
838 listAction = actions;
840 } catch (Exception e) {
841 LOG.warn("Exception when egress actions for interface {}", ifName, e);
846 private void setupOrigDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
847 boolean configureRemoteFlows, IMdsalApiManager mdsalApiManager,
848 DataBroker broker, WriteTransaction writeFlowGroupTx)
849 throws ElanException {
850 BigInteger dpId = interfaceInfo.getDpId();
851 String ifName = interfaceInfo.getInterfaceName();
852 long ifTag = interfaceInfo.getInterfaceTag();
853 String elanInstanceName = elanInfo.getElanInstanceName();
855 Long elanTag = elanInfo.getElanTag();
857 setupLocalDmacFlow(elanTag, dpId, ifName, macAddress, elanInfo, mdsalApiManager, ifTag,
859 LOG.debug("Dmac flow entry created for elan Name:{}, logical port Name:{} mand mac address:{} "
860 + "on dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, dpId);
862 if (!configureRemoteFlows) {
866 List<DpnInterfaces> elanDpns = getInvolvedDpnsInElan(elanInstanceName);
867 if (elanDpns == null) {
871 for (DpnInterfaces elanDpn : elanDpns) {
873 if (elanDpn.getDpId().equals(dpId)) {
877 // Check for the Remote DPN present in Inventory Manager
878 if (!isDpnPresent(elanDpn.getDpId())) {
882 // For remote DPNs a flow is needed to indicate that packets of this ELAN going to this MAC need to be
883 // forwarded through the appropriate ITM tunnel
884 setupRemoteDmacFlow(elanDpn.getDpId(), // srcDpn (the remote DPN in this case)
885 dpId, // dstDpn (the local DPN)
886 interfaceInfo.getInterfaceTag(), // lportTag of the local interface
887 elanTag, // identifier of the Elan
888 macAddress, // MAC to be programmed in remote DPN
889 elanInstanceName, writeFlowGroupTx, ifName, elanInfo
891 LOG.debug("Remote Dmac flow entry created for elan Name:{}, logical port Name:{} and mac address:{} on"
892 + " dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, elanDpn.getDpId());
895 // TODO: Make sure that the same is performed against the ElanDevices.
898 public List<DpnInterfaces> getInvolvedDpnsInElan(String elanName) {
899 return elanInstanceManager.getElanDPNByName(elanName);
902 private void setupLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
903 ElanInstance elanInfo, IMdsalApiManager mdsalApiManager, long ifTag, WriteTransaction writeFlowGroupTx) {
904 Flow flowEntity = buildLocalDmacFlowEntry(elanTag, dpId, ifName, macAddress, elanInfo, ifTag);
905 mdsalApiManager.addFlowToTx(dpId, flowEntity, writeFlowGroupTx);
906 installEtreeLocalDmacFlow(elanTag, dpId, ifName, macAddress, elanInfo,
907 mdsalApiManager, ifTag, writeFlowGroupTx);
910 private void installEtreeLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
911 ElanInstance elanInfo, IMdsalApiManager mdsalApiManager, long ifTag, WriteTransaction writeFlowGroupTx) {
912 EtreeInterface etreeInterface = getEtreeInterfaceByElanInterfaceName(broker, ifName);
913 if (etreeInterface != null) {
914 if (etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
915 EtreeLeafTagName etreeTagName = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
916 if (etreeTagName == null) {
917 LOG.warn("Interface {} seems like it belongs to Etree but etreeTagName from elanTag {} is null",
920 Flow flowEntity = buildLocalDmacFlowEntry(etreeTagName.getEtreeLeafTag().getValue(), dpId, ifName,
921 macAddress, elanInfo, ifTag);
922 mdsalApiManager.addFlowToTx(dpId, flowEntity, writeFlowGroupTx);
928 public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, long lporTag, String macAddress,
930 return new StringBuffer().append(tableId).append(elanTag).append(dpId).append(lporTag).append(macAddress)
934 public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, BigInteger remoteDpId,
935 String macAddress, long elanTag) {
936 return new StringBuffer().append(tableId).append(elanTag).append(dpId).append(remoteDpId).append(macAddress)
940 public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, String macAddress, long elanTag) {
941 return new StringBuffer().append(tableId).append(elanTag).append(dpId).append(macAddress).toString();
944 public static String getKnownDynamicmacFlowRef(short elanDmacTable, BigInteger dpId, String extDeviceNodeId,
945 String dstMacAddress, long elanTag, boolean shFlag) {
946 return new StringBuffer().append(elanDmacTable).append(elanTag).append(dpId).append(extDeviceNodeId)
947 .append(dstMacAddress).append(shFlag).toString();
951 * Builds the flow to be programmed in the DMAC table of the local DPN (that
952 * is, where the MAC is attached to). This flow consists in:
954 * <p>Match: + elanTag in metadata + packet goes to a MAC locally attached
955 * Actions: + optionally, pop-vlan + set-vlan-id + output to ifName's
972 public Flow buildLocalDmacFlowEntry(long elanTag, BigInteger dpId, String ifName, String macAddress,
973 ElanInstance elanInfo, long ifTag) {
975 List<MatchInfo> mkMatches = new ArrayList<>();
976 mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
977 mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddress)));
979 List<Instruction> mkInstructions = new ArrayList<>();
980 List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
981 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
982 Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
983 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, ifTag, macAddress, elanTag), 20,
984 elanInfo.getElanInstanceName(), 0, 0, ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(
985 BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
990 public void setupRemoteDmacFlow(BigInteger srcDpId, BigInteger destDpId, int lportTag, long elanTag, String
991 macAddress, String displayName, WriteTransaction writeFlowGroupTx, String interfaceName, ElanInstance
992 elanInstance) throws ElanException {
993 if (interfaceManager.isExternalInterface(interfaceName)) {
994 LOG.debug("Ignoring install remote DMAC {} flow on provider interface {} elan {}",
995 macAddress, interfaceName, elanInstance.getElanInstanceName());
999 // if openstack-vni-semantics are enforced, segmentation ID is passed as network VNI for VxLAN based provider
1000 // networks, 0 otherwise
1001 long lportTagOrVni = !isOpenStackVniSemanticsEnforced() ? lportTag : isVxlan(elanInstance)
1002 ? elanInstance.getSegmentationId() : 0;
1003 flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTagOrVni, elanTag, macAddress, displayName,
1005 mdsalManager.addFlowToTx(srcDpId, flowEntity, writeFlowGroupTx);
1006 setupEtreeRemoteDmacFlow(srcDpId, destDpId, lportTagOrVni, elanTag, macAddress, displayName, interfaceName,
1007 writeFlowGroupTx, elanInstance);
1010 private void setupEtreeRemoteDmacFlow(BigInteger srcDpId, BigInteger destDpId, long lportTagOrVni, long elanTag,
1011 String macAddress, String displayName, String interfaceName,
1012 WriteTransaction writeFlowGroupTx, ElanInstance elanInstance)
1013 throws ElanException {
1015 EtreeInterface etreeInterface = getEtreeInterfaceByElanInterfaceName(broker, interfaceName);
1016 if (etreeInterface != null) {
1017 if (etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
1018 EtreeLeafTagName etreeTagName = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
1019 if (etreeTagName == null) {
1020 LOG.warn("Interface " + interfaceName
1021 + " seems like it belongs to Etree but etreeTagName from elanTag " + elanTag + " is null.");
1023 flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTagOrVni,
1024 etreeTagName.getEtreeLeafTag().getValue(), macAddress, displayName, elanInstance);
1025 mdsalManager.addFlowToTx(srcDpId, flowEntity, writeFlowGroupTx);
1032 * Builds a Flow to be programmed in a remote DPN's DMAC table. This flow
1033 * consists in: Match: + elanTag in packet's metadata + packet going to a
1034 * MAC known to be located in another DPN Actions: + set_tunnel_id
1035 * + output ITM internal tunnel interface with the other DPN
1041 * @param lportTagOrVni
1042 * lportTag or network VNI
1047 * @param displayName
1049 * @return the flow remote Dmac
1050 * @throws ElanException in case of issues creating the flow objects
1052 @SuppressWarnings("checkstyle:IllegalCatch")
1053 public Flow buildRemoteDmacFlowEntry(BigInteger srcDpId, BigInteger destDpId, long lportTagOrVni, long elanTag,
1054 String macAddress, String displayName, ElanInstance elanInstance) throws ElanException {
1055 List<MatchInfo> mkMatches = new ArrayList<>();
1056 mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
1057 mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddress)));
1059 List<Instruction> mkInstructions = new ArrayList<>();
1061 // List of Action for the provided Source and Destination DPIDs
1063 List<Action> actions = null;
1064 if (isVlan(elanInstance) || isFlat(elanInstance)) {
1065 String interfaceName = getExternalElanInterface(elanInstance.getElanInstanceName(), srcDpId);
1066 if (null == interfaceName) {
1067 LOG.info("buildRemoteDmacFlowEntry: Could not find interfaceName for {} {}", srcDpId,
1070 actions = getEgressActionsForInterface(interfaceName, null);
1071 } else if (isVxlan(elanInstance)) {
1072 actions = elanItmUtils.getInternalTunnelItmEgressAction(srcDpId, destDpId, lportTagOrVni);
1074 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
1075 } catch (Exception e) {
1076 LOG.error("Could not get egress actions to add to flow for srcDpId=" + srcDpId + ", destDpId=" + destDpId
1077 + ", lportTag/VNI=" + lportTagOrVni, e);
1080 Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
1081 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, srcDpId, destDpId, macAddress, elanTag),
1083 displayName, 0, /* idleTimeout */
1084 0, /* hardTimeout */
1085 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
1091 public void deleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, MacEntry macEntry,
1092 WriteTransaction deleteFlowGroupTx) {
1093 if (elanInfo == null || interfaceInfo == null) {
1096 String macAddress = macEntry.getMacAddress().getValue();
1097 synchronized (getElanMacDPNKey(elanInfo.getElanTag(), macAddress, interfaceInfo.getDpId())) {
1098 deleteMacFlows(elanInfo, interfaceInfo, macAddress, /* alsoDeleteSMAC */ true, deleteFlowGroupTx);
1102 public void deleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1103 boolean deleteSmac, WriteTransaction deleteFlowGroupTx) {
1104 String elanInstanceName = elanInfo.getElanInstanceName();
1105 List<DpnInterfaces> remoteFEs = getInvolvedDpnsInElan(elanInstanceName);
1106 BigInteger srcdpId = interfaceInfo.getDpId();
1107 boolean isFlowsRemovedInSrcDpn = false;
1108 for (DpnInterfaces dpnInterface : remoteFEs) {
1109 Long elanTag = elanInfo.getElanTag();
1110 BigInteger dstDpId = dpnInterface.getDpId();
1111 if (executeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1112 elanTag, dstDpId, deleteFlowGroupTx)) {
1113 isFlowsRemovedInSrcDpn = true;
1115 executeEtreeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1116 elanTag, dstDpId, deleteFlowGroupTx);
1118 if (!isFlowsRemovedInSrcDpn) {
1119 deleteSmacAndDmacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, deleteFlowGroupTx);
1123 private void executeEtreeDeleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1124 boolean deleteSmac, String elanInstanceName, BigInteger srcdpId, Long elanTag, BigInteger dstDpId,
1125 WriteTransaction deleteFlowGroupTx) {
1126 EtreeLeafTagName etreeLeafTag = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
1127 if (etreeLeafTag != null) {
1128 executeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1129 etreeLeafTag.getEtreeLeafTag().getValue(), dstDpId, deleteFlowGroupTx);
1133 private boolean executeDeleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1134 boolean deleteSmac, String elanInstanceName, BigInteger srcdpId, Long elanTag, BigInteger dstDpId,
1135 WriteTransaction deleteFlowGroupTx) {
1136 boolean isFlowsRemovedInSrcDpn = false;
1137 if (dstDpId.equals(srcdpId)) {
1138 isFlowsRemovedInSrcDpn = true;
1139 deleteSmacAndDmacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, deleteFlowGroupTx);
1140 } else if (isDpnPresent(dstDpId)) {
1142 .removeFlowToTx(dstDpId,
1143 MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, getKnownDynamicmacFlowRef(
1144 NwConstants.ELAN_DMAC_TABLE, dstDpId, srcdpId, macAddress, elanTag)),
1146 LOG.debug("Dmac flow entry deleted for elan:{}, logical interface port:{} and mac address:{} on dpn:{}",
1147 elanInstanceName, interfaceInfo.getPortName(), macAddress, dstDpId);
1149 return isFlowsRemovedInSrcDpn;
1152 private void deleteSmacAndDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1153 boolean deleteSmac, WriteTransaction deleteFlowGroupTx) {
1154 String elanInstanceName = elanInfo.getElanInstanceName();
1155 long ifTag = interfaceInfo.getInterfaceTag();
1156 BigInteger srcdpId = interfaceInfo.getDpId();
1157 Long elanTag = elanInfo.getElanTag();
1160 .removeFlowToTx(srcdpId,
1161 MDSALUtil.buildFlow(NwConstants.ELAN_SMAC_TABLE, getKnownDynamicmacFlowRef(
1162 NwConstants.ELAN_SMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)),
1165 mdsalManager.removeFlowToTx(srcdpId,
1166 MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE,
1167 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)),
1169 LOG.debug("All the required flows deleted for elan:{}, logical Interface port:{} and MAC address:{} on dpn:{}",
1170 elanInstanceName, interfaceInfo.getPortName(), macAddress, srcdpId);
1174 * Updates the Elan information in the Operational DS. It also updates the
1175 * ElanInstance in the Config DS by setting the adquired elanTag.
1181 * @param elanInstanceAdded
1182 * the elan instance added
1183 * @param elanInterfaces
1184 * the elan interfaces
1188 public static void updateOperationalDataStore(DataBroker broker, IdManagerService idManager,
1189 ElanInstance elanInstanceAdded, List<String> elanInterfaces, WriteTransaction tx) {
1190 String elanInstanceName = elanInstanceAdded.getElanInstanceName();
1191 Long elanTag = elanInstanceAdded.getElanTag();
1192 if (elanTag == null || elanTag == 0L) {
1193 elanTag = retrieveNewElanTag(idManager, elanInstanceName);
1195 Elan elanInfo = new ElanBuilder().setName(elanInstanceName).setElanInterfaces(elanInterfaces)
1196 .setKey(new ElanKey(elanInstanceName)).build();
1198 // Add the ElanState in the elan-state operational data-store
1199 tx.put(LogicalDatastoreType.OPERATIONAL, getElanInstanceOperationalDataPath(elanInstanceName),
1200 elanInfo, WriteTransaction.CREATE_MISSING_PARENTS);
1202 // Add the ElanMacTable in the elan-mac-table operational data-store
1203 MacTable elanMacTable = new MacTableBuilder().setKey(new MacTableKey(elanInstanceName)).build();
1204 tx.put(LogicalDatastoreType.OPERATIONAL, getElanMacTableOperationalDataPath(elanInstanceName),
1205 elanMacTable, WriteTransaction.CREATE_MISSING_PARENTS);
1207 ElanTagNameBuilder elanTagNameBuilder = new ElanTagNameBuilder().setElanTag(elanTag)
1208 .setKey(new ElanTagNameKey(elanTag)).setName(elanInstanceName);
1209 long etreeLeafTag = -1;
1210 if (isEtreeInstance(elanInstanceAdded)) {
1211 etreeLeafTag = retrieveNewElanTag(idManager,elanInstanceName + ElanConstants
1213 EtreeLeafTagName etreeLeafTagName = new EtreeLeafTagNameBuilder()
1214 .setEtreeLeafTag(new EtreeLeafTag(etreeLeafTag)).build();
1215 elanTagNameBuilder.addAugmentation(EtreeLeafTagName.class, etreeLeafTagName);
1216 addTheLeafTagAsElanTag(broker, elanInstanceName, etreeLeafTag, tx);
1218 ElanTagName elanTagName = elanTagNameBuilder.build();
1220 // Add the ElanTag to ElanName in the elan-tag-name Operational
1222 tx.put(LogicalDatastoreType.OPERATIONAL,
1223 getElanInfoEntriesOperationalDataPath(elanTag), elanTagName);
1225 // Updates the ElanInstance Config DS by setting the just acquired
1227 ElanInstanceBuilder elanInstanceBuilder = new ElanInstanceBuilder().setElanInstanceName(elanInstanceName)
1228 .setDescription(elanInstanceAdded.getDescription())
1229 .setMacTimeout(elanInstanceAdded.getMacTimeout() == null ? ElanConstants.DEFAULT_MAC_TIME_OUT
1230 : elanInstanceAdded.getMacTimeout())
1231 .setKey(elanInstanceAdded.getKey()).setElanTag(elanTag);
1232 if (isEtreeInstance(elanInstanceAdded)) {
1233 EtreeInstance etreeInstance = new EtreeInstanceBuilder().setEtreeLeafTagVal(new EtreeLeafTag(etreeLeafTag))
1235 elanInstanceBuilder.addAugmentation(EtreeInstance.class, etreeInstance);
1237 ElanInstance elanInstanceWithTag = elanInstanceBuilder.build();
1238 tx.merge(LogicalDatastoreType.CONFIGURATION, ElanHelper.getElanInstanceConfigurationDataPath(elanInstanceName),
1239 elanInstanceWithTag, true);
1242 private static void addTheLeafTagAsElanTag(DataBroker broker, String elanInstanceName, long etreeLeafTag,
1243 WriteTransaction tx) {
1244 ElanTagName etreeTagAsElanTag = new ElanTagNameBuilder().setElanTag(etreeLeafTag)
1245 .setKey(new ElanTagNameKey(etreeLeafTag)).setName(elanInstanceName).build();
1246 tx.put(LogicalDatastoreType.OPERATIONAL,
1247 getElanInfoEntriesOperationalDataPath(etreeLeafTag), etreeTagAsElanTag);
1250 private static boolean isEtreeInstance(ElanInstance elanInstanceAdded) {
1251 return elanInstanceAdded.getAugmentation(EtreeInstance.class) != null;
1254 public boolean isDpnPresent(BigInteger dpnId) {
1255 String dpn = String.format("%s:%s", "openflow", dpnId);
1256 NodeId nodeId = new NodeId(dpn);
1258 InstanceIdentifier<Node> node = InstanceIdentifier.builder(Nodes.class).child(Node.class, new NodeKey(nodeId))
1260 return read(broker, LogicalDatastoreType.CONFIGURATION, node).isPresent();
1263 public static ServicesInfo getServiceInfo(String elanInstanceName, String interfaceName) {
1264 return InterfaceServiceUtil.buildServiceInfo(elanInstanceName + "." + interfaceName,
1265 ElanConstants.ELAN_SERVICE_PRIORITY);
1268 public static BoundServices getBoundServices(String serviceName, short servicePriority, int flowPriority,
1269 BigInteger cookie, List<Instruction> instructions) {
1270 StypeOpenflowBuilder augBuilder = new StypeOpenflowBuilder().setFlowCookie(cookie).setFlowPriority(flowPriority)
1271 .setInstruction(instructions);
1272 return new BoundServicesBuilder().setKey(new BoundServicesKey(servicePriority)).setServiceName(serviceName)
1273 .setServicePriority(servicePriority).setServiceType(ServiceTypeFlowBased.class)
1274 .addAugmentation(StypeOpenflow.class, augBuilder.build()).build();
1277 public static InstanceIdentifier<BoundServices> buildServiceId(String interfaceName, short serviceIndex) {
1278 return InstanceIdentifier.builder(ServiceBindings.class)
1279 .child(ServicesInfo.class, new ServicesInfoKey(interfaceName, ServiceModeIngress.class))
1280 .child(BoundServices.class, new BoundServicesKey(serviceIndex)).build();
1283 public static List<MatchInfo> getTunnelMatchesForServiceId(int elanTag) {
1284 List<MatchInfo> mkMatches = new ArrayList<>();
1285 // Matching metadata
1286 mkMatches.add(new MatchTunnelId(BigInteger.valueOf(elanTag)));
1291 public void removeTerminatingServiceAction(BigInteger destDpId, int serviceId) {
1292 RemoveTerminatingServiceActionsInput input = new RemoveTerminatingServiceActionsInputBuilder()
1293 .setDpnId(destDpId).setServiceId(serviceId).build();
1294 Future<RpcResult<Void>> futureObject = itmRpcService.removeTerminatingServiceActions(input);
1296 RpcResult<Void> result = futureObject.get();
1297 if (result.isSuccessful()) {
1298 LOG.debug("Successfully completed removeTerminatingServiceActions for ELAN with serviceId {} on "
1299 + "dpn {}", serviceId, destDpId);
1301 LOG.debug("Failure in removeTerminatingServiceAction RPC call for ELAN with serviceId {} on "
1302 + "dpn {}", serviceId, destDpId);
1304 } catch (InterruptedException | ExecutionException e) {
1305 LOG.error("Error in RPC call removeTerminatingServiceActions for ELAN with serviceId {} on "
1306 + "dpn {}: {}", serviceId, destDpId, e);
1311 * Gets the external tunnel.
1313 * @param sourceDevice
1315 * @param destinationDevice
1316 * the destination device
1317 * @param datastoreType
1318 * the datastore type
1319 * @return the external tunnel
1321 public ExternalTunnel getExternalTunnel(String sourceDevice, String destinationDevice,
1322 LogicalDatastoreType datastoreType) {
1323 Class<? extends TunnelTypeBase> tunType = TunnelTypeVxlan.class;
1324 InstanceIdentifier<ExternalTunnel> iid = InstanceIdentifier.builder(ExternalTunnelList.class)
1325 .child(ExternalTunnel.class, new ExternalTunnelKey(destinationDevice, sourceDevice, tunType)).build();
1326 return read(broker, datastoreType, iid).orNull();
1330 * Gets the external tunnel.
1332 * @param interfaceName
1333 * the interface name
1334 * @param datastoreType
1335 * the datastore type
1336 * @return the external tunnel
1338 public ExternalTunnel getExternalTunnel(String interfaceName, LogicalDatastoreType datastoreType) {
1339 ExternalTunnel externalTunnel = null;
1340 List<ExternalTunnel> externalTunnels = getAllExternalTunnels(datastoreType);
1341 for (ExternalTunnel tunnel : externalTunnels) {
1342 if (StringUtils.equalsIgnoreCase(interfaceName, tunnel.getTunnelInterfaceName())) {
1343 externalTunnel = tunnel;
1347 return externalTunnel;
1351 * Gets the all external tunnels.
1353 * @param datastoreType
1354 * the data store type
1355 * @return the all external tunnels
1357 public List<ExternalTunnel> getAllExternalTunnels(LogicalDatastoreType datastoreType) {
1358 InstanceIdentifier<ExternalTunnelList> iid = InstanceIdentifier.builder(ExternalTunnelList.class).build();
1359 return read(broker, datastoreType, iid).toJavaUtil().map(ExternalTunnelList::getExternalTunnel).orElse(
1360 Collections.emptyList());
1363 public static List<MatchInfo> buildMatchesForElanTagShFlagAndDstMac(long elanTag, boolean shFlag, String macAddr) {
1364 List<MatchInfo> mkMatches = new ArrayList<>();
1366 new MatchMetadata(getElanMetadataLabel(elanTag, shFlag), MetaDataUtil.METADATA_MASK_SERVICE_SH_FLAG));
1367 mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddr)));
1372 * Checks if is interface operational.
1374 * @param interfaceName
1375 * the interface name
1378 * @return true, if is interface operational
1380 public static boolean isInterfaceOperational(String interfaceName, DataBroker dataBroker) {
1381 if (StringUtils.isBlank(interfaceName)) {
1384 Interface ifState = getInterfaceStateFromOperDS(interfaceName, dataBroker);
1385 if (ifState == null) {
1388 return ifState.getOperStatus() == OperStatus.Up && ifState.getAdminStatus() == AdminStatus.Up;
1392 * Gets the interface state from operational ds.
1394 * @param interfaceName
1395 * the interface name
1398 * @return the interface state from oper ds
1400 public static org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1401 .ietf.interfaces.rev140508.interfaces.state.Interface getInterfaceStateFromOperDS(
1402 String interfaceName, DataBroker dataBroker) {
1403 InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1404 .ietf.interfaces.rev140508.interfaces.state.Interface> ifStateId = createInterfaceStateInstanceIdentifier(
1406 return MDSALUtil.read(dataBroker, LogicalDatastoreType.OPERATIONAL, ifStateId).orNull();
1410 * Creates the interface state instance identifier.
1412 * @param interfaceName
1413 * the interface name
1414 * @return the instance identifier
1416 public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1417 .ietf.interfaces.rev140508.interfaces.state.Interface> createInterfaceStateInstanceIdentifier(
1418 String interfaceName) {
1419 InstanceIdentifierBuilder<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1420 .ietf.interfaces.rev140508.interfaces.state.Interface> idBuilder = InstanceIdentifier
1421 .builder(InterfacesState.class)
1422 .child(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1423 .ietf.interfaces.rev140508.interfaces.state.Interface.class,
1424 new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1425 .ietf.interfaces.rev140508.interfaces.state.InterfaceKey(
1427 return idBuilder.build();
1430 public static CheckedFuture<Void, TransactionCommitFailedException> waitForTransactionToComplete(
1431 WriteTransaction tx) {
1432 CheckedFuture<Void, TransactionCommitFailedException> futures = tx.submit();
1435 } catch (InterruptedException | ExecutionException e) {
1436 LOG.error("Error writing to datastore {}", e);
1441 public static boolean isVxlanNetwork(DataBroker broker, String elanInstanceName) {
1442 ElanInstance elanInstance = getElanInstanceByName(broker, elanInstanceName);
1443 return elanInstance != null && isVxlan(elanInstance);
1446 public static boolean isVxlan(ElanInstance elanInstance) {
1447 return elanInstance != null && elanInstance.getSegmentType() != null
1448 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1449 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId() != 0;
1452 private static boolean isVxlanSegment(ElanInstance elanInstance) {
1453 if (elanInstance != null) {
1454 List<ElanSegments> elanSegments = elanInstance.getElanSegments();
1455 if (elanSegments != null) {
1456 for (ElanSegments segment : elanSegments) {
1457 if (segment != null && segment.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1458 && segment.getSegmentationId() != null
1459 && segment.getSegmentationId().longValue() != 0) {
1468 public static boolean isVxlanNetworkOrVxlanSegment(ElanInstance elanInstance) {
1469 return isVxlan(elanInstance) || isVxlanSegment(elanInstance);
1472 public static Long getVxlanSegmentationId(ElanInstance elanInstance) {
1473 Long segmentationId = 0L;
1475 if (elanInstance != null && elanInstance.getSegmentType() != null
1476 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1477 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId().longValue() != 0) {
1478 segmentationId = elanInstance.getSegmentationId();
1480 for (ElanSegments segment: elanInstance.getElanSegments()) {
1481 if (segment != null && segment.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1482 && segment.getSegmentationId() != null
1483 && segment.getSegmentationId().longValue() != 0) {
1484 segmentationId = segment.getSegmentationId();
1488 return segmentationId;
1491 public static boolean isVlan(ElanInstance elanInstance) {
1492 return elanInstance != null && elanInstance.getSegmentType() != null
1493 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVlan.class)
1494 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId() != 0;
1497 public static boolean isFlat(ElanInstance elanInstance) {
1498 return elanInstance != null && elanInstance.getSegmentType() != null
1499 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeFlat.class);
1502 public void addDmacRedirectToDispatcherFlows(Long elanTag, String displayName,
1503 String macAddress, List<BigInteger> dpnIds) {
1504 for (BigInteger dpId : dpnIds) {
1505 WriteTransaction writeTx = broker.newWriteOnlyTransaction();
1506 mdsalManager.addFlowToTx(buildDmacRedirectToDispatcherFlow(dpId, macAddress, displayName, elanTag),
1512 public void removeDmacRedirectToDispatcherFlows(Long elanTag, String macAddress, List<BigInteger> dpnIds) {
1513 for (BigInteger dpId : dpnIds) {
1514 String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, macAddress, elanTag);
1515 mdsalManager.removeFlow(dpId, MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, flowId));
1519 public static FlowEntity buildDmacRedirectToDispatcherFlow(BigInteger dpId, String dstMacAddress,
1520 String displayName, long elanTag) {
1521 List<MatchInfo> matches = new ArrayList<>();
1522 matches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
1523 matches.add(new MatchEthernetDestination(new MacAddress(dstMacAddress)));
1524 List<InstructionInfo> instructions = new ArrayList<>();
1525 List<ActionInfo> actions = new ArrayList<>();
1526 actions.add(new ActionNxResubmit(NwConstants.LPORT_DISPATCHER_TABLE));
1528 instructions.add(new InstructionApplyActions(actions));
1529 String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, dstMacAddress, elanTag);
1530 FlowEntity flow = MDSALUtil.buildFlowEntity(dpId, NwConstants.ELAN_DMAC_TABLE, flowId, 20, displayName, 0, 0,
1531 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)),
1532 matches, instructions);
1537 * Add Mac Address to ElanInterfaceForwardingEntries and ElanForwardingTables
1538 * Install SMAC and DMAC flows.
1540 public void addMacEntryToDsAndSetupFlows(IInterfaceManager interfaceManager, String interfaceName,
1541 String macAddress, String elanName, WriteTransaction interfaceTx, WriteTransaction flowTx, int macTimeOut)
1542 throws ElanException {
1543 LOG.trace("Adding mac address {} and interface name {} to ElanInterfaceForwardingEntries and "
1544 + "ElanForwardingTables DS", macAddress, interfaceName);
1545 BigInteger timeStamp = new BigInteger(String.valueOf(System.currentTimeMillis()));
1546 PhysAddress physAddress = new PhysAddress(macAddress);
1547 MacEntry macEntry = new MacEntryBuilder().setInterface(interfaceName).setMacAddress(physAddress)
1548 .setKey(new MacEntryKey(physAddress)).setControllerLearnedForwardingEntryTimestamp(timeStamp)
1549 .setIsStaticAddress(false).build();
1550 InstanceIdentifier<MacEntry> macEntryId = ElanUtils
1551 .getInterfaceMacEntriesIdentifierOperationalDataPath(interfaceName, physAddress);
1552 interfaceTx.put(LogicalDatastoreType.OPERATIONAL, macEntryId, macEntry);
1553 InstanceIdentifier<MacEntry> elanMacEntryId = ElanUtils.getMacEntryOperationalDataPath(elanName, physAddress);
1554 interfaceTx.put(LogicalDatastoreType.OPERATIONAL, elanMacEntryId, macEntry);
1555 ElanInstance elanInstance = ElanUtils.getElanInstanceByName(broker, elanName);
1556 setupMacFlows(elanInstance, interfaceManager.getInterfaceInfo(interfaceName), macTimeOut, macAddress, true,
1561 * Remove Mac Address from ElanInterfaceForwardingEntries and ElanForwardingTables
1562 * Remove SMAC and DMAC flows.
1564 public void deleteMacEntryFromDsAndRemoveFlows(IInterfaceManager interfaceManager, String interfaceName,
1565 String macAddress, String elanName, WriteTransaction interfaceTx, WriteTransaction flowTx) {
1566 LOG.trace("Deleting mac address {} and interface name {} from ElanInterfaceForwardingEntries "
1567 + "and ElanForwardingTables DS", macAddress, interfaceName);
1568 PhysAddress physAddress = new PhysAddress(macAddress);
1569 MacEntry macEntry = getInterfaceMacEntriesOperationalDataPath(interfaceName, physAddress);
1570 InterfaceInfo interfaceInfo = interfaceManager.getInterfaceInfo(interfaceName);
1571 if (macEntry != null && interfaceInfo != null) {
1572 deleteMacFlows(ElanUtils.getElanInstanceByName(broker, elanName), interfaceInfo, macEntry, flowTx);
1574 interfaceTx.delete(LogicalDatastoreType.OPERATIONAL,
1575 ElanUtils.getInterfaceMacEntriesIdentifierOperationalDataPath(interfaceName, physAddress));
1576 interfaceTx.delete(LogicalDatastoreType.OPERATIONAL,
1577 ElanUtils.getMacEntryOperationalDataPath(elanName, physAddress));
1580 public String getExternalElanInterface(String elanInstanceName, BigInteger dpnId) {
1581 DpnInterfaces dpnInterfaces = getElanInterfaceInfoByElanDpn(elanInstanceName, dpnId);
1582 if (dpnInterfaces == null || dpnInterfaces.getInterfaces() == null) {
1583 LOG.trace("Elan {} does not have interfaces in DPN {}", elanInstanceName, dpnId);
1587 for (String dpnInterface : dpnInterfaces.getInterfaces()) {
1588 if (interfaceManager.isExternalInterface(dpnInterface)) {
1589 return dpnInterface;
1593 LOG.trace("Elan {} does not have any external interace attached to DPN {}", elanInstanceName, dpnId);
1597 public static String getElanMacDPNKey(long elanTag, String macAddress, BigInteger dpnId) {
1598 String elanMacDmacDpnKey = "MAC-" + macAddress + " ELAN_TAG-" + elanTag + "DPN_ID-" + dpnId;
1599 return elanMacDmacDpnKey.intern();
1602 public static String getElanMacKey(long elanTag, String macAddress) {
1603 String elanMacKey = "MAC-" + macAddress + " ELAN_TAG-" + elanTag;
1604 return elanMacKey.intern();
1607 // TODO This should return a collection of futures
1608 public static void addToListenableFutureIfTxException(RuntimeException exception,
1609 List<ListenableFuture<Void>> futures) {
1610 Throwable cause = exception.getCause();
1611 if (cause != null && cause instanceof TransactionCommitFailedException) {
1612 futures.add(Futures.immediateFailedCheckedFuture((TransactionCommitFailedException) cause));
1616 public static List<PhysAddress> getPhysAddress(List<String> macAddress) {
1617 Preconditions.checkNotNull(macAddress, "macAddress cannot be null");
1618 List<PhysAddress> physAddresses = new ArrayList<>();
1619 for (String mac : macAddress) {
1620 physAddresses.add(new PhysAddress(mac));
1622 return physAddresses;
1625 public static List<StaticMacEntries> getStaticMacEntries(List<String> staticMacAddresses) {
1626 if (isEmpty(staticMacAddresses)) {
1627 return Collections.EMPTY_LIST;
1629 StaticMacEntriesBuilder staticMacEntriesBuilder = new StaticMacEntriesBuilder();
1630 List<StaticMacEntries> staticMacEntries = new ArrayList<>();
1631 List<PhysAddress> physAddressList = getPhysAddress(staticMacAddresses);
1632 for (PhysAddress physAddress : physAddressList) {
1633 staticMacEntries.add(staticMacEntriesBuilder.setMacAddress(physAddress).build());
1635 return staticMacEntries;
1638 public static InstanceIdentifier<StaticMacEntries> getStaticMacEntriesCfgDataPathIdentifier(String interfaceName,
1639 String macAddress) {
1640 return InstanceIdentifier.builder(ElanInterfaces.class)
1641 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).child(StaticMacEntries.class,
1642 new StaticMacEntriesKey(new PhysAddress(macAddress))).build();
1645 public static List<StaticMacEntries> getDeletedEntries(List<StaticMacEntries> originalStaticMacEntries,
1646 List<StaticMacEntries> updatedStaticMacEntries) {
1647 if (isEmpty(originalStaticMacEntries)) {
1648 return Collections.EMPTY_LIST;
1650 List<StaticMacEntries> deleted = Lists.newArrayList(originalStaticMacEntries);
1651 if (isNotEmpty(updatedStaticMacEntries)) {
1652 deleted.removeAll(updatedStaticMacEntries);
1657 public static <T> List<T> diffOf(List<T> orig, List<T> updated) {
1658 if (isEmpty(orig)) {
1659 return Collections.EMPTY_LIST;
1661 List<T> diff = Lists.newArrayList(orig);
1662 if (isNotEmpty(updated)) {
1663 diff.removeAll(updated);
1668 public static void segregateToBeDeletedAndAddEntries(List<StaticMacEntries> originalStaticMacEntries,
1669 List<StaticMacEntries> updatedStaticMacEntries) {
1670 if (isNotEmpty(updatedStaticMacEntries)) {
1671 List<StaticMacEntries> existingClonedStaticMacEntries = new ArrayList<>();
1672 if (isNotEmpty(originalStaticMacEntries)) {
1673 existingClonedStaticMacEntries.addAll(0, originalStaticMacEntries);
1674 originalStaticMacEntries.removeAll(updatedStaticMacEntries);
1675 updatedStaticMacEntries.removeAll(existingClonedStaticMacEntries);
1680 public static boolean isEmpty(Collection collection) {
1681 return collection == null || collection.isEmpty();
1684 public static boolean isNotEmpty(Collection collection) {
1685 return !isEmpty(collection);
1688 public static void setElanInstancToDpnsCache(Map<String, Set<DpnInterfaces>> elanInstancToDpnsCache) {
1689 ElanUtils.elanInstancToDpnsCache = elanInstancToDpnsCache;
1692 public static Set<DpnInterfaces> getElanInvolvedDPNsFromCache(String elanName) {
1693 return elanInstancToDpnsCache.get(elanName);
1696 public static void addDPNInterfaceToElanInCache(String elanName, DpnInterfaces dpnInterfaces) {
1697 elanInstancToDpnsCache.computeIfAbsent(elanName, key -> new HashSet<>()).add(dpnInterfaces);
1700 public static void removeDPNInterfaceFromElanInCache(String elanName, DpnInterfaces dpnInterfaces) {
1701 elanInstancToDpnsCache.computeIfAbsent(elanName, key -> new HashSet<>()).remove(dpnInterfaces);
1704 public Optional<IpAddress> getSourceIpAddress(Ethernet ethernet) {
1705 Optional<IpAddress> srcIpAddress = Optional.absent();
1706 if (ethernet.getPayload() == null) {
1707 return srcIpAddress;
1709 byte[] ipAddrBytes = null;
1710 if (ethernet.getPayload() instanceof IPv4) {
1711 IPv4 ipv4 = (IPv4) ethernet.getPayload();
1712 ipAddrBytes = Ints.toByteArray(ipv4.getSourceAddress());
1713 } else if (ethernet.getPayload() instanceof ARP) {
1714 ipAddrBytes = ((ARP) ethernet.getPayload()).getSenderProtocolAddress();
1716 if (ipAddrBytes != null) {
1717 String ipAddr = NWUtil.toStringIpAddress(ipAddrBytes);
1718 return Optional.of(IpAddressBuilder.getDefaultInstance(ipAddr));
1720 return srcIpAddress;
1723 public List<MacEntry> getElanMacEntries(String elanName) {
1724 MacTable macTable = getElanMacTable(elanName);
1725 if (macTable == null) {
1726 return Collections.emptyList();
1728 return macTable.getMacEntry();
1731 public boolean isTunnelInLogicalGroup(String interfaceName, DataBroker broker) {
1732 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1733 .ietf.interfaces.rev140508.interfaces.Interface configIface =
1734 interfaceManager.getInterfaceInfoFromConfigDataStore(interfaceName);
1735 IfTunnel ifTunnel = configIface.getAugmentation(IfTunnel.class);
1736 if (ifTunnel != null && ifTunnel.getTunnelInterfaceType().isAssignableFrom(TunnelTypeVxlan.class)) {
1737 ParentRefs refs = configIface.getAugmentation(ParentRefs.class);
1738 if (refs != null && !Strings.isNullOrEmpty(refs.getParentInterface())) {
1739 return true; //multiple VxLAN tunnels enabled, i.e. only logical tunnel should be treated
1745 public static void addElanInterfaceToElanInstanceCache(String elanInstanceName, String elanInterfaceName) {
1746 elanInstanceToInterfacesCache.computeIfAbsent(elanInstanceName, key -> new HashSet<>()).add(elanInterfaceName);
1749 public static void removeElanInterfaceToElanInstanceCache(String elanInstanceName, String interfaceName) {
1750 Set<String> elanInterfaces = elanInstanceToInterfacesCache.get(elanInstanceName);
1751 if (elanInterfaces == null || elanInterfaces.isEmpty()) {
1754 elanInterfaces.remove(interfaceName);
1757 @Nonnull public static Set<String> removeAndGetElanInterfaces(String elanInstanceName) {
1758 Set<String> removed = elanInstanceToInterfacesCache.remove(elanInstanceName);
1759 return removed != null ? removed : Collections.emptySet();
1762 public static InstanceIdentifier<Flow> getFlowIid(Flow flow, BigInteger dpnId) {
1763 FlowKey flowKey = new FlowKey(new FlowId(flow.getId()));
1764 org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId nodeId =
1765 new org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId("openflow:" + dpnId);
1766 org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node nodeDpn =
1767 new NodeBuilder().setId(nodeId).setKey(new NodeKey(nodeId)).build();
1768 return InstanceIdentifier.builder(Nodes.class)
1769 .child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node.class,
1770 nodeDpn.getKey()).augmentation(FlowCapableNode.class)
1771 .child(Table.class, new TableKey(flow.getTableId())).child(Flow.class, flowKey).build();
1774 public static String getElanInterfaceJobKey(String interfaceName) {
1775 return "elaninterface-" + interfaceName;
1778 public void addArpResponderFlow(BigInteger dpnId, String ingressInterfaceName, String ipAddress, String macAddress,
1779 int lportTag, List<Instruction> instructions) {
1780 LOG.info("Installing the ARP responder flow on DPN {} for Interface {} with MAC {} & IP {}", dpnId,
1781 ingressInterfaceName, macAddress, ipAddress);
1782 ElanInterface elanIface = getElanInterfaceByElanInterfaceName(broker, ingressInterfaceName);
1783 ElanInstance elanInstance = getElanInstanceByName(broker, elanIface.getElanInstanceName());
1784 if (elanInstance == null) {
1785 LOG.debug("addArpResponderFlow: elanInstance is null, Failed to install arp responder flow for Interface {}"
1786 + " with MAC {} & IP {}", dpnId,
1787 ingressInterfaceName, macAddress, ipAddress);
1790 String flowId = ArpResponderUtil.getFlowId(lportTag, ipAddress);
1791 ArpResponderUtil.installFlow(mdsalManager, dpnId, flowId, flowId, NwConstants.DEFAULT_ARP_FLOW_PRIORITY,
1792 ArpResponderUtil.generateCookie(lportTag, ipAddress),
1793 ArpResponderUtil.getMatchCriteria(lportTag, elanInstance, ipAddress), instructions);
1794 LOG.info("Installed the ARP Responder flow for Interface {}", ingressInterfaceName);
1797 public void removeArpResponderFlow(BigInteger dpnId, String ingressInterfaceName, String ipAddress,
1799 LOG.info("Removing the ARP responder flow on DPN {} of Interface {} with IP {}", dpnId, ingressInterfaceName,
1801 ArpResponderUtil.removeFlow(mdsalManager, dpnId, ArpResponderUtil.getFlowId(lportTag, ipAddress));