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 static org.opendaylight.genius.infra.Datastore.CONFIGURATION;
12 import com.google.common.base.Optional;
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Strings;
15 import com.google.common.collect.Lists;
16 import com.google.common.primitives.Ints;
17 import com.google.common.util.concurrent.CheckedFuture;
18 import com.google.common.util.concurrent.FutureCallback;
19 import com.google.common.util.concurrent.Futures;
20 import com.google.common.util.concurrent.ListenableFuture;
21 import com.google.common.util.concurrent.MoreExecutors;
23 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
24 import java.math.BigInteger;
25 import java.util.ArrayList;
26 import java.util.Collection;
27 import java.util.Collections;
28 import java.util.List;
29 import java.util.concurrent.ExecutionException;
30 import java.util.concurrent.Future;
32 import javax.annotation.CheckReturnValue;
33 import javax.annotation.Nonnull;
34 import javax.annotation.Nullable;
35 import javax.inject.Inject;
36 import javax.inject.Singleton;
38 import org.apache.commons.lang3.StringUtils;
39 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
40 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
41 import org.opendaylight.controller.md.sal.binding.api.ReadTransaction;
42 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
43 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
44 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
45 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
46 import org.opendaylight.genius.infra.Datastore.Configuration;
47 import org.opendaylight.genius.infra.ManagedNewTransactionRunner;
48 import org.opendaylight.genius.infra.ManagedNewTransactionRunnerImpl;
49 import org.opendaylight.genius.infra.TypedReadWriteTransaction;
50 import org.opendaylight.genius.interfacemanager.globals.InterfaceInfo;
51 import org.opendaylight.genius.interfacemanager.globals.InterfaceServiceUtil;
52 import org.opendaylight.genius.interfacemanager.interfaces.IInterfaceManager;
53 import org.opendaylight.genius.itm.api.IITMProvider;
54 import org.opendaylight.genius.itm.globals.ITMConstants;
55 import org.opendaylight.genius.mdsalutil.ActionInfo;
56 import org.opendaylight.genius.mdsalutil.FlowEntity;
57 import org.opendaylight.genius.mdsalutil.FlowEntityBuilder;
58 import org.opendaylight.genius.mdsalutil.InstructionInfo;
59 import org.opendaylight.genius.mdsalutil.MDSALUtil;
60 import org.opendaylight.genius.mdsalutil.MatchInfo;
61 import org.opendaylight.genius.mdsalutil.MetaDataUtil;
62 import org.opendaylight.genius.mdsalutil.NWUtil;
63 import org.opendaylight.genius.mdsalutil.NwConstants;
64 import org.opendaylight.genius.mdsalutil.actions.ActionNxResubmit;
65 import org.opendaylight.genius.mdsalutil.instructions.InstructionApplyActions;
66 import org.opendaylight.genius.mdsalutil.instructions.InstructionGotoTable;
67 import org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager;
68 import org.opendaylight.genius.mdsalutil.matches.MatchEthernetDestination;
69 import org.opendaylight.genius.mdsalutil.matches.MatchEthernetSource;
70 import org.opendaylight.genius.mdsalutil.matches.MatchMetadata;
71 import org.opendaylight.genius.mdsalutil.matches.MatchTunnelId;
72 import org.opendaylight.genius.mdsalutil.packet.ARP;
73 import org.opendaylight.genius.mdsalutil.packet.Ethernet;
74 import org.opendaylight.genius.mdsalutil.packet.IPv4;
75 import org.opendaylight.infrautils.utils.concurrent.JdkFutures;
76 import org.opendaylight.infrautils.utils.concurrent.ListenableFutures;
77 import org.opendaylight.netvirt.elan.ElanException;
78 import org.opendaylight.netvirt.elan.arp.responder.ArpResponderUtil;
79 import org.opendaylight.netvirt.elan.cache.ElanInterfaceCache;
80 import org.opendaylight.netvirt.elanmanager.api.ElanHelper;
81 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
82 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddressBuilder;
83 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfacesState;
84 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface;
85 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.AdminStatus;
86 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.OperStatus;
87 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
88 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.PhysAddress;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
96 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
97 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInput;
98 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInputBuilder;
99 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdOutput;
100 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdManagerService;
101 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInput;
102 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInputBuilder;
103 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406.IfIndexesInterfaceMap;
104 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._if.indexes._interface.map.IfIndexInterface;
105 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._if.indexes._interface.map.IfIndexInterfaceKey;
106 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfTunnel;
107 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.ParentRefs;
108 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeBase;
109 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeVxlan;
110 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceInput;
111 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceInputBuilder;
112 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceOutput;
113 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.OdlInterfaceRpcService;
114 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceBindings;
115 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceModeIngress;
116 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceTypeFlowBased;
117 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflow;
118 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflowBuilder;
119 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.ServicesInfo;
120 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.ServicesInfoKey;
121 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServices;
122 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesBuilder;
123 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesKey;
124 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.ExternalTunnelList;
125 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnel;
126 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnelKey;
127 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.ItmRpcService;
128 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsInput;
129 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsInputBuilder;
130 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsOutput;
131 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
132 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
133 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
134 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
135 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
136 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.config.rev150710.ElanConfig;
137 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInstance;
138 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInstanceBuilder;
139 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInterface;
140 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInterface.EtreeInterfaceType;
141 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTag;
142 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTagName;
143 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTagNameBuilder;
144 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanDpnInterfaces;
145 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanForwardingTables;
146 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInstances;
147 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaceForwardingEntries;
148 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaces;
149 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanState;
150 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanTagNameMap;
151 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeFlat;
152 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeVlan;
153 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeVxlan;
154 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan._interface.forwarding.entries.ElanInterfaceMac;
155 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan._interface.forwarding.entries.ElanInterfaceMacKey;
156 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesList;
157 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesListKey;
158 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfaces;
159 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfacesKey;
160 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTable;
161 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTableBuilder;
162 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTableKey;
163 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstance;
164 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstanceBuilder;
165 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.elan.instance.ElanSegments;
166 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterface;
167 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterfaceKey;
168 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntries;
169 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntriesBuilder;
170 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntriesKey;
171 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.Elan;
172 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.ElanBuilder;
173 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.ElanKey;
174 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagName;
175 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagNameBuilder;
176 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagNameKey;
177 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntry;
178 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntryKey;
179 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.Subnetmaps;
180 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.subnetmaps.Subnetmap;
181 import org.opendaylight.yangtools.yang.binding.DataObject;
182 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
183 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.InstanceIdentifierBuilder;
184 import org.opendaylight.yangtools.yang.common.RpcResult;
185 import org.slf4j.Logger;
186 import org.slf4j.LoggerFactory;
189 public class ElanUtils {
191 private static final Logger LOG = LoggerFactory.getLogger(ElanUtils.class);
193 private final DataBroker broker;
194 private final ManagedNewTransactionRunner txRunner;
195 private final IMdsalApiManager mdsalManager;
196 private final OdlInterfaceRpcService interfaceManagerRpcService;
197 private final ItmRpcService itmRpcService;
198 private final IInterfaceManager interfaceManager;
199 private final ElanConfig elanConfig;
200 private final ElanItmUtils elanItmUtils;
201 private final ElanEtreeUtils elanEtreeUtils;
202 private final ElanInterfaceCache elanInterfaceCache;
203 private final IITMProvider iitmProvider;
205 public static final FutureCallback<Void> DEFAULT_CALLBACK = new FutureCallback<Void>() {
207 public void onSuccess(Void result) {
208 LOG.debug("Success in Datastore operation");
212 public void onFailure(Throwable error) {
213 LOG.error("Error in Datastore operation", error);
218 public ElanUtils(DataBroker dataBroker, IMdsalApiManager mdsalManager,
219 OdlInterfaceRpcService interfaceManagerRpcService, ItmRpcService itmRpcService, ElanConfig elanConfig,
220 IInterfaceManager interfaceManager, ElanEtreeUtils elanEtreeUtils, ElanItmUtils elanItmUtils,
221 ElanInterfaceCache elanInterfaceCache, IITMProvider iitmProvider) {
222 this.broker = dataBroker;
223 this.txRunner = new ManagedNewTransactionRunnerImpl(dataBroker);
224 this.mdsalManager = mdsalManager;
225 this.interfaceManagerRpcService = interfaceManagerRpcService;
226 this.itmRpcService = itmRpcService;
227 this.interfaceManager = interfaceManager;
228 this.elanConfig = elanConfig;
229 this.elanEtreeUtils = elanEtreeUtils;
230 this.elanItmUtils = elanItmUtils;
231 this.elanInterfaceCache = elanInterfaceCache;
232 this.iitmProvider = iitmProvider;
235 public final Boolean isOpenstackVniSemanticsEnforced() {
236 return elanConfig.isOpenstackVniSemanticsEnforced() != null
237 ? elanConfig.isOpenstackVniSemanticsEnforced() : false;
241 * Uses the IdManager to retrieve a brand new ElanTag.
247 * @return the integer
249 public static Long retrieveNewElanTag(IdManagerService idManager, String idKey) {
251 AllocateIdInput getIdInput = new AllocateIdInputBuilder().setPoolName(ElanConstants.ELAN_ID_POOL_NAME)
252 .setIdKey(idKey).build();
255 Future<RpcResult<AllocateIdOutput>> result = idManager.allocateId(getIdInput);
256 RpcResult<AllocateIdOutput> rpcResult = result.get();
257 if (rpcResult.isSuccessful()) {
258 return rpcResult.getResult().getIdValue();
260 LOG.warn("RPC Call to Allocate Id returned with Errors {}", rpcResult.getErrors());
262 } catch (InterruptedException | ExecutionException e) {
263 LOG.warn("Exception when Allocating Id", e);
268 public static void releaseId(IdManagerService idManager, String poolName, String idKey) {
269 ReleaseIdInput releaseIdInput = new ReleaseIdInputBuilder().setPoolName(poolName).setIdKey(idKey).build();
270 JdkFutures.addErrorLogging(idManager.releaseId(releaseIdInput), LOG, "Release Id");
276 * @deprecated Consider using {@link #read2(LogicalDatastoreType, InstanceIdentifier)} with proper exception
278 * @param broker dataBroker
279 * @param datastoreType Logical DataStore type
280 * @param path IID to read
281 * @param <T> T extends DataObject
282 * @return the read value T
285 @SuppressWarnings("checkstyle:IllegalCatch")
286 public static <T extends DataObject> Optional<T> read(@Nonnull DataBroker broker,
287 LogicalDatastoreType datastoreType, InstanceIdentifier<T> path) {
288 try (ReadOnlyTransaction tx = broker.newReadOnlyTransaction()) {
289 return tx.read(datastoreType, path).get();
290 } catch (Exception e) {
291 throw new RuntimeException(e);
295 public <T extends DataObject> Optional<T> read2(LogicalDatastoreType datastoreType, InstanceIdentifier<T> path)
296 throws ReadFailedException {
297 try (ReadOnlyTransaction tx = broker.newReadOnlyTransaction()) {
298 CheckedFuture<Optional<T>, ReadFailedException> checkedFuture = tx.read(datastoreType, path);
299 return checkedFuture.checkedGet();
303 @SuppressWarnings("checkstyle:ForbidCertainMethod")
304 public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
305 InstanceIdentifier<T> path) {
306 WriteTransaction tx = broker.newWriteOnlyTransaction();
307 tx.delete(datastoreType, path);
308 Futures.addCallback(tx.submit(), DEFAULT_CALLBACK, MoreExecutors.directExecutor());
311 @SuppressWarnings("checkstyle:ForbidCertainMethod")
312 public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
313 InstanceIdentifier<T> path, FutureCallback<Void> callback) {
314 WriteTransaction tx = broker.newWriteOnlyTransaction();
315 tx.delete(datastoreType, path);
316 Futures.addCallback(tx.submit(), callback, MoreExecutors.directExecutor());
319 public static InstanceIdentifier<ElanInstance> getElanInstanceIdentifier() {
320 return InstanceIdentifier.builder(ElanInstances.class).child(ElanInstance.class).build();
323 public static InstanceIdentifier<ElanInterface> getElanInterfaceConfigurationDataPathId(String interfaceName) {
324 return InstanceIdentifier.builder(ElanInterfaces.class)
325 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).build();
328 // elan-state Operational container
329 public static Elan getElanByName(DataBroker broker, String elanInstanceName) {
330 InstanceIdentifier<Elan> elanIdentifier = getElanInstanceOperationalDataPath(elanInstanceName);
331 return MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL, elanIdentifier).orNull();
335 public static Elan getElanByName(ReadTransaction tx, String elanInstanceName) throws ReadFailedException {
336 return tx.read(LogicalDatastoreType.OPERATIONAL,
337 getElanInstanceOperationalDataPath(elanInstanceName)).checkedGet().orNull();
340 public static InstanceIdentifier<Elan> getElanInstanceOperationalDataPath(String elanInstanceName) {
341 return InstanceIdentifier.builder(ElanState.class).child(Elan.class, new ElanKey(elanInstanceName)).build();
344 // grouping of forwarding-entries
345 public MacEntry getInterfaceMacEntriesOperationalDataPath(String interfaceName, PhysAddress physAddress) {
346 InstanceIdentifier<MacEntry> existingMacEntryId = getInterfaceMacEntriesIdentifierOperationalDataPath(
347 interfaceName, physAddress);
348 return read(broker, LogicalDatastoreType.OPERATIONAL, existingMacEntryId).orNull();
351 public MacEntry getInterfaceMacEntriesOperationalDataPathFromId(InstanceIdentifier identifier) {
352 Optional<MacEntry> existingInterfaceMacEntry = read(broker,
353 LogicalDatastoreType.OPERATIONAL, identifier);
354 return existingInterfaceMacEntry.orNull();
357 public static InstanceIdentifier<MacEntry> getInterfaceMacEntriesIdentifierOperationalDataPath(String interfaceName,
358 PhysAddress physAddress) {
359 return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class)
360 .child(ElanInterfaceMac.class, new ElanInterfaceMacKey(interfaceName))
361 .child(MacEntry.class, new MacEntryKey(physAddress)).build();
365 // elan-forwarding-tables Operational container
366 public Optional<MacEntry> getMacEntryForElanInstance(String elanName, PhysAddress physAddress) {
367 InstanceIdentifier<MacEntry> macId = getMacEntryOperationalDataPath(elanName, physAddress);
368 return read(broker, LogicalDatastoreType.OPERATIONAL, macId);
371 public Optional<MacEntry> getMacEntryForElanInstance(ReadTransaction tx, String elanName, PhysAddress physAddress)
372 throws ReadFailedException {
373 InstanceIdentifier<MacEntry> macId = getMacEntryOperationalDataPath(elanName, physAddress);
374 return tx.read(LogicalDatastoreType.OPERATIONAL, macId).checkedGet();
377 public MacEntry getMacEntryFromElanMacId(InstanceIdentifier identifier) {
378 Optional<MacEntry> existingInterfaceMacEntry = read(broker,
379 LogicalDatastoreType.OPERATIONAL, identifier);
380 return existingInterfaceMacEntry.orNull();
383 public static InstanceIdentifier<MacEntry> getMacEntryOperationalDataPath(String elanName,
384 PhysAddress physAddress) {
385 return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class, new MacTableKey(elanName))
386 .child(MacEntry.class, new MacEntryKey(physAddress)).build();
389 public static InstanceIdentifier<MacTable> getElanMacTableOperationalDataPath(String elanName) {
390 return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class, new MacTableKey(elanName))
394 // elan-interface-forwarding-entries Operational container
395 public ElanInterfaceMac getElanInterfaceMacByInterfaceName(String interfaceName) {
396 return getElanInterfaceMacByInterfaceName(broker, interfaceName);
400 public static ElanInterfaceMac getElanInterfaceMacByInterfaceName(DataBroker dataBroker, String interfaceName) {
401 InstanceIdentifier<ElanInterfaceMac> elanInterfaceId = getElanInterfaceMacEntriesOperationalDataPath(
403 return read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanInterfaceId).orNull();
407 * Gets the elan interface mac addresses.
409 * @param interfaceName
411 * @return the elan interface mac addresses
413 public List<PhysAddress> getElanInterfaceMacAddresses(String interfaceName) {
414 List<PhysAddress> macAddresses = new ArrayList<>();
415 ElanInterfaceMac elanInterfaceMac = getElanInterfaceMacByInterfaceName(interfaceName);
416 if (elanInterfaceMac != null && elanInterfaceMac.getMacEntry() != null) {
417 List<MacEntry> macEntries = elanInterfaceMac.getMacEntry();
418 for (MacEntry macEntry : macEntries) {
419 macAddresses.add(macEntry.getMacAddress());
425 public static InstanceIdentifier<ElanInterfaceMac> getElanInterfaceMacEntriesOperationalDataPath(
426 String interfaceName) {
427 return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class)
428 .child(ElanInterfaceMac.class, new ElanInterfaceMacKey(interfaceName)).build();
432 * Returns the list of Interfaces that belong to an Elan on an specific DPN.
433 * Data retrieved from Elan's operational DS: elan-dpn-interfaces container
435 * @param elanInstanceName
436 * name of the Elan to which the interfaces must belong to
438 * Id of the DPN where the interfaces are located
439 * @return the elan interface Info
441 public DpnInterfaces getElanInterfaceInfoByElanDpn(String elanInstanceName, BigInteger dpId) {
442 InstanceIdentifier<DpnInterfaces> elanDpnInterfacesId = getElanDpnInterfaceOperationalDataPath(elanInstanceName,
444 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfacesId).orNull();
448 * Returns the InstanceIdentifier that points to the Interfaces of an Elan
449 * in a given DPN in the Operational DS. Data retrieved from Elans's
450 * operational DS: dpn-interfaces list
452 * @param elanInstanceName
453 * name of the Elan to which the interfaces must belong to
455 * Id of the DPN where the interfaces are located
456 * @return the elan dpn interface
458 public static InstanceIdentifier<DpnInterfaces> getElanDpnInterfaceOperationalDataPath(String elanInstanceName,
460 return InstanceIdentifier.builder(ElanDpnInterfaces.class)
461 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName))
462 .child(DpnInterfaces.class, new DpnInterfacesKey(dpId)).build();
465 // elan-tag-name-map Operational Container
466 public ElanTagName getElanInfoByElanTag(long elanTag) {
467 InstanceIdentifier<ElanTagName> elanId = getElanInfoEntriesOperationalDataPath(elanTag);
468 Optional<ElanTagName> existingElanInfo = read(broker,
469 LogicalDatastoreType.OPERATIONAL, elanId);
470 return existingElanInfo.orNull();
473 public static InstanceIdentifier<ElanTagName> getElanInfoEntriesOperationalDataPath(long elanTag) {
474 return InstanceIdentifier.builder(ElanTagNameMap.class).child(ElanTagName.class, new ElanTagNameKey(elanTag))
478 // interface-index-tag operational container
479 public Optional<IfIndexInterface> getInterfaceInfoByInterfaceTag(long interfaceTag) {
480 InstanceIdentifier<IfIndexInterface> interfaceId = getInterfaceInfoEntriesOperationalDataPath(interfaceTag);
481 return read(broker, LogicalDatastoreType.OPERATIONAL, interfaceId);
484 public static InstanceIdentifier<IfIndexInterface> getInterfaceInfoEntriesOperationalDataPath(long interfaceTag) {
485 return InstanceIdentifier.builder(IfIndexesInterfaceMap.class)
486 .child(IfIndexInterface.class, new IfIndexInterfaceKey((int) interfaceTag)).build();
489 public static InstanceIdentifier<ElanDpnInterfacesList> getElanDpnOperationDataPath(String elanInstanceName) {
490 return InstanceIdentifier.builder(ElanDpnInterfaces.class)
491 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName)).build();
494 public ElanDpnInterfacesList getElanDpnInterfacesList(String elanName) {
495 InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanName);
496 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orNull();
499 public ElanDpnInterfaces getElanDpnInterfacesList() {
500 InstanceIdentifier<ElanDpnInterfaces> elanDpnInterfaceId = InstanceIdentifier.builder(ElanDpnInterfaces.class)
502 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orNull();
506 * This method is useful get all ELAN participating CSS dpIds to install
507 * program remote dmac entries and updating remote bc groups for tor
510 * @param elanInstanceName
511 * the elan instance name
512 * @return list of dpIds
515 public List<BigInteger> getParticipatingDpnsInElanInstance(String elanInstanceName) {
516 List<BigInteger> dpIds = new ArrayList<>();
517 InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
518 Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = read(broker,
519 LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
520 if (!existingElanDpnInterfaces.isPresent()) {
523 List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().getDpnInterfaces();
524 for (DpnInterfaces dpnInterface : dpnInterfaces) {
525 dpIds.add(dpnInterface.getDpId());
531 * To check given dpId is already present in Elan instance. This can be used
532 * to program flow entry in external tunnel table when a new access port
533 * added for first time into the ELAN instance
537 * @param elanInstanceName
538 * the elan instance name
539 * @return true if dpId is already present, otherwise return false
541 public boolean isDpnAlreadyPresentInElanInstance(BigInteger dpId, String elanInstanceName) {
542 InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
543 Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = read(broker,
544 LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
545 if (!existingElanDpnInterfaces.isPresent()) {
548 List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().getDpnInterfaces();
549 for (DpnInterfaces dpnInterface : dpnInterfaces) {
550 if (dpnInterface.getDpId().equals(dpId)) {
557 public ElanForwardingTables getElanForwardingList() {
558 InstanceIdentifier<ElanForwardingTables> elanForwardingTableId = InstanceIdentifier
559 .builder(ElanForwardingTables.class).build();
560 return read(broker, LogicalDatastoreType.OPERATIONAL, elanForwardingTableId).orNull();
563 public static long getElanRemoteBroadCastGroupID(long elanTag) {
564 return ElanConstants.ELAN_GID_MIN + elanTag % ElanConstants.ELAN_GID_MIN * 2;
568 * Gets the elan mac table.
572 * @return the elan mac table
574 public MacTable getElanMacTable(String elanName) {
575 return getElanMacTable(broker, elanName);
579 public static MacTable getElanMacTable(DataBroker dataBroker, String elanName) {
580 InstanceIdentifier<MacTable> elanMacTableId = getElanMacTableOperationalDataPath(elanName);
581 return read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanMacTableId).orNull();
584 public static long getElanLocalBCGId(long elanTag) {
585 return ElanConstants.ELAN_GID_MIN + (elanTag % ElanConstants.ELAN_GID_MIN * 2 - 1);
588 public static long getElanRemoteBCGId(long elanTag) {
589 return ElanConstants.ELAN_GID_MIN + elanTag % ElanConstants.ELAN_GID_MIN * 2;
592 public static long getEtreeLeafLocalBCGId(long etreeLeafTag) {
593 return ElanConstants.ELAN_GID_MIN + (etreeLeafTag % ElanConstants.ELAN_GID_MIN * 2 - 1);
596 public static long getEtreeLeafRemoteBCGId(long etreeLeafTag) {
597 return ElanConstants.ELAN_GID_MIN + etreeLeafTag % ElanConstants.ELAN_GID_MIN * 2;
600 public static BigInteger getElanMetadataLabel(long elanTag, boolean isSHFlagSet) {
601 int shBit = isSHFlagSet ? 1 : 0;
602 return BigInteger.valueOf(elanTag).shiftLeft(24).or(BigInteger.valueOf(shBit));
606 * Setting SMAC, DMAC, UDMAC in this DPN and optionally in other DPNs.
610 * @param interfaceInfo
616 * @param configureRemoteFlows
617 * true if remote dmac flows should be configured as well
618 * @param writeFlowGroupTx
620 * @throws ElanException in case of issues creating the flow objects
622 public void setupMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo,
623 long macTimeout, String macAddress, boolean configureRemoteFlows,
624 WriteTransaction writeFlowGroupTx) throws ElanException {
625 synchronized (getElanMacDPNKey(elanInfo.getElanTag(), macAddress, interfaceInfo.getDpId())) {
626 setupKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress, mdsalManager,
628 setupOrigDmacFlows(elanInfo, interfaceInfo, macAddress, configureRemoteFlows, mdsalManager,
633 public void setupDMacFlowOnRemoteDpn(ElanInstance elanInfo, InterfaceInfo interfaceInfo, BigInteger dstDpId,
634 String macAddress, WriteTransaction writeFlowTx) throws ElanException {
635 String elanInstanceName = elanInfo.getElanInstanceName();
636 setupRemoteDmacFlow(dstDpId, interfaceInfo.getDpId(), interfaceInfo.getInterfaceTag(), elanInfo.getElanTag(),
637 macAddress, elanInstanceName, writeFlowTx, interfaceInfo.getInterfaceName(), elanInfo);
638 LOG.info("Remote Dmac flow entry created for elan Name:{}, logical port Name:{} and"
639 + " mac address {} on dpn:{}", elanInstanceName, interfaceInfo.getPortName(),
640 macAddress, dstDpId);
644 * Inserts a Flow in SMAC table to state that the MAC has already been
647 private void setupKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
648 String macAddress, IMdsalApiManager mdsalApiManager, WriteTransaction writeFlowGroupTx) {
649 FlowEntity flowEntity = buildKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress);
650 mdsalApiManager.addFlowToTx(flowEntity, writeFlowGroupTx);
651 LOG.debug("Known Smac flow entry created for elan Name:{}, logical Interface port:{} and mac address:{}",
652 elanInfo.getElanInstanceName(), elanInfo.getDescription(), macAddress);
655 public FlowEntity buildKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
657 int lportTag = interfaceInfo.getInterfaceTag();
658 // Matching metadata and eth_src fields
659 List<MatchInfo> mkMatches = new ArrayList<>();
660 mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanInfo.getElanTag(), lportTag),
661 ElanHelper.getElanMetadataMask()));
662 mkMatches.add(new MatchEthernetSource(new MacAddress(macAddress)));
663 List<InstructionInfo> mkInstructions = new ArrayList<>();
664 mkInstructions.add(new InstructionGotoTable(NwConstants.ELAN_DMAC_TABLE));
665 BigInteger dpId = interfaceInfo.getDpId();
666 long elanTag = getElanTag(elanInfo, interfaceInfo);
667 return new FlowEntityBuilder()
669 .setTableId(NwConstants.ELAN_SMAC_TABLE)
670 .setFlowId(getKnownDynamicmacFlowRef(NwConstants.ELAN_SMAC_TABLE, dpId, lportTag, macAddress, elanTag))
672 .setFlowName(elanInfo.getDescription())
673 .setIdleTimeOut((int) macTimeout)
675 .setCookie(ElanConstants.COOKIE_ELAN_KNOWN_SMAC.add(BigInteger.valueOf(elanTag)))
676 .setMatchInfoList(mkMatches)
677 .setInstructionInfoList(mkInstructions)
679 // If Mac timeout is 0, the flow won't be deleted automatically, so no need to get notified
680 .setSendFlowRemFlag(macTimeout != 0)
684 private Long getElanTag(ElanInstance elanInfo, InterfaceInfo interfaceInfo) {
685 EtreeInterface etreeInterface = elanInterfaceCache.getEtreeInterface(interfaceInfo.getInterfaceName()).orNull();
686 if (etreeInterface == null || etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
687 return elanInfo.getElanTag();
689 EtreeInstance etreeInstance = elanInfo.augmentation(EtreeInstance.class);
690 if (etreeInstance == null) {
691 LOG.warn("EtreeInterface {} is connected to a non-Etree network: {}",
692 interfaceInfo.getInterfaceName(), elanInfo.getElanInstanceName());
693 return elanInfo.getElanTag();
695 return etreeInstance.getEtreeLeafTagVal().getValue();
701 * Installs a Flow in INTERNAL_TUNNEL_TABLE of the affected DPN that sends
702 * the packet through the specified interface if the tunnel_id matches the
703 * interface's lportTag.
705 * @param interfaceInfo
707 * @param mdsalApiManager
708 * the mdsal API manager
709 * @param writeFlowGroupTx
710 * the writeFLowGroup tx
712 public void setupTermDmacFlows(InterfaceInfo interfaceInfo, IMdsalApiManager mdsalApiManager,
713 WriteTransaction writeFlowGroupTx) {
714 BigInteger dpId = interfaceInfo.getDpId();
715 int lportTag = interfaceInfo.getInterfaceTag();
716 Flow flow = MDSALUtil.buildFlowNew(NwConstants.INTERNAL_TUNNEL_TABLE,
717 getIntTunnelTableFlowRef(NwConstants.INTERNAL_TUNNEL_TABLE, lportTag), 5,
718 String.format("%s:%d", "ITM Flow Entry ", lportTag), 0, 0,
719 ITMConstants.COOKIE_ITM.add(BigInteger.valueOf(lportTag)),
720 getTunnelIdMatchForFilterEqualsLPortTag(lportTag),
721 getInstructionsInPortForOutGroup(interfaceInfo.getInterfaceName()));
722 mdsalApiManager.addFlowToTx(dpId, flow, writeFlowGroupTx);
723 LOG.debug("Terminating service table flow entry created on dpn:{} for logical Interface port:{}", dpId,
724 interfaceInfo.getPortName());
728 * Constructs the FlowName for flows installed in the Internal Tunnel Table,
729 * consisting in tableId + elanTag.
735 * @return the Internal tunnel
737 public static String getIntTunnelTableFlowRef(short tableId, int elanTag) {
738 return new StringBuffer().append(tableId).append(elanTag).toString();
742 * Constructs the Matches that checks that the tunnel_id field contains a
746 * lportTag that must be checked against the tunnel_id field
747 * @return the list of match Info
749 public static List<MatchInfo> getTunnelIdMatchForFilterEqualsLPortTag(int lportTag) {
750 List<MatchInfo> mkMatches = new ArrayList<>();
752 mkMatches.add(new MatchTunnelId(BigInteger.valueOf(lportTag)));
757 * Constructs the Instructions that take the packet over a given interface.
760 * Name of the interface where the packet must be sent over. It
761 * can be a local interface or a tunnel interface (internal or
763 * @return the Instruction
765 public List<Instruction> getInstructionsInPortForOutGroup(String ifName) {
766 List<Instruction> mkInstructions = new ArrayList<>();
767 List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
769 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
770 return mkInstructions;
774 * Returns the list of Actions to be taken when sending the packet through
775 * an Elan interface. Note that this interface can refer to an ElanInterface
776 * where the Elan VM is attached to a DPN or an ITM tunnel interface where
777 * Elan traffic can be sent through. In this latter case, the tunnelKey is
778 * mandatory and it can hold serviceId for internal tunnels or the VNI for
785 * @return the egress actions for interface
787 @SuppressWarnings("checkstyle:IllegalCatch")
788 public List<Action> getEgressActionsForInterface(String ifName, Long tunnelKey) {
789 List<Action> listAction = new ArrayList<>();
791 GetEgressActionsForInterfaceInput getEgressActionInput = new GetEgressActionsForInterfaceInputBuilder()
792 .setIntfName(ifName).setTunnelKey(tunnelKey).build();
793 Future<RpcResult<GetEgressActionsForInterfaceOutput>> result = interfaceManagerRpcService
794 .getEgressActionsForInterface(getEgressActionInput);
795 RpcResult<GetEgressActionsForInterfaceOutput> rpcResult = result.get();
796 if (!rpcResult.isSuccessful()) {
797 LOG.debug("RPC Call to Get egress actions for interface {} returned with Errors {}", ifName,
798 rpcResult.getErrors());
800 List<Action> actions = rpcResult.getResult().getAction();
801 listAction = actions;
803 } catch (Exception e) {
804 LOG.warn("Exception when egress actions for interface {}", ifName, e);
809 private void setupOrigDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
810 boolean configureRemoteFlows, IMdsalApiManager mdsalApiManager,
811 WriteTransaction writeFlowGroupTx)
812 throws ElanException {
813 BigInteger dpId = interfaceInfo.getDpId();
814 String ifName = interfaceInfo.getInterfaceName();
815 long ifTag = interfaceInfo.getInterfaceTag();
816 String elanInstanceName = elanInfo.getElanInstanceName();
818 Long elanTag = elanInfo.getElanTag();
820 setupLocalDmacFlow(elanTag, dpId, ifName, macAddress, elanInfo, mdsalApiManager, ifTag,
822 LOG.debug("Dmac flow entry created for elan Name:{}, logical port Name:{} mand mac address:{} "
823 + "on dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, dpId);
825 if (!configureRemoteFlows) {
829 List<DpnInterfaces> elanDpns = getInvolvedDpnsInElan(elanInstanceName);
830 for (DpnInterfaces elanDpn : elanDpns) {
832 if (elanDpn.getDpId().equals(dpId)) {
836 // Check for the Remote DPN present in Inventory Manager
837 if (!isDpnPresent(elanDpn.getDpId())) {
841 // For remote DPNs a flow is needed to indicate that packets of this ELAN going to this MAC need to be
842 // forwarded through the appropriate ITM tunnel
843 setupRemoteDmacFlow(elanDpn.getDpId(), // srcDpn (the remote DPN in this case)
844 dpId, // dstDpn (the local DPN)
845 interfaceInfo.getInterfaceTag(), // lportTag of the local interface
846 elanTag, // identifier of the Elan
847 macAddress, // MAC to be programmed in remote DPN
848 elanInstanceName, writeFlowGroupTx, ifName, elanInfo
850 LOG.debug("Remote Dmac flow entry created for elan Name:{}, logical port Name:{} and mac address:{} on"
851 + " dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, elanDpn.getDpId());
854 // TODO: Make sure that the same is performed against the ElanDevices.
858 public List<DpnInterfaces> getInvolvedDpnsInElan(String elanName) {
859 return getElanDPNByName(elanName);
863 public List<DpnInterfaces> getElanDPNByName(String elanInstanceName) {
864 InstanceIdentifier<ElanDpnInterfacesList> elanIdentifier = getElanDpnOperationDataPath(elanInstanceName);
865 return MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL, elanIdentifier).toJavaUtil().map(
866 ElanDpnInterfacesList::getDpnInterfaces).orElse(Collections.emptyList());
869 private void setupLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
870 ElanInstance elanInfo, IMdsalApiManager mdsalApiManager, long ifTag, WriteTransaction writeFlowGroupTx) {
871 Flow flowEntity = buildLocalDmacFlowEntry(elanTag, dpId, ifName, macAddress, elanInfo, ifTag);
872 mdsalApiManager.addFlowToTx(dpId, flowEntity, writeFlowGroupTx);
873 installEtreeLocalDmacFlow(elanTag, dpId, ifName, macAddress, elanInfo,
874 ifTag, writeFlowGroupTx);
877 private void installEtreeLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
878 ElanInstance elanInfo, long ifTag, WriteTransaction writeFlowGroupTx) {
879 EtreeInterface etreeInterface = elanInterfaceCache.getEtreeInterface(ifName).orNull();
880 if (etreeInterface != null && etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
881 EtreeLeafTagName etreeTagName = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
882 if (etreeTagName == null) {
883 LOG.warn("Interface {} seems like it belongs to Etree but etreeTagName from elanTag {} is null",
886 Flow flowEntity = buildLocalDmacFlowEntry(etreeTagName.getEtreeLeafTag().getValue(), dpId, ifName,
887 macAddress, elanInfo, ifTag);
888 mdsalManager.addFlowToTx(dpId, flowEntity, writeFlowGroupTx);
893 public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, long lporTag, String macAddress,
895 return String.valueOf(tableId) + elanTag + dpId + lporTag + macAddress;
898 public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, BigInteger remoteDpId,
899 String macAddress, long elanTag) {
900 return String.valueOf(tableId) + elanTag + dpId + remoteDpId + macAddress;
903 public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, String macAddress, long elanTag) {
904 return String.valueOf(tableId) + elanTag + dpId + macAddress;
907 public static String getKnownDynamicmacFlowRef(short elanDmacTable, BigInteger dpId, String extDeviceNodeId,
908 String dstMacAddress, long elanTag, boolean shFlag) {
909 return String.valueOf(elanDmacTable) + elanTag + dpId + extDeviceNodeId + dstMacAddress + shFlag;
913 * Builds the flow to be programmed in the DMAC table of the local DPN (that
914 * is, where the MAC is attached to). This flow consists in:
916 * <p>Match: + elanTag in metadata + packet goes to a MAC locally attached
917 * Actions: + optionally, pop-vlan + set-vlan-id + output to ifName's
934 public Flow buildLocalDmacFlowEntry(long elanTag, BigInteger dpId, String ifName, String macAddress,
935 ElanInstance elanInfo, long ifTag) {
937 List<MatchInfo> mkMatches = new ArrayList<>();
938 mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
939 mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddress)));
941 List<Instruction> mkInstructions = new ArrayList<>();
942 List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
943 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
944 Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
945 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, ifTag, macAddress, elanTag), 20,
946 elanInfo.getElanInstanceName(), 0, 0, ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(
947 BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
952 public void setupRemoteDmacFlow(BigInteger srcDpId, BigInteger destDpId, int lportTag, long elanTag, String
953 macAddress, String displayName, WriteTransaction writeFlowGroupTx, String interfaceName, ElanInstance
954 elanInstance) throws ElanException {
955 if (interfaceManager.isExternalInterface(interfaceName)) {
956 LOG.debug("Ignoring install remote DMAC {} flow on provider interface {} elan {}",
957 macAddress, interfaceName, elanInstance.getElanInstanceName());
961 // if openstack-vni-semantics are enforced, segmentation ID is passed as network VNI for VxLAN based provider
962 // networks, 0 otherwise
963 long lportTagOrVni = !isOpenstackVniSemanticsEnforced() ? lportTag : isVxlanNetworkOrVxlanSegment(elanInstance)
964 ? getVxlanSegmentationId(elanInstance) : 0;
965 flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTagOrVni, elanTag, macAddress, displayName,
967 mdsalManager.addFlowToTx(srcDpId, flowEntity, writeFlowGroupTx);
968 setupEtreeRemoteDmacFlow(srcDpId, destDpId, lportTagOrVni, elanTag, macAddress, displayName, interfaceName,
969 writeFlowGroupTx, elanInstance);
972 private void setupEtreeRemoteDmacFlow(BigInteger srcDpId, BigInteger destDpId, long lportTagOrVni, long elanTag,
973 String macAddress, String displayName, String interfaceName,
974 WriteTransaction writeFlowGroupTx, ElanInstance elanInstance) {
976 EtreeInterface etreeInterface = elanInterfaceCache.getEtreeInterface(interfaceName).orNull();
977 if (etreeInterface != null && etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
978 EtreeLeafTagName etreeTagName = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
979 if (etreeTagName == null) {
980 LOG.warn("Interface {} seems like it belongs to Etree but etreeTagName from elanTag {} is null.",
981 interfaceName, elanTag);
983 flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTagOrVni,
984 etreeTagName.getEtreeLeafTag().getValue(), macAddress, displayName, elanInstance);
985 mdsalManager.addFlowToTx(srcDpId, flowEntity, writeFlowGroupTx);
991 * Builds a Flow to be programmed in a remote DPN's DMAC table. This flow
992 * consists in: Match: + elanTag in packet's metadata + packet going to a
993 * MAC known to be located in another DPN Actions: + set_tunnel_id
994 * + output ITM internal tunnel interface with the other DPN
1000 * @param lportTagOrVni
1001 * lportTag or network VNI
1006 * @param displayName
1008 * @param elanInstance
1010 * @return the flow remote Dmac
1012 @SuppressWarnings("checkstyle:IllegalCatch")
1013 public Flow buildRemoteDmacFlowEntry(BigInteger srcDpId, BigInteger destDpId, long lportTagOrVni, long elanTag,
1014 String macAddress, String displayName, ElanInstance elanInstance) {
1015 List<MatchInfo> mkMatches = new ArrayList<>();
1016 mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
1017 mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddress)));
1019 List<Instruction> mkInstructions = new ArrayList<>();
1021 // List of Action for the provided Source and Destination DPIDs
1023 List<Action> actions = null;
1024 if (isVxlanNetworkOrVxlanSegment(elanInstance)) {
1025 actions = elanItmUtils.getInternalTunnelItmEgressAction(srcDpId, destDpId, lportTagOrVni);
1026 } else if (isVlan(elanInstance) || isFlat(elanInstance)) {
1027 String interfaceName = getExternalElanInterface(elanInstance.getElanInstanceName(), srcDpId);
1028 if (null == interfaceName) {
1029 LOG.info("buildRemoteDmacFlowEntry: Could not find interfaceName for {} {}", srcDpId,
1032 actions = getEgressActionsForInterface(interfaceName, null);
1034 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
1035 } catch (Exception e) {
1036 LOG.error("Could not get egress actions to add to flow for srcDpId {}, destDpId {}, lportTag/VNI {}",
1037 srcDpId, destDpId, lportTagOrVni, e);
1040 Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
1041 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, srcDpId, destDpId, macAddress, elanTag),
1043 displayName, 0, /* idleTimeout */
1044 0, /* hardTimeout */
1045 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
1051 public void deleteMacFlows(@Nullable ElanInstance elanInfo, @Nullable InterfaceInfo interfaceInfo,
1052 MacEntry macEntry, TypedReadWriteTransaction<Configuration> flowTx) {
1053 if (elanInfo == null || interfaceInfo == null) {
1056 String macAddress = macEntry.getMacAddress().getValue();
1057 synchronized (getElanMacDPNKey(elanInfo.getElanTag(), macAddress, interfaceInfo.getDpId())) {
1058 deleteMacFlows(elanInfo, interfaceInfo, macAddress, /* alsoDeleteSMAC */ true, flowTx);
1062 public void deleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1063 boolean deleteSmac, TypedReadWriteTransaction<Configuration> flowTx) {
1064 String elanInstanceName = elanInfo.getElanInstanceName();
1065 List<DpnInterfaces> remoteFEs = getInvolvedDpnsInElan(elanInstanceName);
1066 BigInteger srcdpId = interfaceInfo.getDpId();
1067 boolean isFlowsRemovedInSrcDpn = false;
1068 for (DpnInterfaces dpnInterface : remoteFEs) {
1069 Long elanTag = elanInfo.getElanTag();
1070 BigInteger dstDpId = dpnInterface.getDpId();
1071 if (executeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1072 elanTag, dstDpId, flowTx)) {
1073 isFlowsRemovedInSrcDpn = true;
1075 executeEtreeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1076 elanTag, dstDpId, flowTx);
1078 if (!isFlowsRemovedInSrcDpn) {
1079 deleteSmacAndDmacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, flowTx);
1083 private void executeEtreeDeleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1084 boolean deleteSmac, String elanInstanceName, BigInteger srcdpId, Long elanTag, BigInteger dstDpId,
1085 TypedReadWriteTransaction<Configuration> flowTx) {
1086 EtreeLeafTagName etreeLeafTag = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
1087 if (etreeLeafTag != null) {
1088 executeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1089 etreeLeafTag.getEtreeLeafTag().getValue(), dstDpId, flowTx);
1093 // TODO skitt Fix the exception handling here
1094 @SuppressWarnings("checkstyle:IllegalCatch")
1095 @SuppressFBWarnings("REC_CATCH_EXCEPTION")
1096 private boolean executeDeleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1097 boolean deleteSmac, String elanInstanceName, BigInteger srcdpId, Long elanTag, BigInteger dstDpId,
1098 TypedReadWriteTransaction<Configuration> flowTx) {
1099 boolean isFlowsRemovedInSrcDpn = false;
1100 if (dstDpId.equals(srcdpId)) {
1101 isFlowsRemovedInSrcDpn = true;
1102 deleteSmacAndDmacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, flowTx);
1103 } else if (isDpnPresent(dstDpId)) {
1106 .removeFlow(flowTx, dstDpId,
1107 MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, getKnownDynamicmacFlowRef(
1108 NwConstants.ELAN_DMAC_TABLE, dstDpId, srcdpId, macAddress, elanTag)));
1109 } catch (Exception e) {
1110 LOG.error("Error removing flow", e);
1111 throw new RuntimeException("Error removing flow", e);
1113 LOG.debug("Dmac flow entry deleted for elan:{}, logical interface port:{} and mac address:{} on dpn:{}",
1114 elanInstanceName, interfaceInfo.getPortName(), macAddress, dstDpId);
1116 return isFlowsRemovedInSrcDpn;
1119 // TODO skitt Fix the exception handling here
1120 @SuppressWarnings("checkstyle:IllegalCatch")
1121 @SuppressFBWarnings("REC_CATCH_EXCEPTION")
1122 private void deleteSmacAndDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1123 boolean deleteSmac, TypedReadWriteTransaction<Configuration> flowTx) {
1124 String elanInstanceName = elanInfo.getElanInstanceName();
1125 long ifTag = interfaceInfo.getInterfaceTag();
1126 BigInteger srcdpId = interfaceInfo.getDpId();
1127 Long elanTag = elanInfo.getElanTag();
1131 .removeFlow(flowTx, srcdpId,
1132 MDSALUtil.buildFlow(NwConstants.ELAN_SMAC_TABLE, getKnownDynamicmacFlowRef(
1133 NwConstants.ELAN_SMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)));
1135 mdsalManager.removeFlow(flowTx, srcdpId,
1136 MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE,
1137 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)));
1138 } catch (Exception e) {
1139 LOG.error("Error removing flow", e);
1140 throw new RuntimeException("Error removing flow", e);
1142 LOG.debug("All the required flows deleted for elan:{}, logical Interface port:{} and MAC address:{} on dpn:{}",
1143 elanInstanceName, interfaceInfo.getPortName(), macAddress, srcdpId);
1147 * Updates the Elan information in the Operational DS. It also updates the
1148 * ElanInstance in the Config DS by setting the adquired elanTag.
1152 * @param elanInstanceAdded
1153 * the elan instance added
1154 * @param elanInterfaces
1155 * the elan interfaces
1159 * @return the updated ELAN instance.
1161 public static ElanInstance updateOperationalDataStore(IdManagerService idManager,
1162 ElanInstance elanInstanceAdded, List<String> elanInterfaces, WriteTransaction tx) {
1163 String elanInstanceName = elanInstanceAdded.getElanInstanceName();
1164 Long elanTag = elanInstanceAdded.getElanTag();
1165 if (elanTag == null || elanTag == 0L) {
1166 elanTag = retrieveNewElanTag(idManager, elanInstanceName);
1168 Elan elanInfo = new ElanBuilder().setName(elanInstanceName).setElanInterfaces(elanInterfaces)
1169 .withKey(new ElanKey(elanInstanceName)).build();
1171 // Add the ElanState in the elan-state operational data-store
1172 tx.put(LogicalDatastoreType.OPERATIONAL, getElanInstanceOperationalDataPath(elanInstanceName),
1173 elanInfo, WriteTransaction.CREATE_MISSING_PARENTS);
1175 // Add the ElanMacTable in the elan-mac-table operational data-store
1176 MacTable elanMacTable = new MacTableBuilder().withKey(new MacTableKey(elanInstanceName)).build();
1177 tx.put(LogicalDatastoreType.OPERATIONAL, getElanMacTableOperationalDataPath(elanInstanceName),
1178 elanMacTable, WriteTransaction.CREATE_MISSING_PARENTS);
1180 ElanTagNameBuilder elanTagNameBuilder = new ElanTagNameBuilder().setElanTag(elanTag)
1181 .withKey(new ElanTagNameKey(elanTag)).setName(elanInstanceName);
1182 long etreeLeafTag = -1;
1183 if (isEtreeInstance(elanInstanceAdded)) {
1184 etreeLeafTag = retrieveNewElanTag(idManager,elanInstanceName + ElanConstants
1186 EtreeLeafTagName etreeLeafTagName = new EtreeLeafTagNameBuilder()
1187 .setEtreeLeafTag(new EtreeLeafTag(etreeLeafTag)).build();
1188 elanTagNameBuilder.addAugmentation(EtreeLeafTagName.class, etreeLeafTagName);
1189 addTheLeafTagAsElanTag(elanInstanceName, etreeLeafTag, tx);
1191 ElanTagName elanTagName = elanTagNameBuilder.build();
1193 // Add the ElanTag to ElanName in the elan-tag-name Operational
1195 tx.put(LogicalDatastoreType.OPERATIONAL,
1196 getElanInfoEntriesOperationalDataPath(elanTag), elanTagName);
1198 // Updates the ElanInstance Config DS by setting the just acquired
1200 ElanInstanceBuilder elanInstanceBuilder = new ElanInstanceBuilder().setElanInstanceName(elanInstanceName)
1201 .setDescription(elanInstanceAdded.getDescription())
1202 .setMacTimeout(elanInstanceAdded.getMacTimeout() == null
1203 ? Long.valueOf(ElanConstants.DEFAULT_MAC_TIME_OUT) : elanInstanceAdded.getMacTimeout())
1204 .withKey(elanInstanceAdded.key()).setElanTag(elanTag);
1205 if (isEtreeInstance(elanInstanceAdded)) {
1206 EtreeInstance etreeInstance = new EtreeInstanceBuilder().setEtreeLeafTagVal(new EtreeLeafTag(etreeLeafTag))
1208 elanInstanceBuilder.addAugmentation(EtreeInstance.class, etreeInstance);
1210 ElanInstance elanInstanceWithTag = elanInstanceBuilder.build();
1211 tx.merge(LogicalDatastoreType.CONFIGURATION, ElanHelper.getElanInstanceConfigurationDataPath(elanInstanceName),
1212 elanInstanceWithTag, WriteTransaction.CREATE_MISSING_PARENTS);
1213 return elanInstanceWithTag;
1216 private static void addTheLeafTagAsElanTag(String elanInstanceName, long etreeLeafTag, WriteTransaction tx) {
1217 ElanTagName etreeTagAsElanTag = new ElanTagNameBuilder().setElanTag(etreeLeafTag)
1218 .withKey(new ElanTagNameKey(etreeLeafTag)).setName(elanInstanceName).build();
1219 tx.put(LogicalDatastoreType.OPERATIONAL,
1220 getElanInfoEntriesOperationalDataPath(etreeLeafTag), etreeTagAsElanTag);
1223 private static boolean isEtreeInstance(ElanInstance elanInstanceAdded) {
1224 return elanInstanceAdded.augmentation(EtreeInstance.class) != null;
1227 public boolean isDpnPresent(BigInteger dpnId) {
1228 String dpn = String.format("%s:%s", "openflow", dpnId);
1229 NodeId nodeId = new NodeId(dpn);
1231 InstanceIdentifier<Node> node = InstanceIdentifier.builder(Nodes.class).child(Node.class, new NodeKey(nodeId))
1233 return read(broker, LogicalDatastoreType.CONFIGURATION, node).isPresent();
1236 public static ServicesInfo getServiceInfo(String elanInstanceName, String interfaceName) {
1237 return InterfaceServiceUtil.buildServiceInfo(elanInstanceName + "." + interfaceName,
1238 ElanConstants.ELAN_SERVICE_PRIORITY);
1241 public static String getElanServiceName(String elanName, String interfaceName) {
1242 return "elan." + elanName + interfaceName;
1245 public static BoundServices getBoundServices(String serviceName, short servicePriority, int flowPriority,
1246 BigInteger cookie, List<Instruction> instructions) {
1247 StypeOpenflowBuilder augBuilder = new StypeOpenflowBuilder().setFlowCookie(cookie).setFlowPriority(flowPriority)
1248 .setInstruction(instructions);
1249 return new BoundServicesBuilder().withKey(new BoundServicesKey(servicePriority)).setServiceName(serviceName)
1250 .setServicePriority(servicePriority).setServiceType(ServiceTypeFlowBased.class)
1251 .addAugmentation(StypeOpenflow.class, augBuilder.build()).build();
1254 public static InstanceIdentifier<BoundServices> buildServiceId(String interfaceName, short serviceIndex) {
1255 return InstanceIdentifier.builder(ServiceBindings.class)
1256 .child(ServicesInfo.class, new ServicesInfoKey(interfaceName, ServiceModeIngress.class))
1257 .child(BoundServices.class, new BoundServicesKey(serviceIndex)).build();
1260 public static List<MatchInfo> getTunnelMatchesForServiceId(int elanTag) {
1261 List<MatchInfo> mkMatches = new ArrayList<>();
1262 // Matching metadata
1263 mkMatches.add(new MatchTunnelId(BigInteger.valueOf(elanTag)));
1268 public void removeTerminatingServiceAction(BigInteger destDpId, int serviceId) {
1269 RemoveTerminatingServiceActionsInput input = new RemoveTerminatingServiceActionsInputBuilder()
1270 .setDpnId(destDpId).setServiceId(serviceId).build();
1271 Future<RpcResult<RemoveTerminatingServiceActionsOutput>> futureObject =
1272 itmRpcService.removeTerminatingServiceActions(input);
1274 RpcResult<RemoveTerminatingServiceActionsOutput> result = futureObject.get();
1275 if (result.isSuccessful()) {
1276 LOG.debug("Successfully completed removeTerminatingServiceActions for ELAN with serviceId {} on "
1277 + "dpn {}", serviceId, destDpId);
1279 LOG.debug("Failure in removeTerminatingServiceAction RPC call for ELAN with serviceId {} on "
1280 + "dpn {}", serviceId, destDpId);
1282 } catch (InterruptedException | ExecutionException e) {
1283 LOG.error("Error in RPC call removeTerminatingServiceActions for ELAN with serviceId {} on "
1284 + "dpn {}", serviceId, destDpId, e);
1289 * Gets the external tunnel.
1291 * @param sourceDevice
1293 * @param destinationDevice
1294 * the destination device
1295 * @param datastoreType
1296 * the datastore type
1297 * @return the external tunnel
1299 public ExternalTunnel getExternalTunnel(String sourceDevice, String destinationDevice,
1300 LogicalDatastoreType datastoreType) {
1301 Class<? extends TunnelTypeBase> tunType = TunnelTypeVxlan.class;
1302 InstanceIdentifier<ExternalTunnel> iid = InstanceIdentifier.builder(ExternalTunnelList.class)
1303 .child(ExternalTunnel.class, new ExternalTunnelKey(destinationDevice, sourceDevice, tunType)).build();
1304 return read(broker, datastoreType, iid).orNull();
1308 * Gets the external tunnel.
1310 * @param interfaceName
1311 * the interface name
1312 * @param datastoreType
1313 * the datastore type
1314 * @return the external tunnel
1316 public ExternalTunnel getExternalTunnel(String interfaceName, LogicalDatastoreType datastoreType) {
1317 ExternalTunnel externalTunnel = null;
1318 List<ExternalTunnel> externalTunnels = getAllExternalTunnels(datastoreType);
1319 for (ExternalTunnel tunnel : externalTunnels) {
1320 if (StringUtils.equalsIgnoreCase(interfaceName, tunnel.getTunnelInterfaceName())) {
1321 externalTunnel = tunnel;
1325 return externalTunnel;
1329 * Gets the all external tunnels.
1331 * @param datastoreType
1332 * the data store type
1333 * @return the all external tunnels
1335 public List<ExternalTunnel> getAllExternalTunnels(LogicalDatastoreType datastoreType) {
1336 InstanceIdentifier<ExternalTunnelList> iid = InstanceIdentifier.builder(ExternalTunnelList.class).build();
1337 return read(broker, datastoreType, iid).toJavaUtil().map(ExternalTunnelList::getExternalTunnel).orElse(
1338 Collections.emptyList());
1341 public static List<MatchInfo> buildMatchesForElanTagShFlagAndDstMac(long elanTag, boolean shFlag, String macAddr) {
1342 List<MatchInfo> mkMatches = new ArrayList<>();
1344 new MatchMetadata(getElanMetadataLabel(elanTag, shFlag), MetaDataUtil.METADATA_MASK_SERVICE_SH_FLAG));
1345 mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddr)));
1350 * Checks if is interface operational.
1352 * @param interfaceName
1353 * the interface name
1356 * @return true, if is interface operational
1358 public static boolean isInterfaceOperational(String interfaceName, DataBroker dataBroker) {
1359 if (StringUtils.isBlank(interfaceName)) {
1362 Interface ifState = getInterfaceStateFromOperDS(interfaceName, dataBroker);
1363 if (ifState == null) {
1366 return ifState.getOperStatus() == OperStatus.Up && ifState.getAdminStatus() == AdminStatus.Up;
1370 * Gets the interface state from operational ds.
1372 * @param interfaceName
1373 * the interface name
1376 * @return the interface state from oper ds
1378 public static org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1379 .ietf.interfaces.rev140508.interfaces.state.Interface getInterfaceStateFromOperDS(
1380 String interfaceName, DataBroker dataBroker) {
1381 InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1382 .ietf.interfaces.rev140508.interfaces.state.Interface> ifStateId = createInterfaceStateInstanceIdentifier(
1384 return MDSALUtil.read(dataBroker, LogicalDatastoreType.OPERATIONAL, ifStateId).orNull();
1388 * Creates the interface state instance identifier.
1390 * @param interfaceName
1391 * the interface name
1392 * @return the instance identifier
1394 public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1395 .ietf.interfaces.rev140508.interfaces.state.Interface> createInterfaceStateInstanceIdentifier(
1396 String interfaceName) {
1397 InstanceIdentifierBuilder<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1398 .ietf.interfaces.rev140508.interfaces.state.Interface> idBuilder = InstanceIdentifier
1399 .builder(InterfacesState.class)
1400 .child(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1401 .ietf.interfaces.rev140508.interfaces.state.Interface.class,
1402 new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1403 .ietf.interfaces.rev140508.interfaces.state.InterfaceKey(
1405 return idBuilder.build();
1409 public static CheckedFuture<Void, TransactionCommitFailedException> waitForTransactionToComplete(
1410 WriteTransaction tx) {
1411 CheckedFuture<Void, TransactionCommitFailedException> futures = tx.submit();
1414 } catch (InterruptedException | ExecutionException e) {
1415 // NETVIRT-1215: Do not log.error() here, only debug(); but callers *MUST* @CheckReturnValue
1416 LOG.debug("Error writing to datastore", e);
1421 public static boolean isVxlan(@Nullable ElanInstance elanInstance) {
1422 return elanInstance != null && elanInstance.getSegmentType() != null
1423 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1424 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId() != 0;
1427 private static boolean isVxlanSegment(ElanInstance elanInstance) {
1428 if (elanInstance != null) {
1429 List<ElanSegments> elanSegments = elanInstance.getElanSegments();
1430 if (elanSegments != null) {
1431 for (ElanSegments segment : elanSegments) {
1432 if (segment != null && segment.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1433 && segment.getSegmentationId() != null
1434 && segment.getSegmentationId().longValue() != 0) {
1443 public static boolean isVxlanNetworkOrVxlanSegment(ElanInstance elanInstance) {
1444 return isVxlan(elanInstance) || isVxlanSegment(elanInstance);
1447 public static Long getVxlanSegmentationId(ElanInstance elanInstance) {
1448 Long segmentationId = 0L;
1449 if (elanInstance == null) {
1450 return segmentationId;
1453 if (elanInstance.getSegmentType() != null
1454 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1455 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId().longValue() != 0) {
1456 segmentationId = elanInstance.getSegmentationId();
1458 for (ElanSegments segment: elanInstance.getElanSegments()) {
1459 if (segment != null && segment.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1460 && segment.getSegmentationId() != null
1461 && segment.getSegmentationId().longValue() != 0) {
1462 segmentationId = segment.getSegmentationId();
1466 return segmentationId;
1469 public static boolean isVlan(ElanInstance elanInstance) {
1470 return elanInstance != null && elanInstance.getSegmentType() != null
1471 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVlan.class)
1472 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId() != 0;
1475 public static boolean isFlat(ElanInstance elanInstance) {
1476 return elanInstance != null && elanInstance.getSegmentType() != null
1477 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeFlat.class);
1480 public void addDmacRedirectToDispatcherFlows(Long elanTag, String displayName,
1481 String macAddress, List<BigInteger> dpnIds) {
1482 for (BigInteger dpId : dpnIds) {
1483 ListenableFutures.addErrorLogging(txRunner.callWithNewWriteOnlyTransactionAndSubmit(CONFIGURATION,
1484 tx -> mdsalManager.addFlow(tx, buildDmacRedirectToDispatcherFlow(dpId, macAddress, displayName,
1486 "Error adding DMAC redirect to dispatcher flows");
1490 public void removeDmacRedirectToDispatcherFlows(Long elanTag, String macAddress, List<BigInteger> dpnIds) {
1491 for (BigInteger dpId : dpnIds) {
1492 String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, macAddress, elanTag);
1493 mdsalManager.removeFlow(dpId, MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, flowId));
1497 public static FlowEntity buildDmacRedirectToDispatcherFlow(BigInteger dpId, String dstMacAddress,
1498 String displayName, long elanTag) {
1499 List<MatchInfo> matches = new ArrayList<>();
1500 matches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
1501 matches.add(new MatchEthernetDestination(new MacAddress(dstMacAddress)));
1502 List<InstructionInfo> instructions = new ArrayList<>();
1503 List<ActionInfo> actions = new ArrayList<>();
1504 actions.add(new ActionNxResubmit(NwConstants.LPORT_DISPATCHER_TABLE));
1506 instructions.add(new InstructionApplyActions(actions));
1507 String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, dstMacAddress, elanTag);
1508 return MDSALUtil.buildFlowEntity(dpId, NwConstants.ELAN_DMAC_TABLE, flowId, 20, displayName, 0, 0,
1509 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)),
1510 matches, instructions);
1513 public String getExternalElanInterface(String elanInstanceName, BigInteger dpnId) {
1514 DpnInterfaces dpnInterfaces = getElanInterfaceInfoByElanDpn(elanInstanceName, dpnId);
1515 if (dpnInterfaces == null || dpnInterfaces.getInterfaces() == null) {
1516 LOG.trace("Elan {} does not have interfaces in DPN {}", elanInstanceName, dpnId);
1520 for (String dpnInterface : dpnInterfaces.getInterfaces()) {
1521 if (interfaceManager.isExternalInterface(dpnInterface)) {
1522 return dpnInterface;
1526 LOG.trace("Elan {} does not have any external interace attached to DPN {}", elanInstanceName, dpnId);
1530 public static String getElanMacDPNKey(long elanTag, String macAddress, BigInteger dpnId) {
1531 String elanMacDmacDpnKey = "MAC-" + macAddress + " ELAN_TAG-" + elanTag + "DPN_ID-" + dpnId;
1532 return elanMacDmacDpnKey.intern();
1535 public static String getElanMacKey(long elanTag, String macAddress) {
1536 String elanMacKey = "MAC-" + macAddress + " ELAN_TAG-" + elanTag;
1537 return elanMacKey.intern();
1540 public static List<ListenableFuture<Void>>
1541 returnFailedListenableFutureIfTransactionCommitFailedExceptionCauseOrElseThrow(RuntimeException exception) {
1543 Throwable cause = exception.getCause();
1544 if (cause != null && cause instanceof TransactionCommitFailedException) {
1545 return Collections.singletonList(Futures.immediateFailedFuture(cause));
1551 public static List<PhysAddress> getPhysAddress(List<String> macAddress) {
1552 Preconditions.checkNotNull(macAddress, "macAddress cannot be null");
1553 List<PhysAddress> physAddresses = new ArrayList<>();
1554 for (String mac : macAddress) {
1555 physAddresses.add(new PhysAddress(mac));
1557 return physAddresses;
1560 public static List<StaticMacEntries> getStaticMacEntries(List<String> staticMacAddresses) {
1561 if (isEmpty(staticMacAddresses)) {
1562 return Collections.EMPTY_LIST;
1564 StaticMacEntriesBuilder staticMacEntriesBuilder = new StaticMacEntriesBuilder();
1565 List<StaticMacEntries> staticMacEntries = new ArrayList<>();
1566 List<PhysAddress> physAddressList = getPhysAddress(staticMacAddresses);
1567 for (PhysAddress physAddress : physAddressList) {
1568 staticMacEntries.add(staticMacEntriesBuilder.setMacAddress(physAddress).build());
1570 return staticMacEntries;
1573 public static InstanceIdentifier<StaticMacEntries> getStaticMacEntriesCfgDataPathIdentifier(String interfaceName,
1574 String macAddress) {
1575 return InstanceIdentifier.builder(ElanInterfaces.class)
1576 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).child(StaticMacEntries.class,
1577 new StaticMacEntriesKey(new PhysAddress(macAddress))).build();
1580 public static List<StaticMacEntries> getDeletedEntries(List<StaticMacEntries> originalStaticMacEntries,
1581 List<StaticMacEntries> updatedStaticMacEntries) {
1582 if (isEmpty(originalStaticMacEntries)) {
1583 return Collections.EMPTY_LIST;
1585 List<StaticMacEntries> deleted = Lists.newArrayList(originalStaticMacEntries);
1586 if (isNotEmpty(updatedStaticMacEntries)) {
1587 deleted.removeAll(updatedStaticMacEntries);
1592 public static <T> List<T> diffOf(List<T> orig, List<T> updated) {
1593 if (isEmpty(orig)) {
1594 return Collections.EMPTY_LIST;
1596 List<T> diff = Lists.newArrayList(orig);
1597 if (isNotEmpty(updated)) {
1598 diff.removeAll(updated);
1603 public static void segregateToBeDeletedAndAddEntries(List<StaticMacEntries> originalStaticMacEntries,
1604 List<StaticMacEntries> updatedStaticMacEntries) {
1605 if (isNotEmpty(updatedStaticMacEntries)) {
1606 List<StaticMacEntries> existingClonedStaticMacEntries = new ArrayList<>();
1607 if (isNotEmpty(originalStaticMacEntries)) {
1608 existingClonedStaticMacEntries.addAll(0, originalStaticMacEntries);
1609 originalStaticMacEntries.removeAll(updatedStaticMacEntries);
1610 updatedStaticMacEntries.removeAll(existingClonedStaticMacEntries);
1615 public static boolean isEmpty(Collection collection) {
1616 return collection == null || collection.isEmpty();
1619 public static boolean isNotEmpty(Collection collection) {
1620 return !isEmpty(collection);
1623 public Optional<IpAddress> getSourceIpAddress(Ethernet ethernet) {
1624 Optional<IpAddress> srcIpAddress = Optional.absent();
1625 if (ethernet.getPayload() == null) {
1626 return srcIpAddress;
1628 byte[] ipAddrBytes = null;
1629 if (ethernet.getPayload() instanceof IPv4) {
1630 IPv4 ipv4 = (IPv4) ethernet.getPayload();
1631 ipAddrBytes = Ints.toByteArray(ipv4.getSourceAddress());
1632 } else if (ethernet.getPayload() instanceof ARP) {
1633 ipAddrBytes = ((ARP) ethernet.getPayload()).getSenderProtocolAddress();
1635 if (ipAddrBytes != null) {
1636 String ipAddr = NWUtil.toStringIpAddress(ipAddrBytes);
1637 return Optional.of(IpAddressBuilder.getDefaultInstance(ipAddr));
1639 return srcIpAddress;
1642 public List<MacEntry> getElanMacEntries(String elanName) {
1643 MacTable macTable = getElanMacTable(elanName);
1644 if (macTable == null) {
1645 return Collections.emptyList();
1647 return macTable.getMacEntry();
1650 public boolean isTunnelInLogicalGroup(String interfaceName) {
1651 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1652 .ietf.interfaces.rev140508.interfaces.Interface configIface =
1653 interfaceManager.getInterfaceInfoFromConfigDataStore(interfaceName);
1654 if (configIface == null) {
1655 configIface = iitmProvider.getInterface(interfaceName);
1657 if (configIface == null) {
1660 IfTunnel ifTunnel = configIface.augmentation(IfTunnel.class);
1661 if (ifTunnel != null && ifTunnel.getTunnelInterfaceType().isAssignableFrom(TunnelTypeVxlan.class)) {
1662 ParentRefs refs = configIface.augmentation(ParentRefs.class);
1663 if (refs != null && !Strings.isNullOrEmpty(refs.getParentInterface())) {
1664 return true; //multiple VxLAN tunnels enabled, i.e. only logical tunnel should be treated
1670 public static InstanceIdentifier<Flow> getFlowIid(Flow flow, BigInteger dpnId) {
1671 FlowKey flowKey = new FlowKey(new FlowId(flow.getId()));
1672 org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId nodeId =
1673 new org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId("openflow:" + dpnId);
1674 org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node nodeDpn =
1675 new NodeBuilder().setId(nodeId).withKey(new NodeKey(nodeId)).build();
1676 return InstanceIdentifier.builder(Nodes.class)
1677 .child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node.class,
1678 nodeDpn.key()).augmentation(FlowCapableNode.class)
1679 .child(Table.class, new TableKey(flow.getTableId())).child(Flow.class, flowKey).build();
1682 public static String getElanInterfaceJobKey(String interfaceName) {
1683 return "elaninterface-" + interfaceName;
1686 public void removeArpResponderFlow(BigInteger dpnId, String ingressInterfaceName, String ipAddress,
1688 LOG.info("Removing the ARP responder flow on DPN {} of Interface {} with IP {}", dpnId, ingressInterfaceName,
1690 ArpResponderUtil.removeFlow(mdsalManager, dpnId, ArpResponderUtil.getFlowId(lportTag, ipAddress));
1693 public static String getRouterPordIdFromElanInstance(DataBroker dataBroker, String elanInstanceName) {
1694 Optional<Subnetmaps> subnetMapsData =
1695 read(dataBroker, LogicalDatastoreType.CONFIGURATION, buildSubnetMapsWildCardPath());
1696 if (subnetMapsData.isPresent()) {
1697 List<Subnetmap> subnetMapList = subnetMapsData.get().getSubnetmap();
1698 if (subnetMapList != null && !subnetMapList.isEmpty()) {
1699 for (Subnetmap subnet : subnetMapList) {
1700 if (subnet.getNetworkId().getValue().equals(elanInstanceName)) {
1701 if (subnet.getRouterInterfacePortId() != null) {
1702 return subnet.getRouterInterfacePortId().getValue();
1711 static InstanceIdentifier<Subnetmaps> buildSubnetMapsWildCardPath() {
1712 return InstanceIdentifier.create(Subnetmaps.class);