2 * Copyright © 2016, 2017 Ericsson India Global Services Pvt Ltd. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.netvirt.elan.utils;
10 import com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Strings;
13 import com.google.common.collect.Lists;
14 import com.google.common.primitives.Ints;
15 import com.google.common.util.concurrent.CheckedFuture;
16 import com.google.common.util.concurrent.FutureCallback;
17 import com.google.common.util.concurrent.Futures;
18 import com.google.common.util.concurrent.ListenableFuture;
19 import com.google.common.util.concurrent.MoreExecutors;
20 import java.math.BigInteger;
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.Collections;
24 import java.util.List;
25 import java.util.concurrent.ExecutionException;
26 import java.util.concurrent.Future;
27 import javax.annotation.CheckReturnValue;
28 import javax.annotation.Nonnull;
29 import javax.annotation.Nullable;
30 import javax.inject.Inject;
31 import javax.inject.Singleton;
32 import org.apache.commons.lang3.StringUtils;
33 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
34 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
35 import org.opendaylight.controller.md.sal.binding.api.ReadTransaction;
36 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
37 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
38 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
39 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
40 import org.opendaylight.genius.infra.ManagedNewTransactionRunner;
41 import org.opendaylight.genius.infra.ManagedNewTransactionRunnerImpl;
42 import org.opendaylight.genius.interfacemanager.globals.InterfaceInfo;
43 import org.opendaylight.genius.interfacemanager.globals.InterfaceServiceUtil;
44 import org.opendaylight.genius.interfacemanager.interfaces.IInterfaceManager;
45 import org.opendaylight.genius.itm.api.IITMProvider;
46 import org.opendaylight.genius.itm.globals.ITMConstants;
47 import org.opendaylight.genius.mdsalutil.ActionInfo;
48 import org.opendaylight.genius.mdsalutil.FlowEntity;
49 import org.opendaylight.genius.mdsalutil.FlowEntityBuilder;
50 import org.opendaylight.genius.mdsalutil.InstructionInfo;
51 import org.opendaylight.genius.mdsalutil.MDSALUtil;
52 import org.opendaylight.genius.mdsalutil.MatchInfo;
53 import org.opendaylight.genius.mdsalutil.MetaDataUtil;
54 import org.opendaylight.genius.mdsalutil.NWUtil;
55 import org.opendaylight.genius.mdsalutil.NwConstants;
56 import org.opendaylight.genius.mdsalutil.actions.ActionNxResubmit;
57 import org.opendaylight.genius.mdsalutil.instructions.InstructionApplyActions;
58 import org.opendaylight.genius.mdsalutil.instructions.InstructionGotoTable;
59 import org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager;
60 import org.opendaylight.genius.mdsalutil.matches.MatchEthernetDestination;
61 import org.opendaylight.genius.mdsalutil.matches.MatchEthernetSource;
62 import org.opendaylight.genius.mdsalutil.matches.MatchMetadata;
63 import org.opendaylight.genius.mdsalutil.matches.MatchTunnelId;
64 import org.opendaylight.genius.mdsalutil.packet.ARP;
65 import org.opendaylight.genius.mdsalutil.packet.Ethernet;
66 import org.opendaylight.genius.mdsalutil.packet.IPv4;
67 import org.opendaylight.infrautils.utils.concurrent.JdkFutures;
68 import org.opendaylight.infrautils.utils.concurrent.ListenableFutures;
69 import org.opendaylight.netvirt.elan.ElanException;
70 import org.opendaylight.netvirt.elan.arp.responder.ArpResponderUtil;
71 import org.opendaylight.netvirt.elan.cache.ElanInterfaceCache;
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.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsOutput;
123 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
124 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
125 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
126 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
127 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
128 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.config.rev150710.ElanConfig;
129 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInstance;
130 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInstanceBuilder;
131 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInterface;
132 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInterface.EtreeInterfaceType;
133 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTag;
134 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTagName;
135 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTagNameBuilder;
136 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanDpnInterfaces;
137 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanForwardingTables;
138 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInstances;
139 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaceForwardingEntries;
140 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaces;
141 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanState;
142 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanTagNameMap;
143 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeFlat;
144 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeVlan;
145 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeVxlan;
146 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan._interface.forwarding.entries.ElanInterfaceMac;
147 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan._interface.forwarding.entries.ElanInterfaceMacKey;
148 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesList;
149 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesListKey;
150 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfaces;
151 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfacesKey;
152 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTable;
153 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTableBuilder;
154 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTableKey;
155 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstance;
156 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstanceBuilder;
157 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.elan.instance.ElanSegments;
158 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterface;
159 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterfaceKey;
160 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntries;
161 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntriesBuilder;
162 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntriesKey;
163 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.Elan;
164 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.ElanBuilder;
165 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.ElanKey;
166 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagName;
167 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagNameBuilder;
168 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagNameKey;
169 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntry;
170 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntryKey;
171 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.Subnetmaps;
172 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.subnetmaps.Subnetmap;
173 import org.opendaylight.yangtools.yang.binding.DataObject;
174 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
175 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.InstanceIdentifierBuilder;
176 import org.opendaylight.yangtools.yang.common.RpcResult;
177 import org.slf4j.Logger;
178 import org.slf4j.LoggerFactory;
181 public class ElanUtils {
183 private static final Logger LOG = LoggerFactory.getLogger(ElanUtils.class);
185 private final DataBroker broker;
186 private final ManagedNewTransactionRunner txRunner;
187 private final IMdsalApiManager mdsalManager;
188 private final OdlInterfaceRpcService interfaceManagerRpcService;
189 private final ItmRpcService itmRpcService;
190 private final IInterfaceManager interfaceManager;
191 private final ElanConfig elanConfig;
192 private final ElanItmUtils elanItmUtils;
193 private final ElanEtreeUtils elanEtreeUtils;
194 private final ElanInterfaceCache elanInterfaceCache;
195 private final IITMProvider iitmProvider;
197 public static final FutureCallback<Void> DEFAULT_CALLBACK = new FutureCallback<Void>() {
199 public void onSuccess(Void result) {
200 LOG.debug("Success in Datastore operation");
204 public void onFailure(Throwable error) {
205 LOG.error("Error in Datastore operation", error);
210 public ElanUtils(DataBroker dataBroker, IMdsalApiManager mdsalManager,
211 OdlInterfaceRpcService interfaceManagerRpcService, ItmRpcService itmRpcService, ElanConfig elanConfig,
212 IInterfaceManager interfaceManager, ElanEtreeUtils elanEtreeUtils, ElanItmUtils elanItmUtils,
213 ElanInterfaceCache elanInterfaceCache, IITMProvider iitmProvider) {
214 this.broker = dataBroker;
215 this.txRunner = new ManagedNewTransactionRunnerImpl(dataBroker);
216 this.mdsalManager = mdsalManager;
217 this.interfaceManagerRpcService = interfaceManagerRpcService;
218 this.itmRpcService = itmRpcService;
219 this.interfaceManager = interfaceManager;
220 this.elanConfig = elanConfig;
221 this.elanEtreeUtils = elanEtreeUtils;
222 this.elanItmUtils = elanItmUtils;
223 this.elanInterfaceCache = elanInterfaceCache;
224 this.iitmProvider = iitmProvider;
227 public final Boolean isOpenstackVniSemanticsEnforced() {
228 return elanConfig.isOpenstackVniSemanticsEnforced() != null
229 ? elanConfig.isOpenstackVniSemanticsEnforced() : false;
233 * Uses the IdManager to retrieve a brand new ElanTag.
239 * @return the integer
241 public static Long retrieveNewElanTag(IdManagerService idManager, String idKey) {
243 AllocateIdInput getIdInput = new AllocateIdInputBuilder().setPoolName(ElanConstants.ELAN_ID_POOL_NAME)
244 .setIdKey(idKey).build();
247 Future<RpcResult<AllocateIdOutput>> result = idManager.allocateId(getIdInput);
248 RpcResult<AllocateIdOutput> rpcResult = result.get();
249 if (rpcResult.isSuccessful()) {
250 return rpcResult.getResult().getIdValue();
252 LOG.warn("RPC Call to Allocate Id returned with Errors {}", rpcResult.getErrors());
254 } catch (InterruptedException | ExecutionException e) {
255 LOG.warn("Exception when Allocating Id", e);
260 public static void releaseId(IdManagerService idManager, String poolName, String idKey) {
261 ReleaseIdInput releaseIdInput = new ReleaseIdInputBuilder().setPoolName(poolName).setIdKey(idKey).build();
262 JdkFutures.addErrorLogging(idManager.releaseId(releaseIdInput), LOG, "Release Id");
268 * @deprecated Consider using {@link #read2(LogicalDatastoreType, InstanceIdentifier)} with proper exception
270 * @param broker dataBroker
271 * @param datastoreType Logical DataStore type
272 * @param path IID to read
273 * @param <T> T extends DataObject
274 * @return the read value T
277 @SuppressWarnings("checkstyle:IllegalCatch")
278 public static <T extends DataObject> Optional<T> read(@Nonnull DataBroker broker,
279 LogicalDatastoreType datastoreType, InstanceIdentifier<T> path) {
280 try (ReadOnlyTransaction tx = broker.newReadOnlyTransaction()) {
281 return tx.read(datastoreType, path).get();
282 } catch (Exception e) {
283 throw new RuntimeException(e);
287 public <T extends DataObject> Optional<T> read2(LogicalDatastoreType datastoreType, InstanceIdentifier<T> path)
288 throws ReadFailedException {
289 try (ReadOnlyTransaction tx = broker.newReadOnlyTransaction()) {
290 CheckedFuture<Optional<T>, ReadFailedException> checkedFuture = tx.read(datastoreType, path);
291 return checkedFuture.checkedGet();
295 @SuppressWarnings("checkstyle:ForbiddenMethod")
296 public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
297 InstanceIdentifier<T> path) {
298 WriteTransaction tx = broker.newWriteOnlyTransaction();
299 tx.delete(datastoreType, path);
300 Futures.addCallback(tx.submit(), DEFAULT_CALLBACK, MoreExecutors.directExecutor());
303 @SuppressWarnings("checkstyle:ForbiddenMethod")
304 public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
305 InstanceIdentifier<T> path, FutureCallback<Void> callback) {
306 WriteTransaction tx = broker.newWriteOnlyTransaction();
307 tx.delete(datastoreType, path);
308 Futures.addCallback(tx.submit(), callback, MoreExecutors.directExecutor());
311 public static InstanceIdentifier<ElanInstance> getElanInstanceIdentifier() {
312 return InstanceIdentifier.builder(ElanInstances.class).child(ElanInstance.class).build();
315 public static InstanceIdentifier<ElanInterface> getElanInterfaceConfigurationDataPathId(String interfaceName) {
316 return InstanceIdentifier.builder(ElanInterfaces.class)
317 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).build();
320 // elan-state Operational container
321 public static Elan getElanByName(DataBroker broker, String elanInstanceName) {
322 InstanceIdentifier<Elan> elanIdentifier = getElanInstanceOperationalDataPath(elanInstanceName);
323 return MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL, elanIdentifier).orNull();
327 public static Elan getElanByName(ReadTransaction tx, String elanInstanceName) throws ReadFailedException {
328 return tx.read(LogicalDatastoreType.OPERATIONAL,
329 getElanInstanceOperationalDataPath(elanInstanceName)).checkedGet().orNull();
332 public static InstanceIdentifier<Elan> getElanInstanceOperationalDataPath(String elanInstanceName) {
333 return InstanceIdentifier.builder(ElanState.class).child(Elan.class, new ElanKey(elanInstanceName)).build();
336 // grouping of forwarding-entries
337 public MacEntry getInterfaceMacEntriesOperationalDataPath(String interfaceName, PhysAddress physAddress) {
338 InstanceIdentifier<MacEntry> existingMacEntryId = getInterfaceMacEntriesIdentifierOperationalDataPath(
339 interfaceName, physAddress);
340 return read(broker, LogicalDatastoreType.OPERATIONAL, existingMacEntryId).orNull();
343 public MacEntry getInterfaceMacEntriesOperationalDataPathFromId(InstanceIdentifier identifier) {
344 Optional<MacEntry> existingInterfaceMacEntry = read(broker,
345 LogicalDatastoreType.OPERATIONAL, identifier);
346 return existingInterfaceMacEntry.orNull();
349 public static InstanceIdentifier<MacEntry> getInterfaceMacEntriesIdentifierOperationalDataPath(String interfaceName,
350 PhysAddress physAddress) {
351 return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class)
352 .child(ElanInterfaceMac.class, new ElanInterfaceMacKey(interfaceName))
353 .child(MacEntry.class, new MacEntryKey(physAddress)).build();
357 // elan-forwarding-tables Operational container
358 public Optional<MacEntry> getMacEntryForElanInstance(String elanName, PhysAddress physAddress) {
359 InstanceIdentifier<MacEntry> macId = getMacEntryOperationalDataPath(elanName, physAddress);
360 return read(broker, LogicalDatastoreType.OPERATIONAL, macId);
363 public Optional<MacEntry> getMacEntryForElanInstance(ReadTransaction tx, String elanName, PhysAddress physAddress)
364 throws ReadFailedException {
365 InstanceIdentifier<MacEntry> macId = getMacEntryOperationalDataPath(elanName, physAddress);
366 return tx.read(LogicalDatastoreType.OPERATIONAL, macId).checkedGet();
369 public MacEntry getMacEntryFromElanMacId(InstanceIdentifier identifier) {
370 Optional<MacEntry> existingInterfaceMacEntry = read(broker,
371 LogicalDatastoreType.OPERATIONAL, identifier);
372 return existingInterfaceMacEntry.orNull();
375 public static InstanceIdentifier<MacEntry> getMacEntryOperationalDataPath(String elanName,
376 PhysAddress physAddress) {
377 return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class, new MacTableKey(elanName))
378 .child(MacEntry.class, new MacEntryKey(physAddress)).build();
381 public static InstanceIdentifier<MacTable> getElanMacTableOperationalDataPath(String elanName) {
382 return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class, new MacTableKey(elanName))
386 // elan-interface-forwarding-entries Operational container
387 public ElanInterfaceMac getElanInterfaceMacByInterfaceName(String interfaceName) {
388 return getElanInterfaceMacByInterfaceName(broker, interfaceName);
392 public static ElanInterfaceMac getElanInterfaceMacByInterfaceName(DataBroker dataBroker, String interfaceName) {
393 InstanceIdentifier<ElanInterfaceMac> elanInterfaceId = getElanInterfaceMacEntriesOperationalDataPath(
395 return read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanInterfaceId).orNull();
399 * Gets the elan interface mac addresses.
401 * @param interfaceName
403 * @return the elan interface mac addresses
405 public List<PhysAddress> getElanInterfaceMacAddresses(String interfaceName) {
406 List<PhysAddress> macAddresses = new ArrayList<>();
407 ElanInterfaceMac elanInterfaceMac = getElanInterfaceMacByInterfaceName(interfaceName);
408 if (elanInterfaceMac != null && elanInterfaceMac.getMacEntry() != null) {
409 List<MacEntry> macEntries = elanInterfaceMac.getMacEntry();
410 for (MacEntry macEntry : macEntries) {
411 macAddresses.add(macEntry.getMacAddress());
417 public static InstanceIdentifier<ElanInterfaceMac> getElanInterfaceMacEntriesOperationalDataPath(
418 String interfaceName) {
419 return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class)
420 .child(ElanInterfaceMac.class, new ElanInterfaceMacKey(interfaceName)).build();
424 * Returns the list of Interfaces that belong to an Elan on an specific DPN.
425 * Data retrieved from Elan's operational DS: elan-dpn-interfaces container
427 * @param elanInstanceName
428 * name of the Elan to which the interfaces must belong to
430 * Id of the DPN where the interfaces are located
431 * @return the elan interface Info
433 public DpnInterfaces getElanInterfaceInfoByElanDpn(String elanInstanceName, BigInteger dpId) {
434 InstanceIdentifier<DpnInterfaces> elanDpnInterfacesId = getElanDpnInterfaceOperationalDataPath(elanInstanceName,
436 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfacesId).orNull();
440 * Returns the InstanceIdentifier that points to the Interfaces of an Elan
441 * in a given DPN in the Operational DS. Data retrieved from Elans's
442 * operational DS: dpn-interfaces list
444 * @param elanInstanceName
445 * name of the Elan to which the interfaces must belong to
447 * Id of the DPN where the interfaces are located
448 * @return the elan dpn interface
450 public static InstanceIdentifier<DpnInterfaces> getElanDpnInterfaceOperationalDataPath(String elanInstanceName,
452 return InstanceIdentifier.builder(ElanDpnInterfaces.class)
453 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName))
454 .child(DpnInterfaces.class, new DpnInterfacesKey(dpId)).build();
457 // elan-tag-name-map Operational Container
458 public ElanTagName getElanInfoByElanTag(long elanTag) {
459 InstanceIdentifier<ElanTagName> elanId = getElanInfoEntriesOperationalDataPath(elanTag);
460 Optional<ElanTagName> existingElanInfo = read(broker,
461 LogicalDatastoreType.OPERATIONAL, elanId);
462 return existingElanInfo.orNull();
465 public static InstanceIdentifier<ElanTagName> getElanInfoEntriesOperationalDataPath(long elanTag) {
466 return InstanceIdentifier.builder(ElanTagNameMap.class).child(ElanTagName.class, new ElanTagNameKey(elanTag))
470 // interface-index-tag operational container
471 public Optional<IfIndexInterface> getInterfaceInfoByInterfaceTag(long interfaceTag) {
472 InstanceIdentifier<IfIndexInterface> interfaceId = getInterfaceInfoEntriesOperationalDataPath(interfaceTag);
473 return read(broker, LogicalDatastoreType.OPERATIONAL, interfaceId);
476 public static InstanceIdentifier<IfIndexInterface> getInterfaceInfoEntriesOperationalDataPath(long interfaceTag) {
477 return InstanceIdentifier.builder(IfIndexesInterfaceMap.class)
478 .child(IfIndexInterface.class, new IfIndexInterfaceKey((int) interfaceTag)).build();
481 public static InstanceIdentifier<ElanDpnInterfacesList> getElanDpnOperationDataPath(String elanInstanceName) {
482 return InstanceIdentifier.builder(ElanDpnInterfaces.class)
483 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName)).build();
486 public ElanDpnInterfacesList getElanDpnInterfacesList(String elanName) {
487 InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanName);
488 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orNull();
491 public ElanDpnInterfaces getElanDpnInterfacesList() {
492 InstanceIdentifier<ElanDpnInterfaces> elanDpnInterfaceId = InstanceIdentifier.builder(ElanDpnInterfaces.class)
494 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orNull();
498 * This method is useful get all ELAN participating CSS dpIds to install
499 * program remote dmac entries and updating remote bc groups for tor
502 * @param elanInstanceName
503 * the elan instance name
504 * @return list of dpIds
507 public List<BigInteger> getParticipatingDpnsInElanInstance(String elanInstanceName) {
508 List<BigInteger> dpIds = new ArrayList<>();
509 InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
510 Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = read(broker,
511 LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
512 if (!existingElanDpnInterfaces.isPresent()) {
515 List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().getDpnInterfaces();
516 for (DpnInterfaces dpnInterface : dpnInterfaces) {
517 dpIds.add(dpnInterface.getDpId());
523 * To check given dpId is already present in Elan instance. This can be used
524 * to program flow entry in external tunnel table when a new access port
525 * added for first time into the ELAN instance
529 * @param elanInstanceName
530 * the elan instance name
531 * @return true if dpId is already present, otherwise return false
533 public boolean isDpnAlreadyPresentInElanInstance(BigInteger dpId, String elanInstanceName) {
534 InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
535 Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = read(broker,
536 LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
537 if (!existingElanDpnInterfaces.isPresent()) {
540 List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().getDpnInterfaces();
541 for (DpnInterfaces dpnInterface : dpnInterfaces) {
542 if (dpnInterface.getDpId().equals(dpId)) {
549 public ElanForwardingTables getElanForwardingList() {
550 InstanceIdentifier<ElanForwardingTables> elanForwardingTableId = InstanceIdentifier
551 .builder(ElanForwardingTables.class).build();
552 return read(broker, LogicalDatastoreType.OPERATIONAL, elanForwardingTableId).orNull();
555 public static long getElanRemoteBroadCastGroupID(long elanTag) {
556 return ElanConstants.ELAN_GID_MIN + elanTag % ElanConstants.ELAN_GID_MIN * 2;
560 * Gets the elan mac table.
564 * @return the elan mac table
566 public MacTable getElanMacTable(String elanName) {
567 return getElanMacTable(broker, elanName);
571 public static MacTable getElanMacTable(DataBroker dataBroker, String elanName) {
572 InstanceIdentifier<MacTable> elanMacTableId = getElanMacTableOperationalDataPath(elanName);
573 return read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanMacTableId).orNull();
576 public static long getElanLocalBCGId(long elanTag) {
577 return ElanConstants.ELAN_GID_MIN + (elanTag % ElanConstants.ELAN_GID_MIN * 2 - 1);
580 public static long getElanRemoteBCGId(long elanTag) {
581 return ElanConstants.ELAN_GID_MIN + elanTag % ElanConstants.ELAN_GID_MIN * 2;
584 public static long getEtreeLeafLocalBCGId(long etreeLeafTag) {
585 return ElanConstants.ELAN_GID_MIN + (etreeLeafTag % ElanConstants.ELAN_GID_MIN * 2 - 1);
588 public static long getEtreeLeafRemoteBCGId(long etreeLeafTag) {
589 return ElanConstants.ELAN_GID_MIN + etreeLeafTag % ElanConstants.ELAN_GID_MIN * 2;
592 public static BigInteger getElanMetadataLabel(long elanTag, boolean isSHFlagSet) {
593 int shBit = isSHFlagSet ? 1 : 0;
594 return BigInteger.valueOf(elanTag).shiftLeft(24).or(BigInteger.valueOf(shBit));
598 * Setting SMAC, DMAC, UDMAC in this DPN and optionally in other DPNs.
602 * @param interfaceInfo
608 * @param configureRemoteFlows
609 * true if remote dmac flows should be configured as well
610 * @param writeFlowGroupTx
612 * @throws ElanException in case of issues creating the flow objects
614 public void setupMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo,
615 long macTimeout, String macAddress, boolean configureRemoteFlows,
616 WriteTransaction writeFlowGroupTx) throws ElanException {
617 synchronized (getElanMacDPNKey(elanInfo.getElanTag(), macAddress, interfaceInfo.getDpId())) {
618 setupKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress, mdsalManager,
620 setupOrigDmacFlows(elanInfo, interfaceInfo, macAddress, configureRemoteFlows, mdsalManager,
625 public void setupDMacFlowOnRemoteDpn(ElanInstance elanInfo, InterfaceInfo interfaceInfo, BigInteger dstDpId,
626 String macAddress, WriteTransaction writeFlowTx) throws ElanException {
627 String elanInstanceName = elanInfo.getElanInstanceName();
628 setupRemoteDmacFlow(dstDpId, interfaceInfo.getDpId(), interfaceInfo.getInterfaceTag(), elanInfo.getElanTag(),
629 macAddress, elanInstanceName, writeFlowTx, interfaceInfo.getInterfaceName(), elanInfo);
630 LOG.info("Remote Dmac flow entry created for elan Name:{}, logical port Name:{} and"
631 + " mac address {} on dpn:{}", elanInstanceName, interfaceInfo.getPortName(),
632 macAddress, dstDpId);
636 * Inserts a Flow in SMAC table to state that the MAC has already been
639 private void setupKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
640 String macAddress, IMdsalApiManager mdsalApiManager, WriteTransaction writeFlowGroupTx) {
641 FlowEntity flowEntity = buildKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress);
642 mdsalApiManager.addFlowToTx(flowEntity, writeFlowGroupTx);
643 LOG.debug("Known Smac flow entry created for elan Name:{}, logical Interface port:{} and mac address:{}",
644 elanInfo.getElanInstanceName(), elanInfo.getDescription(), macAddress);
647 public FlowEntity buildKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
649 int lportTag = interfaceInfo.getInterfaceTag();
650 // Matching metadata and eth_src fields
651 List<MatchInfo> mkMatches = new ArrayList<>();
652 mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanInfo.getElanTag(), lportTag),
653 ElanHelper.getElanMetadataMask()));
654 mkMatches.add(new MatchEthernetSource(new MacAddress(macAddress)));
655 List<InstructionInfo> mkInstructions = new ArrayList<>();
656 mkInstructions.add(new InstructionGotoTable(NwConstants.ELAN_DMAC_TABLE));
657 BigInteger dpId = interfaceInfo.getDpId();
658 long elanTag = getElanTag(elanInfo, interfaceInfo);
659 return new FlowEntityBuilder()
661 .setTableId(NwConstants.ELAN_SMAC_TABLE)
662 .setFlowId(getKnownDynamicmacFlowRef(NwConstants.ELAN_SMAC_TABLE, dpId, lportTag, macAddress, elanTag))
664 .setFlowName(elanInfo.getDescription())
665 .setIdleTimeOut((int) macTimeout)
667 .setCookie(ElanConstants.COOKIE_ELAN_KNOWN_SMAC.add(BigInteger.valueOf(elanTag)))
668 .setMatchInfoList(mkMatches)
669 .setInstructionInfoList(mkInstructions)
671 // If Mac timeout is 0, the flow won't be deleted automatically, so no need to get notified
672 .setSendFlowRemFlag(macTimeout != 0)
676 private Long getElanTag(ElanInstance elanInfo, InterfaceInfo interfaceInfo) {
677 EtreeInterface etreeInterface = elanInterfaceCache.getEtreeInterface(interfaceInfo.getInterfaceName()).orNull();
678 if (etreeInterface == null || etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
679 return elanInfo.getElanTag();
681 EtreeInstance etreeInstance = elanInfo.augmentation(EtreeInstance.class);
682 if (etreeInstance == null) {
683 LOG.warn("EtreeInterface {} is connected to a non-Etree network: {}",
684 interfaceInfo.getInterfaceName(), elanInfo.getElanInstanceName());
685 return elanInfo.getElanTag();
687 return etreeInstance.getEtreeLeafTagVal().getValue();
693 * Installs a Flow in INTERNAL_TUNNEL_TABLE of the affected DPN that sends
694 * the packet through the specified interface if the tunnel_id matches the
695 * interface's lportTag.
697 * @param interfaceInfo
699 * @param mdsalApiManager
700 * the mdsal API manager
701 * @param writeFlowGroupTx
702 * the writeFLowGroup tx
704 public void setupTermDmacFlows(InterfaceInfo interfaceInfo, IMdsalApiManager mdsalApiManager,
705 WriteTransaction writeFlowGroupTx) {
706 BigInteger dpId = interfaceInfo.getDpId();
707 int lportTag = interfaceInfo.getInterfaceTag();
708 Flow flow = MDSALUtil.buildFlowNew(NwConstants.INTERNAL_TUNNEL_TABLE,
709 getIntTunnelTableFlowRef(NwConstants.INTERNAL_TUNNEL_TABLE, lportTag), 5,
710 String.format("%s:%d", "ITM Flow Entry ", lportTag), 0, 0,
711 ITMConstants.COOKIE_ITM.add(BigInteger.valueOf(lportTag)),
712 getTunnelIdMatchForFilterEqualsLPortTag(lportTag),
713 getInstructionsInPortForOutGroup(interfaceInfo.getInterfaceName()));
714 mdsalApiManager.addFlowToTx(dpId, flow, writeFlowGroupTx);
715 LOG.debug("Terminating service table flow entry created on dpn:{} for logical Interface port:{}", dpId,
716 interfaceInfo.getPortName());
720 * Constructs the FlowName for flows installed in the Internal Tunnel Table,
721 * consisting in tableId + elanTag.
727 * @return the Internal tunnel
729 public static String getIntTunnelTableFlowRef(short tableId, int elanTag) {
730 return new StringBuffer().append(tableId).append(elanTag).toString();
734 * Constructs the Matches that checks that the tunnel_id field contains a
738 * lportTag that must be checked against the tunnel_id field
739 * @return the list of match Info
741 public static List<MatchInfo> getTunnelIdMatchForFilterEqualsLPortTag(int lportTag) {
742 List<MatchInfo> mkMatches = new ArrayList<>();
744 mkMatches.add(new MatchTunnelId(BigInteger.valueOf(lportTag)));
749 * Constructs the Instructions that take the packet over a given interface.
752 * Name of the interface where the packet must be sent over. It
753 * can be a local interface or a tunnel interface (internal or
755 * @return the Instruction
757 public List<Instruction> getInstructionsInPortForOutGroup(String ifName) {
758 List<Instruction> mkInstructions = new ArrayList<>();
759 List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
761 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
762 return mkInstructions;
766 * Returns the list of Actions to be taken when sending the packet through
767 * an Elan interface. Note that this interface can refer to an ElanInterface
768 * where the Elan VM is attached to a DPN or an ITM tunnel interface where
769 * Elan traffic can be sent through. In this latter case, the tunnelKey is
770 * mandatory and it can hold serviceId for internal tunnels or the VNI for
777 * @return the egress actions for interface
779 @SuppressWarnings("checkstyle:IllegalCatch")
780 public List<Action> getEgressActionsForInterface(String ifName, Long tunnelKey) {
781 List<Action> listAction = new ArrayList<>();
783 GetEgressActionsForInterfaceInput getEgressActionInput = new GetEgressActionsForInterfaceInputBuilder()
784 .setIntfName(ifName).setTunnelKey(tunnelKey).build();
785 Future<RpcResult<GetEgressActionsForInterfaceOutput>> result = interfaceManagerRpcService
786 .getEgressActionsForInterface(getEgressActionInput);
787 RpcResult<GetEgressActionsForInterfaceOutput> rpcResult = result.get();
788 if (!rpcResult.isSuccessful()) {
789 LOG.debug("RPC Call to Get egress actions for interface {} returned with Errors {}", ifName,
790 rpcResult.getErrors());
792 List<Action> actions = rpcResult.getResult().getAction();
793 listAction = actions;
795 } catch (Exception e) {
796 LOG.warn("Exception when egress actions for interface {}", ifName, e);
801 private void setupOrigDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
802 boolean configureRemoteFlows, IMdsalApiManager mdsalApiManager,
803 WriteTransaction writeFlowGroupTx)
804 throws ElanException {
805 BigInteger dpId = interfaceInfo.getDpId();
806 String ifName = interfaceInfo.getInterfaceName();
807 long ifTag = interfaceInfo.getInterfaceTag();
808 String elanInstanceName = elanInfo.getElanInstanceName();
810 Long elanTag = elanInfo.getElanTag();
812 setupLocalDmacFlow(elanTag, dpId, ifName, macAddress, elanInfo, mdsalApiManager, ifTag,
814 LOG.debug("Dmac flow entry created for elan Name:{}, logical port Name:{} mand mac address:{} "
815 + "on dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, dpId);
817 if (!configureRemoteFlows) {
821 List<DpnInterfaces> elanDpns = getInvolvedDpnsInElan(elanInstanceName);
822 for (DpnInterfaces elanDpn : elanDpns) {
824 if (elanDpn.getDpId().equals(dpId)) {
828 // Check for the Remote DPN present in Inventory Manager
829 if (!isDpnPresent(elanDpn.getDpId())) {
833 // For remote DPNs a flow is needed to indicate that packets of this ELAN going to this MAC need to be
834 // forwarded through the appropriate ITM tunnel
835 setupRemoteDmacFlow(elanDpn.getDpId(), // srcDpn (the remote DPN in this case)
836 dpId, // dstDpn (the local DPN)
837 interfaceInfo.getInterfaceTag(), // lportTag of the local interface
838 elanTag, // identifier of the Elan
839 macAddress, // MAC to be programmed in remote DPN
840 elanInstanceName, writeFlowGroupTx, ifName, elanInfo
842 LOG.debug("Remote Dmac flow entry created for elan Name:{}, logical port Name:{} and mac address:{} on"
843 + " dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, elanDpn.getDpId());
846 // TODO: Make sure that the same is performed against the ElanDevices.
850 public List<DpnInterfaces> getInvolvedDpnsInElan(String elanName) {
851 return getElanDPNByName(elanName);
855 public List<DpnInterfaces> getElanDPNByName(String elanInstanceName) {
856 InstanceIdentifier<ElanDpnInterfacesList> elanIdentifier = getElanDpnOperationDataPath(elanInstanceName);
857 return MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL, elanIdentifier).toJavaUtil().map(
858 ElanDpnInterfacesList::getDpnInterfaces).orElse(Collections.emptyList());
861 private void setupLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
862 ElanInstance elanInfo, IMdsalApiManager mdsalApiManager, long ifTag, WriteTransaction writeFlowGroupTx) {
863 Flow flowEntity = buildLocalDmacFlowEntry(elanTag, dpId, ifName, macAddress, elanInfo, ifTag);
864 mdsalApiManager.addFlowToTx(dpId, flowEntity, writeFlowGroupTx);
865 installEtreeLocalDmacFlow(elanTag, dpId, ifName, macAddress, elanInfo,
866 ifTag, writeFlowGroupTx);
869 private void installEtreeLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
870 ElanInstance elanInfo, long ifTag, WriteTransaction writeFlowGroupTx) {
871 EtreeInterface etreeInterface = elanInterfaceCache.getEtreeInterface(ifName).orNull();
872 if (etreeInterface != null && etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
873 EtreeLeafTagName etreeTagName = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
874 if (etreeTagName == null) {
875 LOG.warn("Interface {} seems like it belongs to Etree but etreeTagName from elanTag {} is null",
878 Flow flowEntity = buildLocalDmacFlowEntry(etreeTagName.getEtreeLeafTag().getValue(), dpId, ifName,
879 macAddress, elanInfo, ifTag);
880 mdsalManager.addFlowToTx(dpId, flowEntity, writeFlowGroupTx);
885 public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, long lporTag, String macAddress,
887 return String.valueOf(tableId) + elanTag + dpId + lporTag + macAddress;
890 public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, BigInteger remoteDpId,
891 String macAddress, long elanTag) {
892 return String.valueOf(tableId) + elanTag + dpId + remoteDpId + macAddress;
895 public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, String macAddress, long elanTag) {
896 return String.valueOf(tableId) + elanTag + dpId + macAddress;
899 public static String getKnownDynamicmacFlowRef(short elanDmacTable, BigInteger dpId, String extDeviceNodeId,
900 String dstMacAddress, long elanTag, boolean shFlag) {
901 return String.valueOf(elanDmacTable) + elanTag + dpId + extDeviceNodeId + dstMacAddress + shFlag;
905 * Builds the flow to be programmed in the DMAC table of the local DPN (that
906 * is, where the MAC is attached to). This flow consists in:
908 * <p>Match: + elanTag in metadata + packet goes to a MAC locally attached
909 * Actions: + optionally, pop-vlan + set-vlan-id + output to ifName's
926 public Flow buildLocalDmacFlowEntry(long elanTag, BigInteger dpId, String ifName, String macAddress,
927 ElanInstance elanInfo, long ifTag) {
929 List<MatchInfo> mkMatches = new ArrayList<>();
930 mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
931 mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddress)));
933 List<Instruction> mkInstructions = new ArrayList<>();
934 List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
935 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
936 Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
937 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, ifTag, macAddress, elanTag), 20,
938 elanInfo.getElanInstanceName(), 0, 0, ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(
939 BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
944 public void setupRemoteDmacFlow(BigInteger srcDpId, BigInteger destDpId, int lportTag, long elanTag, String
945 macAddress, String displayName, WriteTransaction writeFlowGroupTx, String interfaceName, ElanInstance
946 elanInstance) throws ElanException {
947 if (interfaceManager.isExternalInterface(interfaceName)) {
948 LOG.debug("Ignoring install remote DMAC {} flow on provider interface {} elan {}",
949 macAddress, interfaceName, elanInstance.getElanInstanceName());
953 // if openstack-vni-semantics are enforced, segmentation ID is passed as network VNI for VxLAN based provider
954 // networks, 0 otherwise
955 long lportTagOrVni = !isOpenstackVniSemanticsEnforced() ? lportTag : isVxlanNetworkOrVxlanSegment(elanInstance)
956 ? getVxlanSegmentationId(elanInstance) : 0;
957 flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTagOrVni, elanTag, macAddress, displayName,
959 mdsalManager.addFlowToTx(srcDpId, flowEntity, writeFlowGroupTx);
960 setupEtreeRemoteDmacFlow(srcDpId, destDpId, lportTagOrVni, elanTag, macAddress, displayName, interfaceName,
961 writeFlowGroupTx, elanInstance);
964 private void setupEtreeRemoteDmacFlow(BigInteger srcDpId, BigInteger destDpId, long lportTagOrVni, long elanTag,
965 String macAddress, String displayName, String interfaceName,
966 WriteTransaction writeFlowGroupTx, ElanInstance elanInstance) {
968 EtreeInterface etreeInterface = elanInterfaceCache.getEtreeInterface(interfaceName).orNull();
969 if (etreeInterface != null && etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
970 EtreeLeafTagName etreeTagName = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
971 if (etreeTagName == null) {
972 LOG.warn("Interface {} seems like it belongs to Etree but etreeTagName from elanTag {} is null.",
973 interfaceName, elanTag);
975 flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTagOrVni,
976 etreeTagName.getEtreeLeafTag().getValue(), macAddress, displayName, elanInstance);
977 mdsalManager.addFlowToTx(srcDpId, flowEntity, writeFlowGroupTx);
983 * Builds a Flow to be programmed in a remote DPN's DMAC table. This flow
984 * consists in: Match: + elanTag in packet's metadata + packet going to a
985 * MAC known to be located in another DPN Actions: + set_tunnel_id
986 * + output ITM internal tunnel interface with the other DPN
992 * @param lportTagOrVni
993 * lportTag or network VNI
1000 * @param elanInstance
1002 * @return the flow remote Dmac
1004 @SuppressWarnings("checkstyle:IllegalCatch")
1005 public Flow buildRemoteDmacFlowEntry(BigInteger srcDpId, BigInteger destDpId, long lportTagOrVni, long elanTag,
1006 String macAddress, String displayName, ElanInstance elanInstance) {
1007 List<MatchInfo> mkMatches = new ArrayList<>();
1008 mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
1009 mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddress)));
1011 List<Instruction> mkInstructions = new ArrayList<>();
1013 // List of Action for the provided Source and Destination DPIDs
1015 List<Action> actions = null;
1016 if (isVxlanNetworkOrVxlanSegment(elanInstance)) {
1017 actions = elanItmUtils.getInternalTunnelItmEgressAction(srcDpId, destDpId, lportTagOrVni);
1018 } else if (isVlan(elanInstance) || isFlat(elanInstance)) {
1019 String interfaceName = getExternalElanInterface(elanInstance.getElanInstanceName(), srcDpId);
1020 if (null == interfaceName) {
1021 LOG.info("buildRemoteDmacFlowEntry: Could not find interfaceName for {} {}", srcDpId,
1024 actions = getEgressActionsForInterface(interfaceName, null);
1026 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
1027 } catch (Exception e) {
1028 LOG.error("Could not get egress actions to add to flow for srcDpId {}, destDpId {}, lportTag/VNI {}",
1029 srcDpId, destDpId, lportTagOrVni, e);
1032 Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
1033 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, srcDpId, destDpId, macAddress, elanTag),
1035 displayName, 0, /* idleTimeout */
1036 0, /* hardTimeout */
1037 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
1043 public void deleteMacFlows(@Nullable ElanInstance elanInfo, @Nullable InterfaceInfo interfaceInfo,
1044 MacEntry macEntry, WriteTransaction deleteFlowGroupTx) {
1045 if (elanInfo == null || interfaceInfo == null) {
1048 String macAddress = macEntry.getMacAddress().getValue();
1049 synchronized (getElanMacDPNKey(elanInfo.getElanTag(), macAddress, interfaceInfo.getDpId())) {
1050 deleteMacFlows(elanInfo, interfaceInfo, macAddress, /* alsoDeleteSMAC */ true, deleteFlowGroupTx);
1054 public void deleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1055 boolean deleteSmac, WriteTransaction deleteFlowGroupTx) {
1056 String elanInstanceName = elanInfo.getElanInstanceName();
1057 List<DpnInterfaces> remoteFEs = getInvolvedDpnsInElan(elanInstanceName);
1058 BigInteger srcdpId = interfaceInfo.getDpId();
1059 boolean isFlowsRemovedInSrcDpn = false;
1060 for (DpnInterfaces dpnInterface : remoteFEs) {
1061 Long elanTag = elanInfo.getElanTag();
1062 BigInteger dstDpId = dpnInterface.getDpId();
1063 if (executeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1064 elanTag, dstDpId, deleteFlowGroupTx)) {
1065 isFlowsRemovedInSrcDpn = true;
1067 executeEtreeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1068 elanTag, dstDpId, deleteFlowGroupTx);
1070 if (!isFlowsRemovedInSrcDpn) {
1071 deleteSmacAndDmacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, deleteFlowGroupTx);
1075 private void executeEtreeDeleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1076 boolean deleteSmac, String elanInstanceName, BigInteger srcdpId, Long elanTag, BigInteger dstDpId,
1077 WriteTransaction deleteFlowGroupTx) {
1078 EtreeLeafTagName etreeLeafTag = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
1079 if (etreeLeafTag != null) {
1080 executeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1081 etreeLeafTag.getEtreeLeafTag().getValue(), dstDpId, deleteFlowGroupTx);
1085 private boolean executeDeleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1086 boolean deleteSmac, String elanInstanceName, BigInteger srcdpId, Long elanTag, BigInteger dstDpId,
1087 WriteTransaction deleteFlowGroupTx) {
1088 boolean isFlowsRemovedInSrcDpn = false;
1089 if (dstDpId.equals(srcdpId)) {
1090 isFlowsRemovedInSrcDpn = true;
1091 deleteSmacAndDmacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, deleteFlowGroupTx);
1092 } else if (isDpnPresent(dstDpId)) {
1094 .removeFlowToTx(dstDpId,
1095 MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, getKnownDynamicmacFlowRef(
1096 NwConstants.ELAN_DMAC_TABLE, dstDpId, srcdpId, macAddress, elanTag)),
1098 LOG.debug("Dmac flow entry deleted for elan:{}, logical interface port:{} and mac address:{} on dpn:{}",
1099 elanInstanceName, interfaceInfo.getPortName(), macAddress, dstDpId);
1101 return isFlowsRemovedInSrcDpn;
1104 private void deleteSmacAndDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1105 boolean deleteSmac, WriteTransaction deleteFlowGroupTx) {
1106 String elanInstanceName = elanInfo.getElanInstanceName();
1107 long ifTag = interfaceInfo.getInterfaceTag();
1108 BigInteger srcdpId = interfaceInfo.getDpId();
1109 Long elanTag = elanInfo.getElanTag();
1112 .removeFlowToTx(srcdpId,
1113 MDSALUtil.buildFlow(NwConstants.ELAN_SMAC_TABLE, getKnownDynamicmacFlowRef(
1114 NwConstants.ELAN_SMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)),
1117 mdsalManager.removeFlowToTx(srcdpId,
1118 MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE,
1119 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)),
1121 LOG.debug("All the required flows deleted for elan:{}, logical Interface port:{} and MAC address:{} on dpn:{}",
1122 elanInstanceName, interfaceInfo.getPortName(), macAddress, srcdpId);
1126 * Updates the Elan information in the Operational DS. It also updates the
1127 * ElanInstance in the Config DS by setting the adquired elanTag.
1131 * @param elanInstanceAdded
1132 * the elan instance added
1133 * @param elanInterfaces
1134 * the elan interfaces
1138 * @return the updated ELAN instance.
1140 public static ElanInstance updateOperationalDataStore(IdManagerService idManager,
1141 ElanInstance elanInstanceAdded, List<String> elanInterfaces, WriteTransaction tx) {
1142 String elanInstanceName = elanInstanceAdded.getElanInstanceName();
1143 Long elanTag = elanInstanceAdded.getElanTag();
1144 if (elanTag == null || elanTag == 0L) {
1145 elanTag = retrieveNewElanTag(idManager, elanInstanceName);
1147 Elan elanInfo = new ElanBuilder().setName(elanInstanceName).setElanInterfaces(elanInterfaces)
1148 .withKey(new ElanKey(elanInstanceName)).build();
1150 // Add the ElanState in the elan-state operational data-store
1151 tx.put(LogicalDatastoreType.OPERATIONAL, getElanInstanceOperationalDataPath(elanInstanceName),
1152 elanInfo, WriteTransaction.CREATE_MISSING_PARENTS);
1154 // Add the ElanMacTable in the elan-mac-table operational data-store
1155 MacTable elanMacTable = new MacTableBuilder().withKey(new MacTableKey(elanInstanceName)).build();
1156 tx.put(LogicalDatastoreType.OPERATIONAL, getElanMacTableOperationalDataPath(elanInstanceName),
1157 elanMacTable, WriteTransaction.CREATE_MISSING_PARENTS);
1159 ElanTagNameBuilder elanTagNameBuilder = new ElanTagNameBuilder().setElanTag(elanTag)
1160 .withKey(new ElanTagNameKey(elanTag)).setName(elanInstanceName);
1161 long etreeLeafTag = -1;
1162 if (isEtreeInstance(elanInstanceAdded)) {
1163 etreeLeafTag = retrieveNewElanTag(idManager,elanInstanceName + ElanConstants
1165 EtreeLeafTagName etreeLeafTagName = new EtreeLeafTagNameBuilder()
1166 .setEtreeLeafTag(new EtreeLeafTag(etreeLeafTag)).build();
1167 elanTagNameBuilder.addAugmentation(EtreeLeafTagName.class, etreeLeafTagName);
1168 addTheLeafTagAsElanTag(elanInstanceName, etreeLeafTag, tx);
1170 ElanTagName elanTagName = elanTagNameBuilder.build();
1172 // Add the ElanTag to ElanName in the elan-tag-name Operational
1174 tx.put(LogicalDatastoreType.OPERATIONAL,
1175 getElanInfoEntriesOperationalDataPath(elanTag), elanTagName);
1177 // Updates the ElanInstance Config DS by setting the just acquired
1179 ElanInstanceBuilder elanInstanceBuilder = new ElanInstanceBuilder().setElanInstanceName(elanInstanceName)
1180 .setDescription(elanInstanceAdded.getDescription())
1181 .setMacTimeout(elanInstanceAdded.getMacTimeout() == null
1182 ? Long.valueOf(ElanConstants.DEFAULT_MAC_TIME_OUT) : elanInstanceAdded.getMacTimeout())
1183 .withKey(elanInstanceAdded.key()).setElanTag(elanTag);
1184 if (isEtreeInstance(elanInstanceAdded)) {
1185 EtreeInstance etreeInstance = new EtreeInstanceBuilder().setEtreeLeafTagVal(new EtreeLeafTag(etreeLeafTag))
1187 elanInstanceBuilder.addAugmentation(EtreeInstance.class, etreeInstance);
1189 ElanInstance elanInstanceWithTag = elanInstanceBuilder.build();
1190 tx.merge(LogicalDatastoreType.CONFIGURATION, ElanHelper.getElanInstanceConfigurationDataPath(elanInstanceName),
1191 elanInstanceWithTag, WriteTransaction.CREATE_MISSING_PARENTS);
1192 return elanInstanceWithTag;
1195 private static void addTheLeafTagAsElanTag(String elanInstanceName, long etreeLeafTag, WriteTransaction tx) {
1196 ElanTagName etreeTagAsElanTag = new ElanTagNameBuilder().setElanTag(etreeLeafTag)
1197 .withKey(new ElanTagNameKey(etreeLeafTag)).setName(elanInstanceName).build();
1198 tx.put(LogicalDatastoreType.OPERATIONAL,
1199 getElanInfoEntriesOperationalDataPath(etreeLeafTag), etreeTagAsElanTag);
1202 private static boolean isEtreeInstance(ElanInstance elanInstanceAdded) {
1203 return elanInstanceAdded.augmentation(EtreeInstance.class) != null;
1206 public boolean isDpnPresent(BigInteger dpnId) {
1207 String dpn = String.format("%s:%s", "openflow", dpnId);
1208 NodeId nodeId = new NodeId(dpn);
1210 InstanceIdentifier<Node> node = InstanceIdentifier.builder(Nodes.class).child(Node.class, new NodeKey(nodeId))
1212 return read(broker, LogicalDatastoreType.CONFIGURATION, node).isPresent();
1215 public static ServicesInfo getServiceInfo(String elanInstanceName, String interfaceName) {
1216 return InterfaceServiceUtil.buildServiceInfo(elanInstanceName + "." + interfaceName,
1217 ElanConstants.ELAN_SERVICE_PRIORITY);
1220 public static String getElanServiceName(String elanName, String interfaceName) {
1221 return "elan." + elanName + interfaceName;
1224 public static BoundServices getBoundServices(String serviceName, short servicePriority, int flowPriority,
1225 BigInteger cookie, List<Instruction> instructions) {
1226 StypeOpenflowBuilder augBuilder = new StypeOpenflowBuilder().setFlowCookie(cookie).setFlowPriority(flowPriority)
1227 .setInstruction(instructions);
1228 return new BoundServicesBuilder().withKey(new BoundServicesKey(servicePriority)).setServiceName(serviceName)
1229 .setServicePriority(servicePriority).setServiceType(ServiceTypeFlowBased.class)
1230 .addAugmentation(StypeOpenflow.class, augBuilder.build()).build();
1233 public static InstanceIdentifier<BoundServices> buildServiceId(String interfaceName, short serviceIndex) {
1234 return InstanceIdentifier.builder(ServiceBindings.class)
1235 .child(ServicesInfo.class, new ServicesInfoKey(interfaceName, ServiceModeIngress.class))
1236 .child(BoundServices.class, new BoundServicesKey(serviceIndex)).build();
1239 public static List<MatchInfo> getTunnelMatchesForServiceId(int elanTag) {
1240 List<MatchInfo> mkMatches = new ArrayList<>();
1241 // Matching metadata
1242 mkMatches.add(new MatchTunnelId(BigInteger.valueOf(elanTag)));
1247 public void removeTerminatingServiceAction(BigInteger destDpId, int serviceId) {
1248 RemoveTerminatingServiceActionsInput input = new RemoveTerminatingServiceActionsInputBuilder()
1249 .setDpnId(destDpId).setServiceId(serviceId).build();
1250 Future<RpcResult<RemoveTerminatingServiceActionsOutput>> futureObject =
1251 itmRpcService.removeTerminatingServiceActions(input);
1253 RpcResult<RemoveTerminatingServiceActionsOutput> result = futureObject.get();
1254 if (result.isSuccessful()) {
1255 LOG.debug("Successfully completed removeTerminatingServiceActions for ELAN with serviceId {} on "
1256 + "dpn {}", serviceId, destDpId);
1258 LOG.debug("Failure in removeTerminatingServiceAction RPC call for ELAN with serviceId {} on "
1259 + "dpn {}", serviceId, destDpId);
1261 } catch (InterruptedException | ExecutionException e) {
1262 LOG.error("Error in RPC call removeTerminatingServiceActions for ELAN with serviceId {} on "
1263 + "dpn {}", serviceId, destDpId, e);
1268 * Gets the external tunnel.
1270 * @param sourceDevice
1272 * @param destinationDevice
1273 * the destination device
1274 * @param datastoreType
1275 * the datastore type
1276 * @return the external tunnel
1278 public ExternalTunnel getExternalTunnel(String sourceDevice, String destinationDevice,
1279 LogicalDatastoreType datastoreType) {
1280 Class<? extends TunnelTypeBase> tunType = TunnelTypeVxlan.class;
1281 InstanceIdentifier<ExternalTunnel> iid = InstanceIdentifier.builder(ExternalTunnelList.class)
1282 .child(ExternalTunnel.class, new ExternalTunnelKey(destinationDevice, sourceDevice, tunType)).build();
1283 return read(broker, datastoreType, iid).orNull();
1287 * Gets the external tunnel.
1289 * @param interfaceName
1290 * the interface name
1291 * @param datastoreType
1292 * the datastore type
1293 * @return the external tunnel
1295 public ExternalTunnel getExternalTunnel(String interfaceName, LogicalDatastoreType datastoreType) {
1296 ExternalTunnel externalTunnel = null;
1297 List<ExternalTunnel> externalTunnels = getAllExternalTunnels(datastoreType);
1298 for (ExternalTunnel tunnel : externalTunnels) {
1299 if (StringUtils.equalsIgnoreCase(interfaceName, tunnel.getTunnelInterfaceName())) {
1300 externalTunnel = tunnel;
1304 return externalTunnel;
1308 * Gets the all external tunnels.
1310 * @param datastoreType
1311 * the data store type
1312 * @return the all external tunnels
1314 public List<ExternalTunnel> getAllExternalTunnels(LogicalDatastoreType datastoreType) {
1315 InstanceIdentifier<ExternalTunnelList> iid = InstanceIdentifier.builder(ExternalTunnelList.class).build();
1316 return read(broker, datastoreType, iid).toJavaUtil().map(ExternalTunnelList::getExternalTunnel).orElse(
1317 Collections.emptyList());
1320 public static List<MatchInfo> buildMatchesForElanTagShFlagAndDstMac(long elanTag, boolean shFlag, String macAddr) {
1321 List<MatchInfo> mkMatches = new ArrayList<>();
1323 new MatchMetadata(getElanMetadataLabel(elanTag, shFlag), MetaDataUtil.METADATA_MASK_SERVICE_SH_FLAG));
1324 mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddr)));
1329 * Checks if is interface operational.
1331 * @param interfaceName
1332 * the interface name
1335 * @return true, if is interface operational
1337 public static boolean isInterfaceOperational(String interfaceName, DataBroker dataBroker) {
1338 if (StringUtils.isBlank(interfaceName)) {
1341 Interface ifState = getInterfaceStateFromOperDS(interfaceName, dataBroker);
1342 if (ifState == null) {
1345 return ifState.getOperStatus() == OperStatus.Up && ifState.getAdminStatus() == AdminStatus.Up;
1349 * Gets the interface state from operational ds.
1351 * @param interfaceName
1352 * the interface name
1355 * @return the interface state from oper ds
1357 public static org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1358 .ietf.interfaces.rev140508.interfaces.state.Interface getInterfaceStateFromOperDS(
1359 String interfaceName, DataBroker dataBroker) {
1360 InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1361 .ietf.interfaces.rev140508.interfaces.state.Interface> ifStateId = createInterfaceStateInstanceIdentifier(
1363 return MDSALUtil.read(dataBroker, LogicalDatastoreType.OPERATIONAL, ifStateId).orNull();
1367 * Creates the interface state instance identifier.
1369 * @param interfaceName
1370 * the interface name
1371 * @return the instance identifier
1373 public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1374 .ietf.interfaces.rev140508.interfaces.state.Interface> createInterfaceStateInstanceIdentifier(
1375 String interfaceName) {
1376 InstanceIdentifierBuilder<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1377 .ietf.interfaces.rev140508.interfaces.state.Interface> idBuilder = InstanceIdentifier
1378 .builder(InterfacesState.class)
1379 .child(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1380 .ietf.interfaces.rev140508.interfaces.state.Interface.class,
1381 new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1382 .ietf.interfaces.rev140508.interfaces.state.InterfaceKey(
1384 return idBuilder.build();
1388 public static CheckedFuture<Void, TransactionCommitFailedException> waitForTransactionToComplete(
1389 WriteTransaction tx) {
1390 CheckedFuture<Void, TransactionCommitFailedException> futures = tx.submit();
1393 } catch (InterruptedException | ExecutionException e) {
1394 // NETVIRT-1215: Do not log.error() here, only debug(); but callers *MUST* @CheckReturnValue
1395 LOG.debug("Error writing to datastore", e);
1400 public static boolean isVxlan(@Nullable ElanInstance elanInstance) {
1401 return elanInstance != null && elanInstance.getSegmentType() != null
1402 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1403 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId() != 0;
1406 private static boolean isVxlanSegment(ElanInstance elanInstance) {
1407 if (elanInstance != null) {
1408 List<ElanSegments> elanSegments = elanInstance.getElanSegments();
1409 if (elanSegments != null) {
1410 for (ElanSegments segment : elanSegments) {
1411 if (segment != null && segment.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1412 && segment.getSegmentationId() != null
1413 && segment.getSegmentationId().longValue() != 0) {
1422 public static boolean isVxlanNetworkOrVxlanSegment(ElanInstance elanInstance) {
1423 return isVxlan(elanInstance) || isVxlanSegment(elanInstance);
1426 public static Long getVxlanSegmentationId(ElanInstance elanInstance) {
1427 Long segmentationId = 0L;
1428 if (elanInstance == null) {
1429 return segmentationId;
1432 if (elanInstance.getSegmentType() != null
1433 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1434 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId().longValue() != 0) {
1435 segmentationId = elanInstance.getSegmentationId();
1437 for (ElanSegments segment: elanInstance.getElanSegments()) {
1438 if (segment != null && segment.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1439 && segment.getSegmentationId() != null
1440 && segment.getSegmentationId().longValue() != 0) {
1441 segmentationId = segment.getSegmentationId();
1445 return segmentationId;
1448 public static boolean isVlan(ElanInstance elanInstance) {
1449 return elanInstance != null && elanInstance.getSegmentType() != null
1450 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVlan.class)
1451 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId() != 0;
1454 public static boolean isFlat(ElanInstance elanInstance) {
1455 return elanInstance != null && elanInstance.getSegmentType() != null
1456 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeFlat.class);
1459 public void addDmacRedirectToDispatcherFlows(Long elanTag, String displayName,
1460 String macAddress, List<BigInteger> dpnIds) {
1461 for (BigInteger dpId : dpnIds) {
1462 ListenableFutures.addErrorLogging(txRunner.callWithNewWriteOnlyTransactionAndSubmit(
1463 tx -> mdsalManager.addFlowToTx(
1464 buildDmacRedirectToDispatcherFlow(dpId, macAddress, displayName, elanTag), tx)), LOG,
1465 "Error adding DMAC redirect to dispatcher flows");
1469 public void removeDmacRedirectToDispatcherFlows(Long elanTag, String macAddress, List<BigInteger> dpnIds) {
1470 for (BigInteger dpId : dpnIds) {
1471 String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, macAddress, elanTag);
1472 mdsalManager.removeFlow(dpId, MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, flowId));
1476 public static FlowEntity buildDmacRedirectToDispatcherFlow(BigInteger dpId, String dstMacAddress,
1477 String displayName, long elanTag) {
1478 List<MatchInfo> matches = new ArrayList<>();
1479 matches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
1480 matches.add(new MatchEthernetDestination(new MacAddress(dstMacAddress)));
1481 List<InstructionInfo> instructions = new ArrayList<>();
1482 List<ActionInfo> actions = new ArrayList<>();
1483 actions.add(new ActionNxResubmit(NwConstants.LPORT_DISPATCHER_TABLE));
1485 instructions.add(new InstructionApplyActions(actions));
1486 String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, dstMacAddress, elanTag);
1487 return MDSALUtil.buildFlowEntity(dpId, NwConstants.ELAN_DMAC_TABLE, flowId, 20, displayName, 0, 0,
1488 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)),
1489 matches, instructions);
1492 public String getExternalElanInterface(String elanInstanceName, BigInteger dpnId) {
1493 DpnInterfaces dpnInterfaces = getElanInterfaceInfoByElanDpn(elanInstanceName, dpnId);
1494 if (dpnInterfaces == null || dpnInterfaces.getInterfaces() == null) {
1495 LOG.trace("Elan {} does not have interfaces in DPN {}", elanInstanceName, dpnId);
1499 for (String dpnInterface : dpnInterfaces.getInterfaces()) {
1500 if (interfaceManager.isExternalInterface(dpnInterface)) {
1501 return dpnInterface;
1505 LOG.trace("Elan {} does not have any external interace attached to DPN {}", elanInstanceName, dpnId);
1509 public static String getElanMacDPNKey(long elanTag, String macAddress, BigInteger dpnId) {
1510 String elanMacDmacDpnKey = "MAC-" + macAddress + " ELAN_TAG-" + elanTag + "DPN_ID-" + dpnId;
1511 return elanMacDmacDpnKey.intern();
1514 public static String getElanMacKey(long elanTag, String macAddress) {
1515 String elanMacKey = "MAC-" + macAddress + " ELAN_TAG-" + elanTag;
1516 return elanMacKey.intern();
1519 public static List<ListenableFuture<Void>>
1520 returnFailedListenableFutureIfTransactionCommitFailedExceptionCauseOrElseThrow(RuntimeException exception) {
1522 Throwable cause = exception.getCause();
1523 if (cause != null && cause instanceof TransactionCommitFailedException) {
1524 return Collections.singletonList(Futures.immediateFailedFuture(cause));
1530 public static List<PhysAddress> getPhysAddress(List<String> macAddress) {
1531 Preconditions.checkNotNull(macAddress, "macAddress cannot be null");
1532 List<PhysAddress> physAddresses = new ArrayList<>();
1533 for (String mac : macAddress) {
1534 physAddresses.add(new PhysAddress(mac));
1536 return physAddresses;
1539 public static List<StaticMacEntries> getStaticMacEntries(List<String> staticMacAddresses) {
1540 if (isEmpty(staticMacAddresses)) {
1541 return Collections.EMPTY_LIST;
1543 StaticMacEntriesBuilder staticMacEntriesBuilder = new StaticMacEntriesBuilder();
1544 List<StaticMacEntries> staticMacEntries = new ArrayList<>();
1545 List<PhysAddress> physAddressList = getPhysAddress(staticMacAddresses);
1546 for (PhysAddress physAddress : physAddressList) {
1547 staticMacEntries.add(staticMacEntriesBuilder.setMacAddress(physAddress).build());
1549 return staticMacEntries;
1552 public static InstanceIdentifier<StaticMacEntries> getStaticMacEntriesCfgDataPathIdentifier(String interfaceName,
1553 String macAddress) {
1554 return InstanceIdentifier.builder(ElanInterfaces.class)
1555 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).child(StaticMacEntries.class,
1556 new StaticMacEntriesKey(new PhysAddress(macAddress))).build();
1559 public static List<StaticMacEntries> getDeletedEntries(List<StaticMacEntries> originalStaticMacEntries,
1560 List<StaticMacEntries> updatedStaticMacEntries) {
1561 if (isEmpty(originalStaticMacEntries)) {
1562 return Collections.EMPTY_LIST;
1564 List<StaticMacEntries> deleted = Lists.newArrayList(originalStaticMacEntries);
1565 if (isNotEmpty(updatedStaticMacEntries)) {
1566 deleted.removeAll(updatedStaticMacEntries);
1571 public static <T> List<T> diffOf(List<T> orig, List<T> updated) {
1572 if (isEmpty(orig)) {
1573 return Collections.EMPTY_LIST;
1575 List<T> diff = Lists.newArrayList(orig);
1576 if (isNotEmpty(updated)) {
1577 diff.removeAll(updated);
1582 public static void segregateToBeDeletedAndAddEntries(List<StaticMacEntries> originalStaticMacEntries,
1583 List<StaticMacEntries> updatedStaticMacEntries) {
1584 if (isNotEmpty(updatedStaticMacEntries)) {
1585 List<StaticMacEntries> existingClonedStaticMacEntries = new ArrayList<>();
1586 if (isNotEmpty(originalStaticMacEntries)) {
1587 existingClonedStaticMacEntries.addAll(0, originalStaticMacEntries);
1588 originalStaticMacEntries.removeAll(updatedStaticMacEntries);
1589 updatedStaticMacEntries.removeAll(existingClonedStaticMacEntries);
1594 public static boolean isEmpty(Collection collection) {
1595 return collection == null || collection.isEmpty();
1598 public static boolean isNotEmpty(Collection collection) {
1599 return !isEmpty(collection);
1602 public Optional<IpAddress> getSourceIpAddress(Ethernet ethernet) {
1603 Optional<IpAddress> srcIpAddress = Optional.absent();
1604 if (ethernet.getPayload() == null) {
1605 return srcIpAddress;
1607 byte[] ipAddrBytes = null;
1608 if (ethernet.getPayload() instanceof IPv4) {
1609 IPv4 ipv4 = (IPv4) ethernet.getPayload();
1610 ipAddrBytes = Ints.toByteArray(ipv4.getSourceAddress());
1611 } else if (ethernet.getPayload() instanceof ARP) {
1612 ipAddrBytes = ((ARP) ethernet.getPayload()).getSenderProtocolAddress();
1614 if (ipAddrBytes != null) {
1615 String ipAddr = NWUtil.toStringIpAddress(ipAddrBytes);
1616 return Optional.of(IpAddressBuilder.getDefaultInstance(ipAddr));
1618 return srcIpAddress;
1621 public List<MacEntry> getElanMacEntries(String elanName) {
1622 MacTable macTable = getElanMacTable(elanName);
1623 if (macTable == null) {
1624 return Collections.emptyList();
1626 return macTable.getMacEntry();
1629 public boolean isTunnelInLogicalGroup(String interfaceName) {
1630 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1631 .ietf.interfaces.rev140508.interfaces.Interface configIface =
1632 interfaceManager.getInterfaceInfoFromConfigDataStore(interfaceName);
1633 if (configIface == null) {
1634 configIface = iitmProvider.getInterface(interfaceName);
1636 if (configIface == null) {
1639 IfTunnel ifTunnel = configIface.augmentation(IfTunnel.class);
1640 if (ifTunnel != null && ifTunnel.getTunnelInterfaceType().isAssignableFrom(TunnelTypeVxlan.class)) {
1641 ParentRefs refs = configIface.augmentation(ParentRefs.class);
1642 if (refs != null && !Strings.isNullOrEmpty(refs.getParentInterface())) {
1643 return true; //multiple VxLAN tunnels enabled, i.e. only logical tunnel should be treated
1649 public static InstanceIdentifier<Flow> getFlowIid(Flow flow, BigInteger dpnId) {
1650 FlowKey flowKey = new FlowKey(new FlowId(flow.getId()));
1651 org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId nodeId =
1652 new org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId("openflow:" + dpnId);
1653 org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node nodeDpn =
1654 new NodeBuilder().setId(nodeId).withKey(new NodeKey(nodeId)).build();
1655 return InstanceIdentifier.builder(Nodes.class)
1656 .child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node.class,
1657 nodeDpn.key()).augmentation(FlowCapableNode.class)
1658 .child(Table.class, new TableKey(flow.getTableId())).child(Flow.class, flowKey).build();
1661 public static String getElanInterfaceJobKey(String interfaceName) {
1662 return "elaninterface-" + interfaceName;
1665 public void removeArpResponderFlow(BigInteger dpnId, String ingressInterfaceName, String ipAddress,
1667 LOG.info("Removing the ARP responder flow on DPN {} of Interface {} with IP {}", dpnId, ingressInterfaceName,
1669 ArpResponderUtil.removeFlow(mdsalManager, dpnId, ArpResponderUtil.getFlowId(lportTag, ipAddress));
1672 public static String getRouterPordIdFromElanInstance(DataBroker dataBroker, String elanInstanceName) {
1673 Optional<Subnetmaps> subnetMapsData =
1674 read(dataBroker, LogicalDatastoreType.CONFIGURATION, buildSubnetMapsWildCardPath());
1675 if (subnetMapsData.isPresent()) {
1676 List<Subnetmap> subnetMapList = subnetMapsData.get().getSubnetmap();
1677 if (subnetMapList != null && !subnetMapList.isEmpty()) {
1678 for (Subnetmap subnet : subnetMapList) {
1679 if (subnet.getNetworkId().getValue().equals(elanInstanceName)) {
1680 if (subnet.getRouterInterfacePortId() != null) {
1681 return subnet.getRouterInterfacePortId().getValue();
1690 static InstanceIdentifier<Subnetmaps> buildSubnetMapsWildCardPath() {
1691 return InstanceIdentifier.create(Subnetmaps.class);