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.Nonnull;
28 import javax.annotation.Nullable;
29 import javax.inject.Inject;
30 import javax.inject.Singleton;
31 import org.apache.commons.lang3.StringUtils;
32 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
33 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
34 import org.opendaylight.controller.md.sal.binding.api.ReadTransaction;
35 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
36 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
37 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
38 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
39 import org.opendaylight.genius.infra.ManagedNewTransactionRunner;
40 import org.opendaylight.genius.infra.ManagedNewTransactionRunnerImpl;
41 import org.opendaylight.genius.interfacemanager.globals.InterfaceInfo;
42 import org.opendaylight.genius.interfacemanager.globals.InterfaceServiceUtil;
43 import org.opendaylight.genius.interfacemanager.interfaces.IInterfaceManager;
44 import org.opendaylight.genius.itm.globals.ITMConstants;
45 import org.opendaylight.genius.mdsalutil.ActionInfo;
46 import org.opendaylight.genius.mdsalutil.FlowEntity;
47 import org.opendaylight.genius.mdsalutil.FlowEntityBuilder;
48 import org.opendaylight.genius.mdsalutil.InstructionInfo;
49 import org.opendaylight.genius.mdsalutil.MDSALUtil;
50 import org.opendaylight.genius.mdsalutil.MatchInfo;
51 import org.opendaylight.genius.mdsalutil.MetaDataUtil;
52 import org.opendaylight.genius.mdsalutil.NWUtil;
53 import org.opendaylight.genius.mdsalutil.NwConstants;
54 import org.opendaylight.genius.mdsalutil.actions.ActionNxResubmit;
55 import org.opendaylight.genius.mdsalutil.instructions.InstructionApplyActions;
56 import org.opendaylight.genius.mdsalutil.instructions.InstructionGotoTable;
57 import org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager;
58 import org.opendaylight.genius.mdsalutil.matches.MatchEthernetDestination;
59 import org.opendaylight.genius.mdsalutil.matches.MatchEthernetSource;
60 import org.opendaylight.genius.mdsalutil.matches.MatchMetadata;
61 import org.opendaylight.genius.mdsalutil.matches.MatchTunnelId;
62 import org.opendaylight.genius.mdsalutil.packet.ARP;
63 import org.opendaylight.genius.mdsalutil.packet.Ethernet;
64 import org.opendaylight.genius.mdsalutil.packet.IPv4;
65 import org.opendaylight.infrautils.utils.concurrent.JdkFutures;
66 import org.opendaylight.infrautils.utils.concurrent.ListenableFutures;
67 import org.opendaylight.netvirt.elan.ElanException;
68 import org.opendaylight.netvirt.elan.arp.responder.ArpResponderUtil;
69 import org.opendaylight.netvirt.elan.cache.ElanInterfaceCache;
70 import org.opendaylight.netvirt.elanmanager.api.ElanHelper;
71 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
72 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddressBuilder;
73 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfacesState;
74 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface;
75 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.AdminStatus;
76 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.OperStatus;
77 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
78 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.PhysAddress;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInput;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInputBuilder;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdOutput;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdManagerService;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInput;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInputBuilder;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406.IfIndexesInterfaceMap;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._if.indexes._interface.map.IfIndexInterface;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._if.indexes._interface.map.IfIndexInterfaceKey;
96 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfTunnel;
97 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.ParentRefs;
98 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeBase;
99 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeVxlan;
100 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceInput;
101 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceInputBuilder;
102 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceOutput;
103 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.OdlInterfaceRpcService;
104 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceBindings;
105 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceModeIngress;
106 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceTypeFlowBased;
107 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflow;
108 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflowBuilder;
109 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.ServicesInfo;
110 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.ServicesInfoKey;
111 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServices;
112 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesBuilder;
113 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesKey;
114 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.ExternalTunnelList;
115 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnel;
116 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnelKey;
117 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.ItmRpcService;
118 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsInput;
119 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsInputBuilder;
120 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsOutput;
121 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
122 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
123 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
124 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
125 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
126 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.config.rev150710.ElanConfig;
127 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInstance;
128 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInstanceBuilder;
129 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInterface;
130 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInterface.EtreeInterfaceType;
131 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTag;
132 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTagName;
133 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTagNameBuilder;
134 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanDpnInterfaces;
135 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanForwardingTables;
136 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInstances;
137 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaceForwardingEntries;
138 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaces;
139 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanState;
140 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanTagNameMap;
141 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeFlat;
142 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeVlan;
143 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeVxlan;
144 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan._interface.forwarding.entries.ElanInterfaceMac;
145 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan._interface.forwarding.entries.ElanInterfaceMacKey;
146 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesList;
147 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesListKey;
148 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfaces;
149 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfacesKey;
150 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTable;
151 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTableBuilder;
152 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTableKey;
153 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstance;
154 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstanceBuilder;
155 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.elan.instance.ElanSegments;
156 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterface;
157 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterfaceKey;
158 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntries;
159 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntriesBuilder;
160 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntriesKey;
161 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.Elan;
162 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.ElanBuilder;
163 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.ElanKey;
164 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagName;
165 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagNameBuilder;
166 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagNameKey;
167 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntry;
168 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntryKey;
169 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.Subnetmaps;
170 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.subnetmaps.Subnetmap;
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 final DataBroker broker;
184 private final ManagedNewTransactionRunner txRunner;
185 private final IMdsalApiManager mdsalManager;
186 private final OdlInterfaceRpcService interfaceManagerRpcService;
187 private final ItmRpcService itmRpcService;
188 private final IInterfaceManager interfaceManager;
189 private final ElanConfig elanConfig;
190 private final ElanItmUtils elanItmUtils;
191 private final ElanEtreeUtils elanEtreeUtils;
192 private final ElanInterfaceCache elanInterfaceCache;
194 public static final FutureCallback<Void> DEFAULT_CALLBACK = new FutureCallback<Void>() {
196 public void onSuccess(Void result) {
197 LOG.debug("Success in Datastore operation");
201 public void onFailure(Throwable error) {
202 LOG.error("Error in Datastore operation", error);
207 public ElanUtils(DataBroker dataBroker, IMdsalApiManager mdsalManager,
208 OdlInterfaceRpcService interfaceManagerRpcService, ItmRpcService itmRpcService, ElanConfig elanConfig,
209 IInterfaceManager interfaceManager, ElanEtreeUtils elanEtreeUtils, ElanItmUtils elanItmUtils,
210 ElanInterfaceCache elanInterfaceCache) {
211 this.broker = dataBroker;
212 this.txRunner = new ManagedNewTransactionRunnerImpl(dataBroker);
213 this.mdsalManager = mdsalManager;
214 this.interfaceManagerRpcService = interfaceManagerRpcService;
215 this.itmRpcService = itmRpcService;
216 this.interfaceManager = interfaceManager;
217 this.elanConfig = elanConfig;
218 this.elanEtreeUtils = elanEtreeUtils;
219 this.elanItmUtils = elanItmUtils;
220 this.elanInterfaceCache = elanInterfaceCache;
223 public final Boolean isOpenstackVniSemanticsEnforced() {
224 return elanConfig.isOpenstackVniSemanticsEnforced() != null
225 ? elanConfig.isOpenstackVniSemanticsEnforced() : false;
229 * Uses the IdManager to retrieve a brand new ElanTag.
235 * @return the integer
237 public static Long retrieveNewElanTag(IdManagerService idManager, String idKey) {
239 AllocateIdInput getIdInput = new AllocateIdInputBuilder().setPoolName(ElanConstants.ELAN_ID_POOL_NAME)
240 .setIdKey(idKey).build();
243 Future<RpcResult<AllocateIdOutput>> result = idManager.allocateId(getIdInput);
244 RpcResult<AllocateIdOutput> rpcResult = result.get();
245 if (rpcResult.isSuccessful()) {
246 return rpcResult.getResult().getIdValue();
248 LOG.warn("RPC Call to Allocate Id returned with Errors {}", rpcResult.getErrors());
250 } catch (InterruptedException | ExecutionException e) {
251 LOG.warn("Exception when Allocating Id", e);
256 public static void releaseId(IdManagerService idManager, String poolName, String idKey) {
257 ReleaseIdInput releaseIdInput = new ReleaseIdInputBuilder().setPoolName(poolName).setIdKey(idKey).build();
258 JdkFutures.addErrorLogging(idManager.releaseId(releaseIdInput), LOG, "Release Id");
264 * @deprecated Consider using {@link #read2(LogicalDatastoreType, InstanceIdentifier)} with proper exception
266 * @param broker dataBroker
267 * @param datastoreType Logical DataStore type
268 * @param path IID to read
269 * @param <T> T extends DataObject
270 * @return the read value T
273 @SuppressWarnings("checkstyle:IllegalCatch")
274 public static <T extends DataObject> Optional<T> read(@Nonnull DataBroker broker,
275 LogicalDatastoreType datastoreType, InstanceIdentifier<T> path) {
276 try (ReadOnlyTransaction tx = broker.newReadOnlyTransaction()) {
277 return tx.read(datastoreType, path).get();
278 } catch (Exception e) {
279 throw new RuntimeException(e);
283 public <T extends DataObject> Optional<T> read2(LogicalDatastoreType datastoreType, InstanceIdentifier<T> path)
284 throws ReadFailedException {
285 try (ReadOnlyTransaction tx = broker.newReadOnlyTransaction()) {
286 CheckedFuture<Optional<T>, ReadFailedException> checkedFuture = tx.read(datastoreType, path);
287 return checkedFuture.checkedGet();
291 @SuppressWarnings("checkstyle:ForbiddenMethod")
292 public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
293 InstanceIdentifier<T> path) {
294 WriteTransaction tx = broker.newWriteOnlyTransaction();
295 tx.delete(datastoreType, path);
296 Futures.addCallback(tx.submit(), DEFAULT_CALLBACK, MoreExecutors.directExecutor());
299 @SuppressWarnings("checkstyle:ForbiddenMethod")
300 public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
301 InstanceIdentifier<T> path, FutureCallback<Void> callback) {
302 WriteTransaction tx = broker.newWriteOnlyTransaction();
303 tx.delete(datastoreType, path);
304 Futures.addCallback(tx.submit(), callback, MoreExecutors.directExecutor());
307 public static InstanceIdentifier<ElanInstance> getElanInstanceIdentifier() {
308 return InstanceIdentifier.builder(ElanInstances.class).child(ElanInstance.class).build();
311 public static InstanceIdentifier<ElanInterface> getElanInterfaceConfigurationDataPathId(String interfaceName) {
312 return InstanceIdentifier.builder(ElanInterfaces.class)
313 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).build();
316 // elan-state Operational container
317 public static Elan getElanByName(DataBroker broker, String elanInstanceName) {
318 InstanceIdentifier<Elan> elanIdentifier = getElanInstanceOperationalDataPath(elanInstanceName);
319 return MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL, elanIdentifier).orNull();
323 public static Elan getElanByName(ReadTransaction tx, String elanInstanceName) throws ReadFailedException {
324 return tx.read(LogicalDatastoreType.OPERATIONAL,
325 getElanInstanceOperationalDataPath(elanInstanceName)).checkedGet().orNull();
328 public static InstanceIdentifier<Elan> getElanInstanceOperationalDataPath(String elanInstanceName) {
329 return InstanceIdentifier.builder(ElanState.class).child(Elan.class, new ElanKey(elanInstanceName)).build();
332 // grouping of forwarding-entries
333 public MacEntry getInterfaceMacEntriesOperationalDataPath(String interfaceName, PhysAddress physAddress) {
334 InstanceIdentifier<MacEntry> existingMacEntryId = getInterfaceMacEntriesIdentifierOperationalDataPath(
335 interfaceName, physAddress);
336 return read(broker, LogicalDatastoreType.OPERATIONAL, existingMacEntryId).orNull();
339 public MacEntry getInterfaceMacEntriesOperationalDataPathFromId(InstanceIdentifier identifier) {
340 Optional<MacEntry> existingInterfaceMacEntry = read(broker,
341 LogicalDatastoreType.OPERATIONAL, identifier);
342 return existingInterfaceMacEntry.orNull();
345 public static InstanceIdentifier<MacEntry> getInterfaceMacEntriesIdentifierOperationalDataPath(String interfaceName,
346 PhysAddress physAddress) {
347 return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class)
348 .child(ElanInterfaceMac.class, new ElanInterfaceMacKey(interfaceName))
349 .child(MacEntry.class, new MacEntryKey(physAddress)).build();
353 // elan-forwarding-tables Operational container
354 public Optional<MacEntry> getMacEntryForElanInstance(String elanName, PhysAddress physAddress) {
355 InstanceIdentifier<MacEntry> macId = getMacEntryOperationalDataPath(elanName, physAddress);
356 return read(broker, LogicalDatastoreType.OPERATIONAL, macId);
359 public Optional<MacEntry> getMacEntryForElanInstance(ReadTransaction tx, String elanName, PhysAddress physAddress)
360 throws ReadFailedException {
361 InstanceIdentifier<MacEntry> macId = getMacEntryOperationalDataPath(elanName, physAddress);
362 return tx.read(LogicalDatastoreType.OPERATIONAL, macId).checkedGet();
365 public MacEntry getMacEntryFromElanMacId(InstanceIdentifier identifier) {
366 Optional<MacEntry> existingInterfaceMacEntry = read(broker,
367 LogicalDatastoreType.OPERATIONAL, identifier);
368 return existingInterfaceMacEntry.orNull();
371 public static InstanceIdentifier<MacEntry> getMacEntryOperationalDataPath(String elanName,
372 PhysAddress physAddress) {
373 return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class, new MacTableKey(elanName))
374 .child(MacEntry.class, new MacEntryKey(physAddress)).build();
377 public static InstanceIdentifier<MacTable> getElanMacTableOperationalDataPath(String elanName) {
378 return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class, new MacTableKey(elanName))
382 // elan-interface-forwarding-entries Operational container
383 public ElanInterfaceMac getElanInterfaceMacByInterfaceName(String interfaceName) {
384 return getElanInterfaceMacByInterfaceName(broker, interfaceName);
388 public static ElanInterfaceMac getElanInterfaceMacByInterfaceName(DataBroker dataBroker, String interfaceName) {
389 InstanceIdentifier<ElanInterfaceMac> elanInterfaceId = getElanInterfaceMacEntriesOperationalDataPath(
391 return read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanInterfaceId).orNull();
395 * Gets the elan interface mac addresses.
397 * @param interfaceName
399 * @return the elan interface mac addresses
401 public List<PhysAddress> getElanInterfaceMacAddresses(String interfaceName) {
402 List<PhysAddress> macAddresses = new ArrayList<>();
403 ElanInterfaceMac elanInterfaceMac = getElanInterfaceMacByInterfaceName(interfaceName);
404 if (elanInterfaceMac != null && elanInterfaceMac.getMacEntry() != null) {
405 List<MacEntry> macEntries = elanInterfaceMac.getMacEntry();
406 for (MacEntry macEntry : macEntries) {
407 macAddresses.add(macEntry.getMacAddress());
413 public static InstanceIdentifier<ElanInterfaceMac> getElanInterfaceMacEntriesOperationalDataPath(
414 String interfaceName) {
415 return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class)
416 .child(ElanInterfaceMac.class, new ElanInterfaceMacKey(interfaceName)).build();
420 * Returns the list of Interfaces that belong to an Elan on an specific DPN.
421 * Data retrieved from Elan's operational DS: elan-dpn-interfaces container
423 * @param elanInstanceName
424 * name of the Elan to which the interfaces must belong to
426 * Id of the DPN where the interfaces are located
427 * @return the elan interface Info
429 public DpnInterfaces getElanInterfaceInfoByElanDpn(String elanInstanceName, BigInteger dpId) {
430 InstanceIdentifier<DpnInterfaces> elanDpnInterfacesId = getElanDpnInterfaceOperationalDataPath(elanInstanceName,
432 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfacesId).orNull();
436 * Returns the InstanceIdentifier that points to the Interfaces of an Elan
437 * in a given DPN in the Operational DS. Data retrieved from Elans's
438 * operational DS: dpn-interfaces list
440 * @param elanInstanceName
441 * name of the Elan to which the interfaces must belong to
443 * Id of the DPN where the interfaces are located
444 * @return the elan dpn interface
446 public static InstanceIdentifier<DpnInterfaces> getElanDpnInterfaceOperationalDataPath(String elanInstanceName,
448 return InstanceIdentifier.builder(ElanDpnInterfaces.class)
449 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName))
450 .child(DpnInterfaces.class, new DpnInterfacesKey(dpId)).build();
453 // elan-tag-name-map Operational Container
454 public ElanTagName getElanInfoByElanTag(long elanTag) {
455 InstanceIdentifier<ElanTagName> elanId = getElanInfoEntriesOperationalDataPath(elanTag);
456 Optional<ElanTagName> existingElanInfo = read(broker,
457 LogicalDatastoreType.OPERATIONAL, elanId);
458 return existingElanInfo.orNull();
461 public static InstanceIdentifier<ElanTagName> getElanInfoEntriesOperationalDataPath(long elanTag) {
462 return InstanceIdentifier.builder(ElanTagNameMap.class).child(ElanTagName.class, new ElanTagNameKey(elanTag))
466 // interface-index-tag operational container
467 public Optional<IfIndexInterface> getInterfaceInfoByInterfaceTag(long interfaceTag) {
468 InstanceIdentifier<IfIndexInterface> interfaceId = getInterfaceInfoEntriesOperationalDataPath(interfaceTag);
469 return read(broker, LogicalDatastoreType.OPERATIONAL, interfaceId);
472 public static InstanceIdentifier<IfIndexInterface> getInterfaceInfoEntriesOperationalDataPath(long interfaceTag) {
473 return InstanceIdentifier.builder(IfIndexesInterfaceMap.class)
474 .child(IfIndexInterface.class, new IfIndexInterfaceKey((int) interfaceTag)).build();
477 public static InstanceIdentifier<ElanDpnInterfacesList> getElanDpnOperationDataPath(String elanInstanceName) {
478 return InstanceIdentifier.builder(ElanDpnInterfaces.class)
479 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName)).build();
482 public ElanDpnInterfacesList getElanDpnInterfacesList(String elanName) {
483 InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanName);
484 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orNull();
487 public ElanDpnInterfaces getElanDpnInterfacesList() {
488 InstanceIdentifier<ElanDpnInterfaces> elanDpnInterfaceId = InstanceIdentifier.builder(ElanDpnInterfaces.class)
490 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orNull();
494 * This method is useful get all ELAN participating CSS dpIds to install
495 * program remote dmac entries and updating remote bc groups for tor
498 * @param elanInstanceName
499 * the elan instance name
500 * @return list of dpIds
503 public List<BigInteger> getParticipatingDpnsInElanInstance(String elanInstanceName) {
504 List<BigInteger> dpIds = new ArrayList<>();
505 InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
506 Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = read(broker,
507 LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
508 if (!existingElanDpnInterfaces.isPresent()) {
511 List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().getDpnInterfaces();
512 for (DpnInterfaces dpnInterface : dpnInterfaces) {
513 dpIds.add(dpnInterface.getDpId());
519 * To check given dpId is already present in Elan instance. This can be used
520 * to program flow entry in external tunnel table when a new access port
521 * added for first time into the ELAN instance
525 * @param elanInstanceName
526 * the elan instance name
527 * @return true if dpId is already present, otherwise return false
529 public boolean isDpnAlreadyPresentInElanInstance(BigInteger dpId, String elanInstanceName) {
530 InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
531 Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = read(broker,
532 LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
533 if (!existingElanDpnInterfaces.isPresent()) {
536 List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().getDpnInterfaces();
537 for (DpnInterfaces dpnInterface : dpnInterfaces) {
538 if (dpnInterface.getDpId().equals(dpId)) {
545 public ElanForwardingTables getElanForwardingList() {
546 InstanceIdentifier<ElanForwardingTables> elanForwardingTableId = InstanceIdentifier
547 .builder(ElanForwardingTables.class).build();
548 return read(broker, LogicalDatastoreType.OPERATIONAL, elanForwardingTableId).orNull();
551 public static long getElanRemoteBroadCastGroupID(long elanTag) {
552 return ElanConstants.ELAN_GID_MIN + elanTag % ElanConstants.ELAN_GID_MIN * 2;
556 * Gets the elan mac table.
560 * @return the elan mac table
562 public MacTable getElanMacTable(String elanName) {
563 return getElanMacTable(broker, elanName);
567 public static MacTable getElanMacTable(DataBroker dataBroker, String elanName) {
568 InstanceIdentifier<MacTable> elanMacTableId = getElanMacTableOperationalDataPath(elanName);
569 return read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanMacTableId).orNull();
572 public static long getElanLocalBCGId(long elanTag) {
573 return ElanConstants.ELAN_GID_MIN + (elanTag % ElanConstants.ELAN_GID_MIN * 2 - 1);
576 public static long getElanRemoteBCGId(long elanTag) {
577 return ElanConstants.ELAN_GID_MIN + elanTag % ElanConstants.ELAN_GID_MIN * 2;
580 public static long getEtreeLeafLocalBCGId(long etreeLeafTag) {
581 return ElanConstants.ELAN_GID_MIN + (etreeLeafTag % ElanConstants.ELAN_GID_MIN * 2 - 1);
584 public static long getEtreeLeafRemoteBCGId(long etreeLeafTag) {
585 return ElanConstants.ELAN_GID_MIN + etreeLeafTag % ElanConstants.ELAN_GID_MIN * 2;
588 public static BigInteger getElanMetadataLabel(long elanTag, boolean isSHFlagSet) {
589 int shBit = isSHFlagSet ? 1 : 0;
590 return BigInteger.valueOf(elanTag).shiftLeft(24).or(BigInteger.valueOf(shBit));
594 * Setting SMAC, DMAC, UDMAC in this DPN and optionally in other DPNs.
598 * @param interfaceInfo
604 * @param configureRemoteFlows
605 * true if remote dmac flows should be configured as well
606 * @param writeFlowGroupTx
608 * @throws ElanException in case of issues creating the flow objects
610 public void setupMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo,
611 long macTimeout, String macAddress, boolean configureRemoteFlows,
612 WriteTransaction writeFlowGroupTx) throws ElanException {
613 synchronized (getElanMacDPNKey(elanInfo.getElanTag(), macAddress, interfaceInfo.getDpId())) {
614 setupKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress, mdsalManager,
616 setupOrigDmacFlows(elanInfo, interfaceInfo, macAddress, configureRemoteFlows, mdsalManager,
621 public void setupDMacFlowOnRemoteDpn(ElanInstance elanInfo, InterfaceInfo interfaceInfo, BigInteger dstDpId,
622 String macAddress, WriteTransaction writeFlowTx) throws ElanException {
623 String elanInstanceName = elanInfo.getElanInstanceName();
624 setupRemoteDmacFlow(dstDpId, interfaceInfo.getDpId(), interfaceInfo.getInterfaceTag(), elanInfo.getElanTag(),
625 macAddress, elanInstanceName, writeFlowTx, interfaceInfo.getInterfaceName(), elanInfo);
626 LOG.info("Remote Dmac flow entry created for elan Name:{}, logical port Name:{} and"
627 + " mac address {} on dpn:{}", elanInstanceName, interfaceInfo.getPortName(),
628 macAddress, dstDpId);
632 * Inserts a Flow in SMAC table to state that the MAC has already been
635 private void setupKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
636 String macAddress, IMdsalApiManager mdsalApiManager, WriteTransaction writeFlowGroupTx) {
637 FlowEntity flowEntity = buildKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress);
638 mdsalApiManager.addFlowToTx(flowEntity, writeFlowGroupTx);
639 LOG.debug("Known Smac flow entry created for elan Name:{}, logical Interface port:{} and mac address:{}",
640 elanInfo.getElanInstanceName(), elanInfo.getDescription(), macAddress);
643 public FlowEntity buildKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
645 int lportTag = interfaceInfo.getInterfaceTag();
646 // Matching metadata and eth_src fields
647 List<MatchInfo> mkMatches = new ArrayList<>();
648 mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanInfo.getElanTag(), lportTag),
649 ElanHelper.getElanMetadataMask()));
650 mkMatches.add(new MatchEthernetSource(new MacAddress(macAddress)));
651 List<InstructionInfo> mkInstructions = new ArrayList<>();
652 mkInstructions.add(new InstructionGotoTable(NwConstants.ELAN_DMAC_TABLE));
653 BigInteger dpId = interfaceInfo.getDpId();
654 long elanTag = getElanTag(elanInfo, interfaceInfo);
655 return new FlowEntityBuilder()
657 .setTableId(NwConstants.ELAN_SMAC_TABLE)
658 .setFlowId(getKnownDynamicmacFlowRef(NwConstants.ELAN_SMAC_TABLE, dpId, lportTag, macAddress, elanTag))
660 .setFlowName(elanInfo.getDescription())
661 .setIdleTimeOut((int) macTimeout)
663 .setCookie(ElanConstants.COOKIE_ELAN_KNOWN_SMAC.add(BigInteger.valueOf(elanTag)))
664 .setMatchInfoList(mkMatches)
665 .setInstructionInfoList(mkInstructions)
667 // If Mac timeout is 0, the flow won't be deleted automatically, so no need to get notified
668 .setSendFlowRemFlag(macTimeout != 0)
672 private Long getElanTag(ElanInstance elanInfo, InterfaceInfo interfaceInfo) {
673 EtreeInterface etreeInterface = elanInterfaceCache.getEtreeInterface(interfaceInfo.getInterfaceName()).orNull();
674 if (etreeInterface == null || etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
675 return elanInfo.getElanTag();
677 EtreeInstance etreeInstance = elanInfo.augmentation(EtreeInstance.class);
678 if (etreeInstance == null) {
679 LOG.warn("EtreeInterface {} is connected to a non-Etree network: {}",
680 interfaceInfo.getInterfaceName(), elanInfo.getElanInstanceName());
681 return elanInfo.getElanTag();
683 return etreeInstance.getEtreeLeafTagVal().getValue();
689 * Installs a Flow in INTERNAL_TUNNEL_TABLE of the affected DPN that sends
690 * the packet through the specified interface if the tunnel_id matches the
691 * interface's lportTag.
693 * @param interfaceInfo
695 * @param mdsalApiManager
696 * the mdsal API manager
697 * @param writeFlowGroupTx
698 * the writeFLowGroup tx
700 public void setupTermDmacFlows(InterfaceInfo interfaceInfo, IMdsalApiManager mdsalApiManager,
701 WriteTransaction writeFlowGroupTx) {
702 BigInteger dpId = interfaceInfo.getDpId();
703 int lportTag = interfaceInfo.getInterfaceTag();
704 Flow flow = MDSALUtil.buildFlowNew(NwConstants.INTERNAL_TUNNEL_TABLE,
705 getIntTunnelTableFlowRef(NwConstants.INTERNAL_TUNNEL_TABLE, lportTag), 5,
706 String.format("%s:%d", "ITM Flow Entry ", lportTag), 0, 0,
707 ITMConstants.COOKIE_ITM.add(BigInteger.valueOf(lportTag)),
708 getTunnelIdMatchForFilterEqualsLPortTag(lportTag),
709 getInstructionsInPortForOutGroup(interfaceInfo.getInterfaceName()));
710 mdsalApiManager.addFlowToTx(dpId, flow, writeFlowGroupTx);
711 LOG.debug("Terminating service table flow entry created on dpn:{} for logical Interface port:{}", dpId,
712 interfaceInfo.getPortName());
716 * Constructs the FlowName for flows installed in the Internal Tunnel Table,
717 * consisting in tableId + elanTag.
723 * @return the Internal tunnel
725 public static String getIntTunnelTableFlowRef(short tableId, int elanTag) {
726 return new StringBuffer().append(tableId).append(elanTag).toString();
730 * Constructs the Matches that checks that the tunnel_id field contains a
734 * lportTag that must be checked against the tunnel_id field
735 * @return the list of match Info
737 public static List<MatchInfo> getTunnelIdMatchForFilterEqualsLPortTag(int lportTag) {
738 List<MatchInfo> mkMatches = new ArrayList<>();
740 mkMatches.add(new MatchTunnelId(BigInteger.valueOf(lportTag)));
745 * Constructs the Instructions that take the packet over a given interface.
748 * Name of the interface where the packet must be sent over. It
749 * can be a local interface or a tunnel interface (internal or
751 * @return the Instruction
753 public List<Instruction> getInstructionsInPortForOutGroup(String ifName) {
754 List<Instruction> mkInstructions = new ArrayList<>();
755 List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
757 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
758 return mkInstructions;
762 * Returns the list of Actions to be taken when sending the packet through
763 * an Elan interface. Note that this interface can refer to an ElanInterface
764 * where the Elan VM is attached to a DPN or an ITM tunnel interface where
765 * Elan traffic can be sent through. In this latter case, the tunnelKey is
766 * mandatory and it can hold serviceId for internal tunnels or the VNI for
773 * @return the egress actions for interface
775 @SuppressWarnings("checkstyle:IllegalCatch")
776 public List<Action> getEgressActionsForInterface(String ifName, Long tunnelKey) {
777 List<Action> listAction = new ArrayList<>();
779 GetEgressActionsForInterfaceInput getEgressActionInput = new GetEgressActionsForInterfaceInputBuilder()
780 .setIntfName(ifName).setTunnelKey(tunnelKey).build();
781 Future<RpcResult<GetEgressActionsForInterfaceOutput>> result = interfaceManagerRpcService
782 .getEgressActionsForInterface(getEgressActionInput);
783 RpcResult<GetEgressActionsForInterfaceOutput> rpcResult = result.get();
784 if (!rpcResult.isSuccessful()) {
785 LOG.debug("RPC Call to Get egress actions for interface {} returned with Errors {}", ifName,
786 rpcResult.getErrors());
788 List<Action> actions = rpcResult.getResult().getAction();
789 listAction = actions;
791 } catch (Exception e) {
792 LOG.warn("Exception when egress actions for interface {}", ifName, e);
797 private void setupOrigDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
798 boolean configureRemoteFlows, IMdsalApiManager mdsalApiManager,
799 WriteTransaction writeFlowGroupTx)
800 throws ElanException {
801 BigInteger dpId = interfaceInfo.getDpId();
802 String ifName = interfaceInfo.getInterfaceName();
803 long ifTag = interfaceInfo.getInterfaceTag();
804 String elanInstanceName = elanInfo.getElanInstanceName();
806 Long elanTag = elanInfo.getElanTag();
808 setupLocalDmacFlow(elanTag, dpId, ifName, macAddress, elanInfo, mdsalApiManager, ifTag,
810 LOG.debug("Dmac flow entry created for elan Name:{}, logical port Name:{} mand mac address:{} "
811 + "on dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, dpId);
813 if (!configureRemoteFlows) {
817 List<DpnInterfaces> elanDpns = getInvolvedDpnsInElan(elanInstanceName);
818 for (DpnInterfaces elanDpn : elanDpns) {
820 if (elanDpn.getDpId().equals(dpId)) {
824 // Check for the Remote DPN present in Inventory Manager
825 if (!isDpnPresent(elanDpn.getDpId())) {
829 // For remote DPNs a flow is needed to indicate that packets of this ELAN going to this MAC need to be
830 // forwarded through the appropriate ITM tunnel
831 setupRemoteDmacFlow(elanDpn.getDpId(), // srcDpn (the remote DPN in this case)
832 dpId, // dstDpn (the local DPN)
833 interfaceInfo.getInterfaceTag(), // lportTag of the local interface
834 elanTag, // identifier of the Elan
835 macAddress, // MAC to be programmed in remote DPN
836 elanInstanceName, writeFlowGroupTx, ifName, elanInfo
838 LOG.debug("Remote Dmac flow entry created for elan Name:{}, logical port Name:{} and mac address:{} on"
839 + " dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, elanDpn.getDpId());
842 // TODO: Make sure that the same is performed against the ElanDevices.
846 public List<DpnInterfaces> getInvolvedDpnsInElan(String elanName) {
847 return getElanDPNByName(elanName);
851 public List<DpnInterfaces> getElanDPNByName(String elanInstanceName) {
852 InstanceIdentifier<ElanDpnInterfacesList> elanIdentifier = getElanDpnOperationDataPath(elanInstanceName);
853 return MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL, elanIdentifier).toJavaUtil().map(
854 ElanDpnInterfacesList::getDpnInterfaces).orElse(Collections.emptyList());
857 private void setupLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
858 ElanInstance elanInfo, IMdsalApiManager mdsalApiManager, long ifTag, WriteTransaction writeFlowGroupTx) {
859 Flow flowEntity = buildLocalDmacFlowEntry(elanTag, dpId, ifName, macAddress, elanInfo, ifTag);
860 mdsalApiManager.addFlowToTx(dpId, flowEntity, writeFlowGroupTx);
861 installEtreeLocalDmacFlow(elanTag, dpId, ifName, macAddress, elanInfo,
862 ifTag, writeFlowGroupTx);
865 private void installEtreeLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
866 ElanInstance elanInfo, long ifTag, WriteTransaction writeFlowGroupTx) {
867 EtreeInterface etreeInterface = elanInterfaceCache.getEtreeInterface(ifName).orNull();
868 if (etreeInterface != null && etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
869 EtreeLeafTagName etreeTagName = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
870 if (etreeTagName == null) {
871 LOG.warn("Interface {} seems like it belongs to Etree but etreeTagName from elanTag {} is null",
874 Flow flowEntity = buildLocalDmacFlowEntry(etreeTagName.getEtreeLeafTag().getValue(), dpId, ifName,
875 macAddress, elanInfo, ifTag);
876 mdsalManager.addFlowToTx(dpId, flowEntity, writeFlowGroupTx);
881 public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, long lporTag, String macAddress,
883 return String.valueOf(tableId) + elanTag + dpId + lporTag + macAddress;
886 public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, BigInteger remoteDpId,
887 String macAddress, long elanTag) {
888 return String.valueOf(tableId) + elanTag + dpId + remoteDpId + macAddress;
891 public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, String macAddress, long elanTag) {
892 return String.valueOf(tableId) + elanTag + dpId + macAddress;
895 public static String getKnownDynamicmacFlowRef(short elanDmacTable, BigInteger dpId, String extDeviceNodeId,
896 String dstMacAddress, long elanTag, boolean shFlag) {
897 return String.valueOf(elanDmacTable) + elanTag + dpId + extDeviceNodeId + dstMacAddress + shFlag;
901 * Builds the flow to be programmed in the DMAC table of the local DPN (that
902 * is, where the MAC is attached to). This flow consists in:
904 * <p>Match: + elanTag in metadata + packet goes to a MAC locally attached
905 * Actions: + optionally, pop-vlan + set-vlan-id + output to ifName's
922 public Flow buildLocalDmacFlowEntry(long elanTag, BigInteger dpId, String ifName, String macAddress,
923 ElanInstance elanInfo, long ifTag) {
925 List<MatchInfo> mkMatches = new ArrayList<>();
926 mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
927 mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddress)));
929 List<Instruction> mkInstructions = new ArrayList<>();
930 List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
931 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
932 Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
933 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, ifTag, macAddress, elanTag), 20,
934 elanInfo.getElanInstanceName(), 0, 0, ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(
935 BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
940 public void setupRemoteDmacFlow(BigInteger srcDpId, BigInteger destDpId, int lportTag, long elanTag, String
941 macAddress, String displayName, WriteTransaction writeFlowGroupTx, String interfaceName, ElanInstance
942 elanInstance) throws ElanException {
943 if (interfaceManager.isExternalInterface(interfaceName)) {
944 LOG.debug("Ignoring install remote DMAC {} flow on provider interface {} elan {}",
945 macAddress, interfaceName, elanInstance.getElanInstanceName());
949 // if openstack-vni-semantics are enforced, segmentation ID is passed as network VNI for VxLAN based provider
950 // networks, 0 otherwise
951 long lportTagOrVni = !isOpenstackVniSemanticsEnforced() ? lportTag : isVxlanNetworkOrVxlanSegment(elanInstance)
952 ? getVxlanSegmentationId(elanInstance) : 0;
953 flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTagOrVni, elanTag, macAddress, displayName,
955 mdsalManager.addFlowToTx(srcDpId, flowEntity, writeFlowGroupTx);
956 setupEtreeRemoteDmacFlow(srcDpId, destDpId, lportTagOrVni, elanTag, macAddress, displayName, interfaceName,
957 writeFlowGroupTx, elanInstance);
960 private void setupEtreeRemoteDmacFlow(BigInteger srcDpId, BigInteger destDpId, long lportTagOrVni, long elanTag,
961 String macAddress, String displayName, String interfaceName,
962 WriteTransaction writeFlowGroupTx, ElanInstance elanInstance) {
964 EtreeInterface etreeInterface = elanInterfaceCache.getEtreeInterface(interfaceName).orNull();
965 if (etreeInterface != null && etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
966 EtreeLeafTagName etreeTagName = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
967 if (etreeTagName == null) {
968 LOG.warn("Interface {} seems like it belongs to Etree but etreeTagName from elanTag {} is null.",
969 interfaceName, elanTag);
971 flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTagOrVni,
972 etreeTagName.getEtreeLeafTag().getValue(), macAddress, displayName, elanInstance);
973 mdsalManager.addFlowToTx(srcDpId, flowEntity, writeFlowGroupTx);
979 * Builds a Flow to be programmed in a remote DPN's DMAC table. This flow
980 * consists in: Match: + elanTag in packet's metadata + packet going to a
981 * MAC known to be located in another DPN Actions: + set_tunnel_id
982 * + output ITM internal tunnel interface with the other DPN
988 * @param lportTagOrVni
989 * lportTag or network VNI
996 * @param elanInstance
998 * @return the flow remote Dmac
1000 @SuppressWarnings("checkstyle:IllegalCatch")
1001 public Flow buildRemoteDmacFlowEntry(BigInteger srcDpId, BigInteger destDpId, long lportTagOrVni, long elanTag,
1002 String macAddress, String displayName, ElanInstance elanInstance) {
1003 List<MatchInfo> mkMatches = new ArrayList<>();
1004 mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
1005 mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddress)));
1007 List<Instruction> mkInstructions = new ArrayList<>();
1009 // List of Action for the provided Source and Destination DPIDs
1011 List<Action> actions = null;
1012 if (isVlan(elanInstance) || isFlat(elanInstance)) {
1013 String interfaceName = getExternalElanInterface(elanInstance.getElanInstanceName(), srcDpId);
1014 if (null == interfaceName) {
1015 LOG.info("buildRemoteDmacFlowEntry: Could not find interfaceName for {} {}", srcDpId,
1018 actions = getEgressActionsForInterface(interfaceName, null);
1019 } else if (isVxlanNetworkOrVxlanSegment(elanInstance)) {
1020 actions = elanItmUtils.getInternalTunnelItmEgressAction(srcDpId, destDpId, lportTagOrVni);
1022 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
1023 } catch (Exception e) {
1024 LOG.error("Could not get egress actions to add to flow for srcDpId {}, destDpId {}, lportTag/VNI {}",
1025 srcDpId, destDpId, lportTagOrVni, e);
1028 Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
1029 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, srcDpId, destDpId, macAddress, elanTag),
1031 displayName, 0, /* idleTimeout */
1032 0, /* hardTimeout */
1033 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
1039 public void deleteMacFlows(@Nullable ElanInstance elanInfo, @Nullable InterfaceInfo interfaceInfo,
1040 MacEntry macEntry, WriteTransaction deleteFlowGroupTx) {
1041 if (elanInfo == null || interfaceInfo == null) {
1044 String macAddress = macEntry.getMacAddress().getValue();
1045 synchronized (getElanMacDPNKey(elanInfo.getElanTag(), macAddress, interfaceInfo.getDpId())) {
1046 deleteMacFlows(elanInfo, interfaceInfo, macAddress, /* alsoDeleteSMAC */ true, deleteFlowGroupTx);
1050 public void deleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1051 boolean deleteSmac, WriteTransaction deleteFlowGroupTx) {
1052 String elanInstanceName = elanInfo.getElanInstanceName();
1053 List<DpnInterfaces> remoteFEs = getInvolvedDpnsInElan(elanInstanceName);
1054 BigInteger srcdpId = interfaceInfo.getDpId();
1055 boolean isFlowsRemovedInSrcDpn = false;
1056 for (DpnInterfaces dpnInterface : remoteFEs) {
1057 Long elanTag = elanInfo.getElanTag();
1058 BigInteger dstDpId = dpnInterface.getDpId();
1059 if (executeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1060 elanTag, dstDpId, deleteFlowGroupTx)) {
1061 isFlowsRemovedInSrcDpn = true;
1063 executeEtreeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1064 elanTag, dstDpId, deleteFlowGroupTx);
1066 if (!isFlowsRemovedInSrcDpn) {
1067 deleteSmacAndDmacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, deleteFlowGroupTx);
1071 private void executeEtreeDeleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1072 boolean deleteSmac, String elanInstanceName, BigInteger srcdpId, Long elanTag, BigInteger dstDpId,
1073 WriteTransaction deleteFlowGroupTx) {
1074 EtreeLeafTagName etreeLeafTag = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
1075 if (etreeLeafTag != null) {
1076 executeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1077 etreeLeafTag.getEtreeLeafTag().getValue(), dstDpId, deleteFlowGroupTx);
1081 private boolean executeDeleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1082 boolean deleteSmac, String elanInstanceName, BigInteger srcdpId, Long elanTag, BigInteger dstDpId,
1083 WriteTransaction deleteFlowGroupTx) {
1084 boolean isFlowsRemovedInSrcDpn = false;
1085 if (dstDpId.equals(srcdpId)) {
1086 isFlowsRemovedInSrcDpn = true;
1087 deleteSmacAndDmacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, deleteFlowGroupTx);
1088 } else if (isDpnPresent(dstDpId)) {
1090 .removeFlowToTx(dstDpId,
1091 MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, getKnownDynamicmacFlowRef(
1092 NwConstants.ELAN_DMAC_TABLE, dstDpId, srcdpId, macAddress, elanTag)),
1094 LOG.debug("Dmac flow entry deleted for elan:{}, logical interface port:{} and mac address:{} on dpn:{}",
1095 elanInstanceName, interfaceInfo.getPortName(), macAddress, dstDpId);
1097 return isFlowsRemovedInSrcDpn;
1100 private void deleteSmacAndDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1101 boolean deleteSmac, WriteTransaction deleteFlowGroupTx) {
1102 String elanInstanceName = elanInfo.getElanInstanceName();
1103 long ifTag = interfaceInfo.getInterfaceTag();
1104 BigInteger srcdpId = interfaceInfo.getDpId();
1105 Long elanTag = elanInfo.getElanTag();
1108 .removeFlowToTx(srcdpId,
1109 MDSALUtil.buildFlow(NwConstants.ELAN_SMAC_TABLE, getKnownDynamicmacFlowRef(
1110 NwConstants.ELAN_SMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)),
1113 mdsalManager.removeFlowToTx(srcdpId,
1114 MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE,
1115 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)),
1117 LOG.debug("All the required flows deleted for elan:{}, logical Interface port:{} and MAC address:{} on dpn:{}",
1118 elanInstanceName, interfaceInfo.getPortName(), macAddress, srcdpId);
1122 * Updates the Elan information in the Operational DS. It also updates the
1123 * ElanInstance in the Config DS by setting the adquired elanTag.
1127 * @param elanInstanceAdded
1128 * the elan instance added
1129 * @param elanInterfaces
1130 * the elan interfaces
1134 * @return the updated ELAN instance.
1136 public static ElanInstance updateOperationalDataStore(IdManagerService idManager,
1137 ElanInstance elanInstanceAdded, List<String> elanInterfaces, WriteTransaction tx) {
1138 String elanInstanceName = elanInstanceAdded.getElanInstanceName();
1139 Long elanTag = elanInstanceAdded.getElanTag();
1140 if (elanTag == null || elanTag == 0L) {
1141 elanTag = retrieveNewElanTag(idManager, elanInstanceName);
1143 Elan elanInfo = new ElanBuilder().setName(elanInstanceName).setElanInterfaces(elanInterfaces)
1144 .withKey(new ElanKey(elanInstanceName)).build();
1146 // Add the ElanState in the elan-state operational data-store
1147 tx.put(LogicalDatastoreType.OPERATIONAL, getElanInstanceOperationalDataPath(elanInstanceName),
1148 elanInfo, WriteTransaction.CREATE_MISSING_PARENTS);
1150 // Add the ElanMacTable in the elan-mac-table operational data-store
1151 MacTable elanMacTable = new MacTableBuilder().withKey(new MacTableKey(elanInstanceName)).build();
1152 tx.put(LogicalDatastoreType.OPERATIONAL, getElanMacTableOperationalDataPath(elanInstanceName),
1153 elanMacTable, WriteTransaction.CREATE_MISSING_PARENTS);
1155 ElanTagNameBuilder elanTagNameBuilder = new ElanTagNameBuilder().setElanTag(elanTag)
1156 .withKey(new ElanTagNameKey(elanTag)).setName(elanInstanceName);
1157 long etreeLeafTag = -1;
1158 if (isEtreeInstance(elanInstanceAdded)) {
1159 etreeLeafTag = retrieveNewElanTag(idManager,elanInstanceName + ElanConstants
1161 EtreeLeafTagName etreeLeafTagName = new EtreeLeafTagNameBuilder()
1162 .setEtreeLeafTag(new EtreeLeafTag(etreeLeafTag)).build();
1163 elanTagNameBuilder.addAugmentation(EtreeLeafTagName.class, etreeLeafTagName);
1164 addTheLeafTagAsElanTag(elanInstanceName, etreeLeafTag, tx);
1166 ElanTagName elanTagName = elanTagNameBuilder.build();
1168 // Add the ElanTag to ElanName in the elan-tag-name Operational
1170 tx.put(LogicalDatastoreType.OPERATIONAL,
1171 getElanInfoEntriesOperationalDataPath(elanTag), elanTagName);
1173 // Updates the ElanInstance Config DS by setting the just acquired
1175 ElanInstanceBuilder elanInstanceBuilder = new ElanInstanceBuilder().setElanInstanceName(elanInstanceName)
1176 .setDescription(elanInstanceAdded.getDescription())
1177 .setMacTimeout(elanInstanceAdded.getMacTimeout() == null
1178 ? Long.valueOf(ElanConstants.DEFAULT_MAC_TIME_OUT) : elanInstanceAdded.getMacTimeout())
1179 .withKey(elanInstanceAdded.key()).setElanTag(elanTag);
1180 if (isEtreeInstance(elanInstanceAdded)) {
1181 EtreeInstance etreeInstance = new EtreeInstanceBuilder().setEtreeLeafTagVal(new EtreeLeafTag(etreeLeafTag))
1183 elanInstanceBuilder.addAugmentation(EtreeInstance.class, etreeInstance);
1185 ElanInstance elanInstanceWithTag = elanInstanceBuilder.build();
1186 tx.merge(LogicalDatastoreType.CONFIGURATION, ElanHelper.getElanInstanceConfigurationDataPath(elanInstanceName),
1187 elanInstanceWithTag, WriteTransaction.CREATE_MISSING_PARENTS);
1188 return elanInstanceWithTag;
1191 private static void addTheLeafTagAsElanTag(String elanInstanceName, long etreeLeafTag, WriteTransaction tx) {
1192 ElanTagName etreeTagAsElanTag = new ElanTagNameBuilder().setElanTag(etreeLeafTag)
1193 .withKey(new ElanTagNameKey(etreeLeafTag)).setName(elanInstanceName).build();
1194 tx.put(LogicalDatastoreType.OPERATIONAL,
1195 getElanInfoEntriesOperationalDataPath(etreeLeafTag), etreeTagAsElanTag);
1198 private static boolean isEtreeInstance(ElanInstance elanInstanceAdded) {
1199 return elanInstanceAdded.augmentation(EtreeInstance.class) != null;
1202 public boolean isDpnPresent(BigInteger dpnId) {
1203 String dpn = String.format("%s:%s", "openflow", dpnId);
1204 NodeId nodeId = new NodeId(dpn);
1206 InstanceIdentifier<Node> node = InstanceIdentifier.builder(Nodes.class).child(Node.class, new NodeKey(nodeId))
1208 return read(broker, LogicalDatastoreType.CONFIGURATION, node).isPresent();
1211 public static ServicesInfo getServiceInfo(String elanInstanceName, String interfaceName) {
1212 return InterfaceServiceUtil.buildServiceInfo(elanInstanceName + "." + interfaceName,
1213 ElanConstants.ELAN_SERVICE_PRIORITY);
1216 public static String getElanServiceName(String elanName, String interfaceName) {
1217 return "elan." + elanName + interfaceName;
1220 public static BoundServices getBoundServices(String serviceName, short servicePriority, int flowPriority,
1221 BigInteger cookie, List<Instruction> instructions) {
1222 StypeOpenflowBuilder augBuilder = new StypeOpenflowBuilder().setFlowCookie(cookie).setFlowPriority(flowPriority)
1223 .setInstruction(instructions);
1224 return new BoundServicesBuilder().withKey(new BoundServicesKey(servicePriority)).setServiceName(serviceName)
1225 .setServicePriority(servicePriority).setServiceType(ServiceTypeFlowBased.class)
1226 .addAugmentation(StypeOpenflow.class, augBuilder.build()).build();
1229 public static InstanceIdentifier<BoundServices> buildServiceId(String interfaceName, short serviceIndex) {
1230 return InstanceIdentifier.builder(ServiceBindings.class)
1231 .child(ServicesInfo.class, new ServicesInfoKey(interfaceName, ServiceModeIngress.class))
1232 .child(BoundServices.class, new BoundServicesKey(serviceIndex)).build();
1235 public static List<MatchInfo> getTunnelMatchesForServiceId(int elanTag) {
1236 List<MatchInfo> mkMatches = new ArrayList<>();
1237 // Matching metadata
1238 mkMatches.add(new MatchTunnelId(BigInteger.valueOf(elanTag)));
1243 public void removeTerminatingServiceAction(BigInteger destDpId, int serviceId) {
1244 RemoveTerminatingServiceActionsInput input = new RemoveTerminatingServiceActionsInputBuilder()
1245 .setDpnId(destDpId).setServiceId(serviceId).build();
1246 Future<RpcResult<RemoveTerminatingServiceActionsOutput>> futureObject =
1247 itmRpcService.removeTerminatingServiceActions(input);
1249 RpcResult<RemoveTerminatingServiceActionsOutput> result = futureObject.get();
1250 if (result.isSuccessful()) {
1251 LOG.debug("Successfully completed removeTerminatingServiceActions for ELAN with serviceId {} on "
1252 + "dpn {}", serviceId, destDpId);
1254 LOG.debug("Failure in removeTerminatingServiceAction RPC call for ELAN with serviceId {} on "
1255 + "dpn {}", serviceId, destDpId);
1257 } catch (InterruptedException | ExecutionException e) {
1258 LOG.error("Error in RPC call removeTerminatingServiceActions for ELAN with serviceId {} on "
1259 + "dpn {}", serviceId, destDpId, e);
1264 * Gets the external tunnel.
1266 * @param sourceDevice
1268 * @param destinationDevice
1269 * the destination device
1270 * @param datastoreType
1271 * the datastore type
1272 * @return the external tunnel
1274 public ExternalTunnel getExternalTunnel(String sourceDevice, String destinationDevice,
1275 LogicalDatastoreType datastoreType) {
1276 Class<? extends TunnelTypeBase> tunType = TunnelTypeVxlan.class;
1277 InstanceIdentifier<ExternalTunnel> iid = InstanceIdentifier.builder(ExternalTunnelList.class)
1278 .child(ExternalTunnel.class, new ExternalTunnelKey(destinationDevice, sourceDevice, tunType)).build();
1279 return read(broker, datastoreType, iid).orNull();
1283 * Gets the external tunnel.
1285 * @param interfaceName
1286 * the interface name
1287 * @param datastoreType
1288 * the datastore type
1289 * @return the external tunnel
1291 public ExternalTunnel getExternalTunnel(String interfaceName, LogicalDatastoreType datastoreType) {
1292 ExternalTunnel externalTunnel = null;
1293 List<ExternalTunnel> externalTunnels = getAllExternalTunnels(datastoreType);
1294 for (ExternalTunnel tunnel : externalTunnels) {
1295 if (StringUtils.equalsIgnoreCase(interfaceName, tunnel.getTunnelInterfaceName())) {
1296 externalTunnel = tunnel;
1300 return externalTunnel;
1304 * Gets the all external tunnels.
1306 * @param datastoreType
1307 * the data store type
1308 * @return the all external tunnels
1310 public List<ExternalTunnel> getAllExternalTunnels(LogicalDatastoreType datastoreType) {
1311 InstanceIdentifier<ExternalTunnelList> iid = InstanceIdentifier.builder(ExternalTunnelList.class).build();
1312 return read(broker, datastoreType, iid).toJavaUtil().map(ExternalTunnelList::getExternalTunnel).orElse(
1313 Collections.emptyList());
1316 public static List<MatchInfo> buildMatchesForElanTagShFlagAndDstMac(long elanTag, boolean shFlag, String macAddr) {
1317 List<MatchInfo> mkMatches = new ArrayList<>();
1319 new MatchMetadata(getElanMetadataLabel(elanTag, shFlag), MetaDataUtil.METADATA_MASK_SERVICE_SH_FLAG));
1320 mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddr)));
1325 * Checks if is interface operational.
1327 * @param interfaceName
1328 * the interface name
1331 * @return true, if is interface operational
1333 public static boolean isInterfaceOperational(String interfaceName, DataBroker dataBroker) {
1334 if (StringUtils.isBlank(interfaceName)) {
1337 Interface ifState = getInterfaceStateFromOperDS(interfaceName, dataBroker);
1338 if (ifState == null) {
1341 return ifState.getOperStatus() == OperStatus.Up && ifState.getAdminStatus() == AdminStatus.Up;
1345 * Gets the interface state from operational ds.
1347 * @param interfaceName
1348 * the interface name
1351 * @return the interface state from oper ds
1353 public static org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1354 .ietf.interfaces.rev140508.interfaces.state.Interface getInterfaceStateFromOperDS(
1355 String interfaceName, DataBroker dataBroker) {
1356 InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1357 .ietf.interfaces.rev140508.interfaces.state.Interface> ifStateId = createInterfaceStateInstanceIdentifier(
1359 return MDSALUtil.read(dataBroker, LogicalDatastoreType.OPERATIONAL, ifStateId).orNull();
1363 * Creates the interface state instance identifier.
1365 * @param interfaceName
1366 * the interface name
1367 * @return the instance identifier
1369 public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1370 .ietf.interfaces.rev140508.interfaces.state.Interface> createInterfaceStateInstanceIdentifier(
1371 String interfaceName) {
1372 InstanceIdentifierBuilder<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1373 .ietf.interfaces.rev140508.interfaces.state.Interface> idBuilder = InstanceIdentifier
1374 .builder(InterfacesState.class)
1375 .child(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1376 .ietf.interfaces.rev140508.interfaces.state.Interface.class,
1377 new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1378 .ietf.interfaces.rev140508.interfaces.state.InterfaceKey(
1380 return idBuilder.build();
1383 public static CheckedFuture<Void, TransactionCommitFailedException> waitForTransactionToComplete(
1384 WriteTransaction tx) {
1385 CheckedFuture<Void, TransactionCommitFailedException> futures = tx.submit();
1388 } catch (InterruptedException | ExecutionException e) {
1389 // NETVIRT-1215: Do not log.error() here, only debug()
1390 LOG.debug("Error writing to datastore", e);
1395 public static boolean isVxlan(@Nullable ElanInstance elanInstance) {
1396 return elanInstance != null && elanInstance.getSegmentType() != null
1397 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1398 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId() != 0;
1401 private static boolean isVxlanSegment(ElanInstance elanInstance) {
1402 if (elanInstance != null) {
1403 List<ElanSegments> elanSegments = elanInstance.getElanSegments();
1404 if (elanSegments != null) {
1405 for (ElanSegments segment : elanSegments) {
1406 if (segment != null && segment.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1407 && segment.getSegmentationId() != null
1408 && segment.getSegmentationId().longValue() != 0) {
1417 public static boolean isVxlanNetworkOrVxlanSegment(ElanInstance elanInstance) {
1418 return isVxlan(elanInstance) || isVxlanSegment(elanInstance);
1421 public static Long getVxlanSegmentationId(ElanInstance elanInstance) {
1422 Long segmentationId = 0L;
1423 if (elanInstance == null) {
1424 return segmentationId;
1427 if (elanInstance.getSegmentType() != null
1428 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1429 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId().longValue() != 0) {
1430 segmentationId = elanInstance.getSegmentationId();
1432 for (ElanSegments segment: elanInstance.getElanSegments()) {
1433 if (segment != null && segment.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1434 && segment.getSegmentationId() != null
1435 && segment.getSegmentationId().longValue() != 0) {
1436 segmentationId = segment.getSegmentationId();
1440 return segmentationId;
1443 public static boolean isVlan(ElanInstance elanInstance) {
1444 return elanInstance != null && elanInstance.getSegmentType() != null
1445 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVlan.class)
1446 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId() != 0;
1449 public static boolean isFlat(ElanInstance elanInstance) {
1450 return elanInstance != null && elanInstance.getSegmentType() != null
1451 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeFlat.class);
1454 public void addDmacRedirectToDispatcherFlows(Long elanTag, String displayName,
1455 String macAddress, List<BigInteger> dpnIds) {
1456 for (BigInteger dpId : dpnIds) {
1457 ListenableFutures.addErrorLogging(txRunner.callWithNewWriteOnlyTransactionAndSubmit(
1458 tx -> mdsalManager.addFlowToTx(
1459 buildDmacRedirectToDispatcherFlow(dpId, macAddress, displayName, elanTag), tx)), LOG,
1460 "Error adding DMAC redirect to dispatcher flows");
1464 public void removeDmacRedirectToDispatcherFlows(Long elanTag, String macAddress, List<BigInteger> dpnIds) {
1465 for (BigInteger dpId : dpnIds) {
1466 String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, macAddress, elanTag);
1467 mdsalManager.removeFlow(dpId, MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, flowId));
1471 public static FlowEntity buildDmacRedirectToDispatcherFlow(BigInteger dpId, String dstMacAddress,
1472 String displayName, long elanTag) {
1473 List<MatchInfo> matches = new ArrayList<>();
1474 matches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
1475 matches.add(new MatchEthernetDestination(new MacAddress(dstMacAddress)));
1476 List<InstructionInfo> instructions = new ArrayList<>();
1477 List<ActionInfo> actions = new ArrayList<>();
1478 actions.add(new ActionNxResubmit(NwConstants.LPORT_DISPATCHER_TABLE));
1480 instructions.add(new InstructionApplyActions(actions));
1481 String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, dstMacAddress, elanTag);
1482 return MDSALUtil.buildFlowEntity(dpId, NwConstants.ELAN_DMAC_TABLE, flowId, 20, displayName, 0, 0,
1483 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)),
1484 matches, instructions);
1487 public String getExternalElanInterface(String elanInstanceName, BigInteger dpnId) {
1488 DpnInterfaces dpnInterfaces = getElanInterfaceInfoByElanDpn(elanInstanceName, dpnId);
1489 if (dpnInterfaces == null || dpnInterfaces.getInterfaces() == null) {
1490 LOG.trace("Elan {} does not have interfaces in DPN {}", elanInstanceName, dpnId);
1494 for (String dpnInterface : dpnInterfaces.getInterfaces()) {
1495 if (interfaceManager.isExternalInterface(dpnInterface)) {
1496 return dpnInterface;
1500 LOG.trace("Elan {} does not have any external interace attached to DPN {}", elanInstanceName, dpnId);
1504 public static String getElanMacDPNKey(long elanTag, String macAddress, BigInteger dpnId) {
1505 String elanMacDmacDpnKey = "MAC-" + macAddress + " ELAN_TAG-" + elanTag + "DPN_ID-" + dpnId;
1506 return elanMacDmacDpnKey.intern();
1509 public static String getElanMacKey(long elanTag, String macAddress) {
1510 String elanMacKey = "MAC-" + macAddress + " ELAN_TAG-" + elanTag;
1511 return elanMacKey.intern();
1514 public static List<ListenableFuture<Void>>
1515 returnFailedListenableFutureIfTransactionCommitFailedExceptionCauseOrElseThrow(RuntimeException exception) {
1517 Throwable cause = exception.getCause();
1518 if (cause != null && cause instanceof TransactionCommitFailedException) {
1519 return Collections.singletonList(Futures.immediateFailedFuture(cause));
1525 public static List<PhysAddress> getPhysAddress(List<String> macAddress) {
1526 Preconditions.checkNotNull(macAddress, "macAddress cannot be null");
1527 List<PhysAddress> physAddresses = new ArrayList<>();
1528 for (String mac : macAddress) {
1529 physAddresses.add(new PhysAddress(mac));
1531 return physAddresses;
1534 public static List<StaticMacEntries> getStaticMacEntries(List<String> staticMacAddresses) {
1535 if (isEmpty(staticMacAddresses)) {
1536 return Collections.EMPTY_LIST;
1538 StaticMacEntriesBuilder staticMacEntriesBuilder = new StaticMacEntriesBuilder();
1539 List<StaticMacEntries> staticMacEntries = new ArrayList<>();
1540 List<PhysAddress> physAddressList = getPhysAddress(staticMacAddresses);
1541 for (PhysAddress physAddress : physAddressList) {
1542 staticMacEntries.add(staticMacEntriesBuilder.setMacAddress(physAddress).build());
1544 return staticMacEntries;
1547 public static InstanceIdentifier<StaticMacEntries> getStaticMacEntriesCfgDataPathIdentifier(String interfaceName,
1548 String macAddress) {
1549 return InstanceIdentifier.builder(ElanInterfaces.class)
1550 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).child(StaticMacEntries.class,
1551 new StaticMacEntriesKey(new PhysAddress(macAddress))).build();
1554 public static List<StaticMacEntries> getDeletedEntries(List<StaticMacEntries> originalStaticMacEntries,
1555 List<StaticMacEntries> updatedStaticMacEntries) {
1556 if (isEmpty(originalStaticMacEntries)) {
1557 return Collections.EMPTY_LIST;
1559 List<StaticMacEntries> deleted = Lists.newArrayList(originalStaticMacEntries);
1560 if (isNotEmpty(updatedStaticMacEntries)) {
1561 deleted.removeAll(updatedStaticMacEntries);
1566 public static <T> List<T> diffOf(List<T> orig, List<T> updated) {
1567 if (isEmpty(orig)) {
1568 return Collections.EMPTY_LIST;
1570 List<T> diff = Lists.newArrayList(orig);
1571 if (isNotEmpty(updated)) {
1572 diff.removeAll(updated);
1577 public static void segregateToBeDeletedAndAddEntries(List<StaticMacEntries> originalStaticMacEntries,
1578 List<StaticMacEntries> updatedStaticMacEntries) {
1579 if (isNotEmpty(updatedStaticMacEntries)) {
1580 List<StaticMacEntries> existingClonedStaticMacEntries = new ArrayList<>();
1581 if (isNotEmpty(originalStaticMacEntries)) {
1582 existingClonedStaticMacEntries.addAll(0, originalStaticMacEntries);
1583 originalStaticMacEntries.removeAll(updatedStaticMacEntries);
1584 updatedStaticMacEntries.removeAll(existingClonedStaticMacEntries);
1589 public static boolean isEmpty(Collection collection) {
1590 return collection == null || collection.isEmpty();
1593 public static boolean isNotEmpty(Collection collection) {
1594 return !isEmpty(collection);
1597 public Optional<IpAddress> getSourceIpAddress(Ethernet ethernet) {
1598 Optional<IpAddress> srcIpAddress = Optional.absent();
1599 if (ethernet.getPayload() == null) {
1600 return srcIpAddress;
1602 byte[] ipAddrBytes = null;
1603 if (ethernet.getPayload() instanceof IPv4) {
1604 IPv4 ipv4 = (IPv4) ethernet.getPayload();
1605 ipAddrBytes = Ints.toByteArray(ipv4.getSourceAddress());
1606 } else if (ethernet.getPayload() instanceof ARP) {
1607 ipAddrBytes = ((ARP) ethernet.getPayload()).getSenderProtocolAddress();
1609 if (ipAddrBytes != null) {
1610 String ipAddr = NWUtil.toStringIpAddress(ipAddrBytes);
1611 return Optional.of(IpAddressBuilder.getDefaultInstance(ipAddr));
1613 return srcIpAddress;
1616 public List<MacEntry> getElanMacEntries(String elanName) {
1617 MacTable macTable = getElanMacTable(elanName);
1618 if (macTable == null) {
1619 return Collections.emptyList();
1621 return macTable.getMacEntry();
1624 public boolean isTunnelInLogicalGroup(String interfaceName) {
1625 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1626 .ietf.interfaces.rev140508.interfaces.Interface configIface =
1627 interfaceManager.getInterfaceInfoFromConfigDataStore(interfaceName);
1628 IfTunnel ifTunnel = configIface.augmentation(IfTunnel.class);
1629 if (ifTunnel != null && ifTunnel.getTunnelInterfaceType().isAssignableFrom(TunnelTypeVxlan.class)) {
1630 ParentRefs refs = configIface.augmentation(ParentRefs.class);
1631 if (refs != null && !Strings.isNullOrEmpty(refs.getParentInterface())) {
1632 return true; //multiple VxLAN tunnels enabled, i.e. only logical tunnel should be treated
1638 public static InstanceIdentifier<Flow> getFlowIid(Flow flow, BigInteger dpnId) {
1639 FlowKey flowKey = new FlowKey(new FlowId(flow.getId()));
1640 org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId nodeId =
1641 new org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId("openflow:" + dpnId);
1642 org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node nodeDpn =
1643 new NodeBuilder().setId(nodeId).withKey(new NodeKey(nodeId)).build();
1644 return InstanceIdentifier.builder(Nodes.class)
1645 .child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node.class,
1646 nodeDpn.key()).augmentation(FlowCapableNode.class)
1647 .child(Table.class, new TableKey(flow.getTableId())).child(Flow.class, flowKey).build();
1650 public static String getElanInterfaceJobKey(String interfaceName) {
1651 return "elaninterface-" + interfaceName;
1654 public void removeArpResponderFlow(BigInteger dpnId, String ingressInterfaceName, String ipAddress,
1656 LOG.info("Removing the ARP responder flow on DPN {} of Interface {} with IP {}", dpnId, ingressInterfaceName,
1658 ArpResponderUtil.removeFlow(mdsalManager, dpnId, ArpResponderUtil.getFlowId(lportTag, ipAddress));
1661 public static String getRouterPordIdFromElanInstance(DataBroker dataBroker, String elanInstanceName) {
1662 Optional<Subnetmaps> subnetMapsData =
1663 read(dataBroker, LogicalDatastoreType.CONFIGURATION, buildSubnetMapsWildCardPath());
1664 if (subnetMapsData.isPresent()) {
1665 List<Subnetmap> subnetMapList = subnetMapsData.get().getSubnetmap();
1666 if (subnetMapList != null && !subnetMapList.isEmpty()) {
1667 for (Subnetmap subnet : subnetMapList) {
1668 if (subnet.getNetworkId().getValue().equals(elanInstanceName)) {
1669 if (subnet.getRouterInterfacePortId() != null) {
1670 return subnet.getRouterInterfacePortId().getValue();
1679 static InstanceIdentifier<Subnetmaps> buildSubnetMapsWildCardPath() {
1680 return InstanceIdentifier.create(Subnetmaps.class);