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.controller.md.sal.binding.api.WriteTransaction.CREATE_MISSING_PARENTS;
11 import static org.opendaylight.genius.infra.Datastore.CONFIGURATION;
13 import com.google.common.base.Optional;
14 import com.google.common.base.Preconditions;
15 import com.google.common.base.Strings;
16 import com.google.common.collect.Lists;
17 import com.google.common.primitives.Ints;
18 import com.google.common.util.concurrent.CheckedFuture;
19 import com.google.common.util.concurrent.FutureCallback;
20 import com.google.common.util.concurrent.Futures;
21 import com.google.common.util.concurrent.ListenableFuture;
22 import com.google.common.util.concurrent.MoreExecutors;
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.WriteTransaction;
42 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
43 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
44 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
45 import org.opendaylight.genius.infra.Datastore;
46 import org.opendaylight.genius.infra.Datastore.Configuration;
47 import org.opendaylight.genius.infra.Datastore.Operational;
48 import org.opendaylight.genius.infra.ManagedNewTransactionRunner;
49 import org.opendaylight.genius.infra.ManagedNewTransactionRunnerImpl;
50 import org.opendaylight.genius.infra.TypedReadTransaction;
51 import org.opendaylight.genius.infra.TypedReadWriteTransaction;
52 import org.opendaylight.genius.infra.TypedWriteTransaction;
53 import org.opendaylight.genius.interfacemanager.globals.InterfaceInfo;
54 import org.opendaylight.genius.interfacemanager.globals.InterfaceServiceUtil;
55 import org.opendaylight.genius.interfacemanager.interfaces.IInterfaceManager;
56 import org.opendaylight.genius.itm.api.IITMProvider;
57 import org.opendaylight.genius.itm.globals.ITMConstants;
58 import org.opendaylight.genius.mdsalutil.ActionInfo;
59 import org.opendaylight.genius.mdsalutil.FlowEntity;
60 import org.opendaylight.genius.mdsalutil.FlowEntityBuilder;
61 import org.opendaylight.genius.mdsalutil.InstructionInfo;
62 import org.opendaylight.genius.mdsalutil.MDSALUtil;
63 import org.opendaylight.genius.mdsalutil.MatchInfo;
64 import org.opendaylight.genius.mdsalutil.MetaDataUtil;
65 import org.opendaylight.genius.mdsalutil.NWUtil;
66 import org.opendaylight.genius.mdsalutil.NwConstants;
67 import org.opendaylight.genius.mdsalutil.actions.ActionNxResubmit;
68 import org.opendaylight.genius.mdsalutil.instructions.InstructionApplyActions;
69 import org.opendaylight.genius.mdsalutil.instructions.InstructionGotoTable;
70 import org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager;
71 import org.opendaylight.genius.mdsalutil.matches.MatchEthernetDestination;
72 import org.opendaylight.genius.mdsalutil.matches.MatchEthernetSource;
73 import org.opendaylight.genius.mdsalutil.matches.MatchMetadata;
74 import org.opendaylight.genius.mdsalutil.matches.MatchTunnelId;
75 import org.opendaylight.genius.mdsalutil.packet.ARP;
76 import org.opendaylight.genius.mdsalutil.packet.Ethernet;
77 import org.opendaylight.genius.mdsalutil.packet.IPv4;
78 import org.opendaylight.infrautils.utils.concurrent.JdkFutures;
79 import org.opendaylight.infrautils.utils.concurrent.ListenableFutures;
80 import org.opendaylight.netvirt.elan.arp.responder.ArpResponderUtil;
81 import org.opendaylight.netvirt.elan.cache.ElanInterfaceCache;
82 import org.opendaylight.netvirt.elanmanager.api.ElanHelper;
83 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
84 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddressBuilder;
85 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfacesState;
86 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface;
87 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.AdminStatus;
88 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.OperStatus;
89 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
90 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.PhysAddress;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
96 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
97 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
98 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
99 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInput;
100 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInputBuilder;
101 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdOutput;
102 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdManagerService;
103 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInput;
104 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInputBuilder;
105 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406.IfIndexesInterfaceMap;
106 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._if.indexes._interface.map.IfIndexInterface;
107 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._if.indexes._interface.map.IfIndexInterfaceKey;
108 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfTunnel;
109 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.ParentRefs;
110 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeBase;
111 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeVxlan;
112 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceInput;
113 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceInputBuilder;
114 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceOutput;
115 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.OdlInterfaceRpcService;
116 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceBindings;
117 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceModeIngress;
118 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceTypeFlowBased;
119 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflow;
120 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflowBuilder;
121 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.ServicesInfo;
122 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.ServicesInfoKey;
123 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServices;
124 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesBuilder;
125 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesKey;
126 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.ExternalTunnelList;
127 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnel;
128 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnelKey;
129 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.ItmRpcService;
130 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsInput;
131 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsInputBuilder;
132 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsOutput;
133 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupId;
134 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group;
135 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupKey;
136 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
137 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
138 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
139 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
140 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
141 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.config.rev150710.ElanConfig;
142 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInstance;
143 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInstanceBuilder;
144 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInterface;
145 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInterface.EtreeInterfaceType;
146 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTag;
147 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTagName;
148 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTagNameBuilder;
149 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanDpnInterfaces;
150 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanForwardingTables;
151 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInstances;
152 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaceForwardingEntries;
153 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaces;
154 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanState;
155 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanTagNameMap;
156 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeFlat;
157 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeVlan;
158 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeVxlan;
159 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan._interface.forwarding.entries.ElanInterfaceMac;
160 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan._interface.forwarding.entries.ElanInterfaceMacKey;
161 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesList;
162 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesListKey;
163 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfaces;
164 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfacesKey;
165 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTable;
166 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTableBuilder;
167 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTableKey;
168 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstance;
169 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstanceBuilder;
170 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.elan.instance.ElanSegments;
171 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterface;
172 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterfaceKey;
173 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntries;
174 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntriesBuilder;
175 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntriesKey;
176 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.Elan;
177 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.ElanBuilder;
178 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.ElanKey;
179 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagName;
180 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagNameBuilder;
181 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagNameKey;
182 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntry;
183 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntryKey;
184 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.Subnetmaps;
185 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.subnetmaps.Subnetmap;
186 import org.opendaylight.yangtools.yang.binding.DataObject;
187 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
188 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.InstanceIdentifierBuilder;
189 import org.opendaylight.yangtools.yang.common.RpcResult;
190 import org.slf4j.Logger;
191 import org.slf4j.LoggerFactory;
194 public class ElanUtils {
196 private static final Logger LOG = LoggerFactory.getLogger(ElanUtils.class);
198 private final DataBroker broker;
199 private final ManagedNewTransactionRunner txRunner;
200 private final IMdsalApiManager mdsalManager;
201 private final OdlInterfaceRpcService interfaceManagerRpcService;
202 private final ItmRpcService itmRpcService;
203 private final IInterfaceManager interfaceManager;
204 private final ElanConfig elanConfig;
205 private final ElanItmUtils elanItmUtils;
206 private final ElanEtreeUtils elanEtreeUtils;
207 private final ElanInterfaceCache elanInterfaceCache;
208 private final IITMProvider iitmProvider;
210 public static final FutureCallback<Void> DEFAULT_CALLBACK = new FutureCallback<Void>() {
212 public void onSuccess(Void result) {
213 LOG.debug("Success in Datastore operation");
217 public void onFailure(Throwable error) {
218 LOG.error("Error in Datastore operation", error);
223 public ElanUtils(DataBroker dataBroker, IMdsalApiManager mdsalManager,
224 OdlInterfaceRpcService interfaceManagerRpcService, ItmRpcService itmRpcService, ElanConfig elanConfig,
225 IInterfaceManager interfaceManager, ElanEtreeUtils elanEtreeUtils, ElanItmUtils elanItmUtils,
226 ElanInterfaceCache elanInterfaceCache, IITMProvider iitmProvider) {
227 this.broker = dataBroker;
228 this.txRunner = new ManagedNewTransactionRunnerImpl(dataBroker);
229 this.mdsalManager = mdsalManager;
230 this.interfaceManagerRpcService = interfaceManagerRpcService;
231 this.itmRpcService = itmRpcService;
232 this.interfaceManager = interfaceManager;
233 this.elanConfig = elanConfig;
234 this.elanEtreeUtils = elanEtreeUtils;
235 this.elanItmUtils = elanItmUtils;
236 this.elanInterfaceCache = elanInterfaceCache;
237 this.iitmProvider = iitmProvider;
240 public final Boolean isOpenstackVniSemanticsEnforced() {
241 return elanConfig.isOpenstackVniSemanticsEnforced() != null
242 ? elanConfig.isOpenstackVniSemanticsEnforced() : false;
246 * Uses the IdManager to retrieve a brand new ElanTag.
252 * @return the integer
254 public static Long retrieveNewElanTag(IdManagerService idManager, String idKey) {
256 AllocateIdInput getIdInput = new AllocateIdInputBuilder().setPoolName(ElanConstants.ELAN_ID_POOL_NAME)
257 .setIdKey(idKey).build();
260 Future<RpcResult<AllocateIdOutput>> result = idManager.allocateId(getIdInput);
261 RpcResult<AllocateIdOutput> rpcResult = result.get();
262 if (rpcResult.isSuccessful()) {
263 return rpcResult.getResult().getIdValue();
265 LOG.warn("RPC Call to Allocate Id returned with Errors {}", rpcResult.getErrors());
267 } catch (InterruptedException | ExecutionException e) {
268 LOG.warn("Exception when Allocating Id", e);
273 public static void releaseId(IdManagerService idManager, String poolName, String idKey) {
274 ReleaseIdInput releaseIdInput = new ReleaseIdInputBuilder().setPoolName(poolName).setIdKey(idKey).build();
275 JdkFutures.addErrorLogging(idManager.releaseId(releaseIdInput), LOG, "Release Id");
281 * @deprecated Consider using {@link #read2(LogicalDatastoreType, InstanceIdentifier)} with proper exception
283 * @param broker dataBroker
284 * @param datastoreType Logical DataStore type
285 * @param path IID to read
286 * @param <T> T extends DataObject
287 * @return the read value T
290 @SuppressWarnings("checkstyle:IllegalCatch")
291 public static <T extends DataObject> Optional<T> read(@Nonnull DataBroker broker,
292 LogicalDatastoreType datastoreType, InstanceIdentifier<T> path) {
293 try (ReadOnlyTransaction tx = broker.newReadOnlyTransaction()) {
294 return tx.read(datastoreType, path).get();
295 } catch (Exception e) {
296 throw new RuntimeException(e);
300 public <T extends DataObject> Optional<T> read2(LogicalDatastoreType datastoreType, InstanceIdentifier<T> path)
301 throws ReadFailedException {
302 try (ReadOnlyTransaction tx = broker.newReadOnlyTransaction()) {
303 CheckedFuture<Optional<T>, ReadFailedException> checkedFuture = tx.read(datastoreType, path);
304 return checkedFuture.checkedGet();
308 @SuppressWarnings("checkstyle:ForbidCertainMethod")
309 public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
310 InstanceIdentifier<T> path) {
311 WriteTransaction tx = broker.newWriteOnlyTransaction();
312 tx.delete(datastoreType, path);
313 Futures.addCallback(tx.submit(), DEFAULT_CALLBACK, MoreExecutors.directExecutor());
316 @SuppressWarnings("checkstyle:ForbidCertainMethod")
317 public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
318 InstanceIdentifier<T> path, FutureCallback<Void> callback) {
319 WriteTransaction tx = broker.newWriteOnlyTransaction();
320 tx.delete(datastoreType, path);
321 Futures.addCallback(tx.submit(), callback, MoreExecutors.directExecutor());
324 public static InstanceIdentifier<ElanInstance> getElanInstanceIdentifier() {
325 return InstanceIdentifier.builder(ElanInstances.class).child(ElanInstance.class).build();
328 public static InstanceIdentifier<ElanInterface> getElanInterfaceConfigurationDataPathId(String interfaceName) {
329 return InstanceIdentifier.builder(ElanInterfaces.class)
330 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).build();
333 // elan-state Operational container
334 public static Elan getElanByName(DataBroker broker, String elanInstanceName) {
335 InstanceIdentifier<Elan> elanIdentifier = getElanInstanceOperationalDataPath(elanInstanceName);
336 return MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL, elanIdentifier).orNull();
340 public static Elan getElanByName(TypedReadTransaction<Operational> tx, String elanInstanceName)
341 throws ExecutionException, InterruptedException {
342 return tx.read(getElanInstanceOperationalDataPath(elanInstanceName)).get().orNull();
345 public static InstanceIdentifier<Elan> getElanInstanceOperationalDataPath(String elanInstanceName) {
346 return InstanceIdentifier.builder(ElanState.class).child(Elan.class, new ElanKey(elanInstanceName)).build();
349 // grouping of forwarding-entries
350 public MacEntry getInterfaceMacEntriesOperationalDataPath(String interfaceName, PhysAddress physAddress) {
351 InstanceIdentifier<MacEntry> existingMacEntryId = getInterfaceMacEntriesIdentifierOperationalDataPath(
352 interfaceName, physAddress);
353 return read(broker, LogicalDatastoreType.OPERATIONAL, existingMacEntryId).orNull();
356 public MacEntry getInterfaceMacEntriesOperationalDataPathFromId(InstanceIdentifier identifier) {
357 Optional<MacEntry> existingInterfaceMacEntry = read(broker,
358 LogicalDatastoreType.OPERATIONAL, identifier);
359 return existingInterfaceMacEntry.orNull();
362 public MacEntry getInterfaceMacEntriesOperationalDataPathFromId(TypedReadTransaction<Operational> tx,
363 InstanceIdentifier<MacEntry> identifier) throws ExecutionException, InterruptedException {
364 return tx.read(identifier).get().orNull();
367 public static InstanceIdentifier<MacEntry> getInterfaceMacEntriesIdentifierOperationalDataPath(String interfaceName,
368 PhysAddress physAddress) {
369 return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class)
370 .child(ElanInterfaceMac.class, new ElanInterfaceMacKey(interfaceName))
371 .child(MacEntry.class, new MacEntryKey(physAddress)).build();
375 // elan-forwarding-tables Operational container
376 public Optional<MacEntry> getMacEntryForElanInstance(String elanName, PhysAddress physAddress) {
377 InstanceIdentifier<MacEntry> macId = getMacEntryOperationalDataPath(elanName, physAddress);
378 return read(broker, LogicalDatastoreType.OPERATIONAL, macId);
381 public Optional<MacEntry> getMacEntryForElanInstance(TypedReadTransaction<Operational> tx, String elanName,
382 PhysAddress physAddress) throws ExecutionException, InterruptedException {
383 InstanceIdentifier<MacEntry> macId = getMacEntryOperationalDataPath(elanName, physAddress);
384 return tx.read(macId).get();
387 public MacEntry getMacEntryFromElanMacId(InstanceIdentifier identifier) {
388 Optional<MacEntry> existingInterfaceMacEntry = read(broker,
389 LogicalDatastoreType.OPERATIONAL, identifier);
390 return existingInterfaceMacEntry.orNull();
393 public MacEntry getMacEntryFromElanMacId(TypedReadTransaction<Operational> tx,
394 InstanceIdentifier<MacEntry> identifier) throws ExecutionException, InterruptedException {
395 return tx.read(identifier).get().orNull();
398 public static InstanceIdentifier<MacEntry> getMacEntryOperationalDataPath(String elanName,
399 PhysAddress physAddress) {
400 return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class, new MacTableKey(elanName))
401 .child(MacEntry.class, new MacEntryKey(physAddress)).build();
404 public static InstanceIdentifier<MacTable> getElanMacTableOperationalDataPath(String elanName) {
405 return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class, new MacTableKey(elanName))
409 // elan-interface-forwarding-entries Operational container
410 public ElanInterfaceMac getElanInterfaceMacByInterfaceName(String interfaceName) {
411 return getElanInterfaceMacByInterfaceName(broker, interfaceName);
415 public static ElanInterfaceMac getElanInterfaceMacByInterfaceName(DataBroker dataBroker, String interfaceName) {
416 InstanceIdentifier<ElanInterfaceMac> elanInterfaceId = getElanInterfaceMacEntriesOperationalDataPath(
418 return read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanInterfaceId).orNull();
422 * Gets the elan interface mac addresses.
424 * @param interfaceName
426 * @return the elan interface mac addresses
428 public List<PhysAddress> getElanInterfaceMacAddresses(String interfaceName) {
429 List<PhysAddress> macAddresses = new ArrayList<>();
430 ElanInterfaceMac elanInterfaceMac = getElanInterfaceMacByInterfaceName(interfaceName);
431 if (elanInterfaceMac != null && elanInterfaceMac.getMacEntry() != null) {
432 List<MacEntry> macEntries = elanInterfaceMac.getMacEntry();
433 for (MacEntry macEntry : macEntries) {
434 macAddresses.add(macEntry.getMacAddress());
440 public static InstanceIdentifier<ElanInterfaceMac> getElanInterfaceMacEntriesOperationalDataPath(
441 String interfaceName) {
442 return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class)
443 .child(ElanInterfaceMac.class, new ElanInterfaceMacKey(interfaceName)).build();
447 * Returns the list of Interfaces that belong to an Elan on an specific DPN.
448 * Data retrieved from Elan's operational DS: elan-dpn-interfaces container
450 * @param elanInstanceName
451 * name of the Elan to which the interfaces must belong to
453 * Id of the DPN where the interfaces are located
454 * @return the elan interface Info
456 public DpnInterfaces getElanInterfaceInfoByElanDpn(String elanInstanceName, BigInteger dpId) {
457 InstanceIdentifier<DpnInterfaces> elanDpnInterfacesId = getElanDpnInterfaceOperationalDataPath(elanInstanceName,
459 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfacesId).orNull();
463 * Returns the InstanceIdentifier that points to the Interfaces of an Elan
464 * in a given DPN in the Operational DS. Data retrieved from Elans's
465 * operational DS: dpn-interfaces list
467 * @param elanInstanceName
468 * name of the Elan to which the interfaces must belong to
470 * Id of the DPN where the interfaces are located
471 * @return the elan dpn interface
473 public static InstanceIdentifier<DpnInterfaces> getElanDpnInterfaceOperationalDataPath(String elanInstanceName,
475 return InstanceIdentifier.builder(ElanDpnInterfaces.class)
476 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName))
477 .child(DpnInterfaces.class, new DpnInterfacesKey(dpId)).build();
480 // elan-tag-name-map Operational Container
481 public ElanTagName getElanInfoByElanTag(long elanTag) {
482 InstanceIdentifier<ElanTagName> elanId = getElanInfoEntriesOperationalDataPath(elanTag);
483 Optional<ElanTagName> existingElanInfo = read(broker,
484 LogicalDatastoreType.OPERATIONAL, elanId);
485 return existingElanInfo.orNull();
488 public static InstanceIdentifier<ElanTagName> getElanInfoEntriesOperationalDataPath(long elanTag) {
489 return InstanceIdentifier.builder(ElanTagNameMap.class).child(ElanTagName.class, new ElanTagNameKey(elanTag))
493 // interface-index-tag operational container
494 public Optional<IfIndexInterface> getInterfaceInfoByInterfaceTag(long interfaceTag) {
495 InstanceIdentifier<IfIndexInterface> interfaceId = getInterfaceInfoEntriesOperationalDataPath(interfaceTag);
496 return read(broker, LogicalDatastoreType.OPERATIONAL, interfaceId);
499 public static InstanceIdentifier<IfIndexInterface> getInterfaceInfoEntriesOperationalDataPath(long interfaceTag) {
500 return InstanceIdentifier.builder(IfIndexesInterfaceMap.class)
501 .child(IfIndexInterface.class, new IfIndexInterfaceKey((int) interfaceTag)).build();
504 public static InstanceIdentifier<ElanDpnInterfacesList> getElanDpnOperationDataPath(String elanInstanceName) {
505 return InstanceIdentifier.builder(ElanDpnInterfaces.class)
506 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName)).build();
509 public ElanDpnInterfacesList getElanDpnInterfacesList(String elanName) {
510 InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanName);
511 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orNull();
514 public ElanDpnInterfaces getElanDpnInterfacesList() {
515 InstanceIdentifier<ElanDpnInterfaces> elanDpnInterfaceId = InstanceIdentifier.builder(ElanDpnInterfaces.class)
517 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orNull();
521 * This method is useful get all ELAN participating CSS dpIds to install
522 * program remote dmac entries and updating remote bc groups for tor
525 * @param elanInstanceName
526 * the elan instance name
527 * @return list of dpIds
530 public List<BigInteger> getParticipatingDpnsInElanInstance(String elanInstanceName) {
531 List<BigInteger> dpIds = new ArrayList<>();
532 InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
533 Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = read(broker,
534 LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
535 if (!existingElanDpnInterfaces.isPresent()) {
538 List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().getDpnInterfaces();
539 for (DpnInterfaces dpnInterface : dpnInterfaces) {
540 dpIds.add(dpnInterface.getDpId());
546 * To check given dpId is already present in Elan instance. This can be used
547 * to program flow entry in external tunnel table when a new access port
548 * added for first time into the ELAN instance
552 * @param elanInstanceName
553 * the elan instance name
554 * @return true if dpId is already present, otherwise return false
556 public boolean isDpnAlreadyPresentInElanInstance(BigInteger dpId, String elanInstanceName) {
557 InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
558 Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = read(broker,
559 LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
560 if (!existingElanDpnInterfaces.isPresent()) {
563 List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().getDpnInterfaces();
564 for (DpnInterfaces dpnInterface : dpnInterfaces) {
565 if (dpnInterface.getDpId().equals(dpId)) {
572 public ElanForwardingTables getElanForwardingList() {
573 InstanceIdentifier<ElanForwardingTables> elanForwardingTableId = InstanceIdentifier
574 .builder(ElanForwardingTables.class).build();
575 return read(broker, LogicalDatastoreType.OPERATIONAL, elanForwardingTableId).orNull();
578 public static long getElanRemoteBroadCastGroupID(long elanTag) {
579 return ElanConstants.ELAN_GID_MIN + elanTag % ElanConstants.ELAN_GID_MIN * 2;
583 * Gets the elan mac table.
587 * @return the elan mac table
589 public MacTable getElanMacTable(String elanName) {
590 return getElanMacTable(broker, elanName);
594 public static MacTable getElanMacTable(DataBroker dataBroker, String elanName) {
595 InstanceIdentifier<MacTable> elanMacTableId = getElanMacTableOperationalDataPath(elanName);
596 return read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanMacTableId).orNull();
599 public static long getElanLocalBCGId(long elanTag) {
600 return ElanConstants.ELAN_GID_MIN + (elanTag % ElanConstants.ELAN_GID_MIN * 2 - 1);
603 public static long getElanRemoteBCGId(long elanTag) {
604 return ElanConstants.ELAN_GID_MIN + elanTag % ElanConstants.ELAN_GID_MIN * 2;
607 public static long getEtreeLeafLocalBCGId(long etreeLeafTag) {
608 return ElanConstants.ELAN_GID_MIN + (etreeLeafTag % ElanConstants.ELAN_GID_MIN * 2 - 1);
611 public static long getEtreeLeafRemoteBCGId(long etreeLeafTag) {
612 return ElanConstants.ELAN_GID_MIN + etreeLeafTag % ElanConstants.ELAN_GID_MIN * 2;
615 public static BigInteger getElanMetadataLabel(long elanTag, boolean isSHFlagSet) {
616 int shBit = isSHFlagSet ? 1 : 0;
617 return BigInteger.valueOf(elanTag).shiftLeft(24).or(BigInteger.valueOf(shBit));
621 * Setting SMAC, DMAC, UDMAC in this DPN and optionally in other DPNs.
625 * @param interfaceInfo
631 * @param configureRemoteFlows
632 * true if remote dmac flows should be configured as well
633 * @param writeFlowGroupTx
636 public void setupMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo,
637 long macTimeout, String macAddress, boolean configureRemoteFlows,
638 TypedWriteTransaction<Configuration> writeFlowGroupTx) {
639 synchronized (getElanMacDPNKey(elanInfo.getElanTag(), macAddress, interfaceInfo.getDpId())) {
640 setupKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress, mdsalManager,
642 setupOrigDmacFlows(elanInfo, interfaceInfo, macAddress, configureRemoteFlows, mdsalManager,
647 public void setupDMacFlowOnRemoteDpn(ElanInstance elanInfo, InterfaceInfo interfaceInfo, BigInteger dstDpId,
648 String macAddress, TypedWriteTransaction<Configuration> writeFlowTx) {
649 String elanInstanceName = elanInfo.getElanInstanceName();
650 setupRemoteDmacFlow(dstDpId, interfaceInfo.getDpId(), interfaceInfo.getInterfaceTag(), elanInfo.getElanTag(),
651 macAddress, elanInstanceName, writeFlowTx, interfaceInfo.getInterfaceName(), elanInfo);
652 LOG.info("Remote Dmac flow entry created for elan Name:{}, logical port Name:{} and"
653 + " mac address {} on dpn:{}", elanInstanceName, interfaceInfo.getPortName(),
654 macAddress, dstDpId);
658 * Inserts a Flow in SMAC table to state that the MAC has already been
661 private void setupKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
662 String macAddress, IMdsalApiManager mdsalApiManager,
663 TypedWriteTransaction<Configuration> writeFlowGroupTx) {
664 FlowEntity flowEntity = buildKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress);
665 mdsalApiManager.addFlow(writeFlowGroupTx, flowEntity);
666 LOG.debug("Known Smac flow entry created for elan Name:{}, logical Interface port:{} and mac address:{}",
667 elanInfo.getElanInstanceName(), elanInfo.getDescription(), macAddress);
670 public FlowEntity buildKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
672 int lportTag = interfaceInfo.getInterfaceTag();
673 // Matching metadata and eth_src fields
674 List<MatchInfo> mkMatches = new ArrayList<>();
675 mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanInfo.getElanTag(), lportTag),
676 ElanHelper.getElanMetadataMask()));
677 mkMatches.add(new MatchEthernetSource(new MacAddress(macAddress)));
678 List<InstructionInfo> mkInstructions = new ArrayList<>();
679 mkInstructions.add(new InstructionGotoTable(NwConstants.ELAN_DMAC_TABLE));
680 BigInteger dpId = interfaceInfo.getDpId();
681 long elanTag = getElanTag(elanInfo, interfaceInfo);
682 return new FlowEntityBuilder()
684 .setTableId(NwConstants.ELAN_SMAC_TABLE)
685 .setFlowId(getKnownDynamicmacFlowRef(NwConstants.ELAN_SMAC_TABLE, dpId, lportTag, macAddress, elanTag))
687 .setFlowName(elanInfo.getDescription())
688 .setIdleTimeOut((int) macTimeout)
690 .setCookie(ElanConstants.COOKIE_ELAN_KNOWN_SMAC.add(BigInteger.valueOf(elanTag)))
691 .setMatchInfoList(mkMatches)
692 .setInstructionInfoList(mkInstructions)
694 // If Mac timeout is 0, the flow won't be deleted automatically, so no need to get notified
695 .setSendFlowRemFlag(macTimeout != 0)
699 private Long getElanTag(ElanInstance elanInfo, InterfaceInfo interfaceInfo) {
700 EtreeInterface etreeInterface = elanInterfaceCache.getEtreeInterface(interfaceInfo.getInterfaceName()).orNull();
701 if (etreeInterface == null || etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
702 return elanInfo.getElanTag();
704 EtreeInstance etreeInstance = elanInfo.augmentation(EtreeInstance.class);
705 if (etreeInstance == null) {
706 LOG.warn("EtreeInterface {} is connected to a non-Etree network: {}",
707 interfaceInfo.getInterfaceName(), elanInfo.getElanInstanceName());
708 return elanInfo.getElanTag();
710 return etreeInstance.getEtreeLeafTagVal().getValue();
716 * Installs a Flow in INTERNAL_TUNNEL_TABLE of the affected DPN that sends
717 * the packet through the specified interface if the tunnel_id matches the
718 * interface's lportTag.
720 * @param interfaceInfo
722 * @param mdsalApiManager
723 * the mdsal API manager
724 * @param writeFlowGroupTx
725 * the writeFLowGroup tx
727 public void setupTermDmacFlows(InterfaceInfo interfaceInfo, IMdsalApiManager mdsalApiManager,
728 TypedWriteTransaction<Configuration> writeFlowGroupTx) {
729 BigInteger dpId = interfaceInfo.getDpId();
730 int lportTag = interfaceInfo.getInterfaceTag();
731 Flow flow = MDSALUtil.buildFlowNew(NwConstants.INTERNAL_TUNNEL_TABLE,
732 getIntTunnelTableFlowRef(NwConstants.INTERNAL_TUNNEL_TABLE, lportTag), 5,
733 String.format("%s:%d", "ITM Flow Entry ", lportTag), 0, 0,
734 ITMConstants.COOKIE_ITM.add(BigInteger.valueOf(lportTag)),
735 getTunnelIdMatchForFilterEqualsLPortTag(lportTag),
736 getInstructionsInPortForOutGroup(interfaceInfo.getInterfaceName()));
737 mdsalApiManager.addFlow(writeFlowGroupTx, dpId, flow);
738 LOG.debug("Terminating service table flow entry created on dpn:{} for logical Interface port:{}", dpId,
739 interfaceInfo.getPortName());
743 * Constructs the FlowName for flows installed in the Internal Tunnel Table,
744 * consisting in tableId + elanTag.
750 * @return the Internal tunnel
752 public static String getIntTunnelTableFlowRef(short tableId, int elanTag) {
753 return new StringBuffer().append(tableId).append(elanTag).toString();
757 * Constructs the Matches that checks that the tunnel_id field contains a
761 * lportTag that must be checked against the tunnel_id field
762 * @return the list of match Info
764 public static List<MatchInfo> getTunnelIdMatchForFilterEqualsLPortTag(int lportTag) {
765 List<MatchInfo> mkMatches = new ArrayList<>();
767 mkMatches.add(new MatchTunnelId(BigInteger.valueOf(lportTag)));
772 * Constructs the Instructions that take the packet over a given interface.
775 * Name of the interface where the packet must be sent over. It
776 * can be a local interface or a tunnel interface (internal or
778 * @return the Instruction
780 public List<Instruction> getInstructionsInPortForOutGroup(String ifName) {
781 List<Instruction> mkInstructions = new ArrayList<>();
782 List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
784 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
785 return mkInstructions;
789 * Returns the list of Actions to be taken when sending the packet through
790 * an Elan interface. Note that this interface can refer to an ElanInterface
791 * where the Elan VM is attached to a DPN or an ITM tunnel interface where
792 * Elan traffic can be sent through. In this latter case, the tunnelKey is
793 * mandatory and it can hold serviceId for internal tunnels or the VNI for
800 * @return the egress actions for interface
802 @SuppressWarnings("checkstyle:IllegalCatch")
803 public List<Action> getEgressActionsForInterface(String ifName, Long tunnelKey) {
804 List<Action> listAction = new ArrayList<>();
806 GetEgressActionsForInterfaceInput getEgressActionInput = new GetEgressActionsForInterfaceInputBuilder()
807 .setIntfName(ifName).setTunnelKey(tunnelKey).build();
808 Future<RpcResult<GetEgressActionsForInterfaceOutput>> result = interfaceManagerRpcService
809 .getEgressActionsForInterface(getEgressActionInput);
810 RpcResult<GetEgressActionsForInterfaceOutput> rpcResult = result.get();
811 if (!rpcResult.isSuccessful()) {
812 LOG.debug("RPC Call to Get egress actions for interface {} returned with Errors {}", ifName,
813 rpcResult.getErrors());
815 List<Action> actions = rpcResult.getResult().getAction();
816 listAction = actions;
818 } catch (Exception e) {
819 LOG.warn("Exception when egress actions for interface {}", ifName, e);
824 private void setupOrigDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
825 boolean configureRemoteFlows, IMdsalApiManager mdsalApiManager,
826 TypedWriteTransaction<Configuration> writeFlowGroupTx) {
827 BigInteger dpId = interfaceInfo.getDpId();
828 String ifName = interfaceInfo.getInterfaceName();
829 long ifTag = interfaceInfo.getInterfaceTag();
830 String elanInstanceName = elanInfo.getElanInstanceName();
832 Long elanTag = elanInfo.getElanTag();
834 setupLocalDmacFlow(elanTag, dpId, ifName, macAddress, elanInfo, mdsalApiManager, ifTag,
836 LOG.debug("Dmac flow entry created for elan Name:{}, logical port Name:{} mand mac address:{} "
837 + "on dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, dpId);
839 if (!configureRemoteFlows) {
843 List<DpnInterfaces> elanDpns = getInvolvedDpnsInElan(elanInstanceName);
844 for (DpnInterfaces elanDpn : elanDpns) {
846 if (elanDpn.getDpId().equals(dpId)) {
850 // Check for the Remote DPN present in Inventory Manager
851 if (!isDpnPresent(elanDpn.getDpId())) {
855 // For remote DPNs a flow is needed to indicate that packets of this ELAN going to this MAC need to be
856 // forwarded through the appropriate ITM tunnel
857 setupRemoteDmacFlow(elanDpn.getDpId(), // srcDpn (the remote DPN in this case)
858 dpId, // dstDpn (the local DPN)
859 interfaceInfo.getInterfaceTag(), // lportTag of the local interface
860 elanTag, // identifier of the Elan
861 macAddress, // MAC to be programmed in remote DPN
862 elanInstanceName, writeFlowGroupTx, ifName, elanInfo
864 LOG.debug("Remote Dmac flow entry created for elan Name:{}, logical port Name:{} and mac address:{} on"
865 + " dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, elanDpn.getDpId());
868 // TODO: Make sure that the same is performed against the ElanDevices.
872 public List<DpnInterfaces> getInvolvedDpnsInElan(String elanName) {
873 return getElanDPNByName(elanName);
877 public List<DpnInterfaces> getElanDPNByName(String elanInstanceName) {
878 InstanceIdentifier<ElanDpnInterfacesList> elanIdentifier = getElanDpnOperationDataPath(elanInstanceName);
879 return MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL, elanIdentifier).toJavaUtil().map(
880 ElanDpnInterfacesList::getDpnInterfaces).orElse(Collections.emptyList());
883 private void setupLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
884 ElanInstance elanInfo, IMdsalApiManager mdsalApiManager, long ifTag,
885 TypedWriteTransaction<Configuration> writeFlowGroupTx) {
886 Flow flowEntity = buildLocalDmacFlowEntry(elanTag, dpId, ifName, macAddress, elanInfo, ifTag);
887 mdsalApiManager.addFlow(writeFlowGroupTx, dpId, flowEntity);
888 installEtreeLocalDmacFlow(elanTag, dpId, ifName, macAddress, elanInfo, ifTag, writeFlowGroupTx);
891 private void installEtreeLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
892 ElanInstance elanInfo, long ifTag, TypedWriteTransaction<Configuration> writeFlowGroupTx) {
893 EtreeInterface etreeInterface = elanInterfaceCache.getEtreeInterface(ifName).orNull();
894 if (etreeInterface != null && etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
895 EtreeLeafTagName etreeTagName = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
896 if (etreeTagName == null) {
897 LOG.warn("Interface {} seems like it belongs to Etree but etreeTagName from elanTag {} is null",
900 Flow flowEntity = buildLocalDmacFlowEntry(etreeTagName.getEtreeLeafTag().getValue(), dpId, ifName,
901 macAddress, elanInfo, ifTag);
902 mdsalManager.addFlow(writeFlowGroupTx, dpId, flowEntity);
907 public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, long lporTag, String macAddress,
909 return String.valueOf(tableId) + elanTag + dpId + lporTag + macAddress;
912 public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, BigInteger remoteDpId,
913 String macAddress, long elanTag) {
914 return String.valueOf(tableId) + elanTag + dpId + remoteDpId + macAddress;
917 public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, String macAddress, long elanTag) {
918 return String.valueOf(tableId) + elanTag + dpId + macAddress;
921 public static String getKnownDynamicmacFlowRef(short elanDmacTable, BigInteger dpId, String extDeviceNodeId,
922 String dstMacAddress, long elanTag, boolean shFlag) {
923 return String.valueOf(elanDmacTable) + elanTag + dpId + extDeviceNodeId + dstMacAddress + shFlag;
927 * Builds the flow to be programmed in the DMAC table of the local DPN (that
928 * is, where the MAC is attached to). This flow consists in:
930 * <p>Match: + elanTag in metadata + packet goes to a MAC locally attached
931 * Actions: + optionally, pop-vlan + set-vlan-id + output to ifName's
948 public Flow buildLocalDmacFlowEntry(long elanTag, BigInteger dpId, String ifName, String macAddress,
949 ElanInstance elanInfo, long ifTag) {
951 List<MatchInfo> mkMatches = new ArrayList<>();
952 mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
953 mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddress)));
955 List<Instruction> mkInstructions = new ArrayList<>();
956 List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
957 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
958 Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
959 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, ifTag, macAddress, elanTag), 20,
960 elanInfo.getElanInstanceName(), 0, 0, ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(
961 BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
966 public void setupRemoteDmacFlow(BigInteger srcDpId, BigInteger destDpId, int lportTag, long elanTag,
967 String macAddress, String displayName, TypedWriteTransaction<Configuration> writeFlowGroupTx,
968 String interfaceName, ElanInstance elanInstance) {
969 if (interfaceManager.isExternalInterface(interfaceName)) {
970 LOG.debug("Ignoring install remote DMAC {} flow on provider interface {} elan {}",
971 macAddress, interfaceName, elanInstance.getElanInstanceName());
975 // if openstack-vni-semantics are enforced, segmentation ID is passed as network VNI for VxLAN based provider
976 // networks, 0 otherwise
977 long lportTagOrVni = !isOpenstackVniSemanticsEnforced() ? lportTag : isVxlanNetworkOrVxlanSegment(elanInstance)
978 ? getVxlanSegmentationId(elanInstance) : 0;
979 flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTagOrVni, elanTag, macAddress, displayName,
981 mdsalManager.addFlow(writeFlowGroupTx, srcDpId, flowEntity);
982 setupEtreeRemoteDmacFlow(srcDpId, destDpId, lportTagOrVni, elanTag, macAddress, displayName, interfaceName,
983 writeFlowGroupTx, elanInstance);
986 private void setupEtreeRemoteDmacFlow(BigInteger srcDpId, BigInteger destDpId, long lportTagOrVni, long elanTag,
987 String macAddress, String displayName, String interfaceName,
988 TypedWriteTransaction<Configuration> writeFlowGroupTx,
989 ElanInstance elanInstance) {
991 EtreeInterface etreeInterface = elanInterfaceCache.getEtreeInterface(interfaceName).orNull();
992 if (etreeInterface != null && etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
993 EtreeLeafTagName etreeTagName = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
994 if (etreeTagName == null) {
995 LOG.warn("Interface {} seems like it belongs to Etree but etreeTagName from elanTag {} is null.",
996 interfaceName, elanTag);
998 flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTagOrVni,
999 etreeTagName.getEtreeLeafTag().getValue(), macAddress, displayName, elanInstance);
1000 mdsalManager.addFlow(writeFlowGroupTx, srcDpId, flowEntity);
1006 * Builds a Flow to be programmed in a remote DPN's DMAC table. This flow
1007 * consists in: Match: + elanTag in packet's metadata + packet going to a
1008 * MAC known to be located in another DPN Actions: + set_tunnel_id
1009 * + output ITM internal tunnel interface with the other DPN
1015 * @param lportTagOrVni
1016 * lportTag or network VNI
1021 * @param displayName
1023 * @param elanInstance
1025 * @return the flow remote Dmac
1027 @SuppressWarnings("checkstyle:IllegalCatch")
1028 public Flow buildRemoteDmacFlowEntry(BigInteger srcDpId, BigInteger destDpId, long lportTagOrVni, long elanTag,
1029 String macAddress, String displayName, ElanInstance elanInstance) {
1030 List<MatchInfo> mkMatches = new ArrayList<>();
1031 mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
1032 mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddress)));
1034 List<Instruction> mkInstructions = new ArrayList<>();
1036 // List of Action for the provided Source and Destination DPIDs
1038 List<Action> actions = null;
1039 if (isVxlanNetworkOrVxlanSegment(elanInstance)) {
1040 actions = elanItmUtils.getInternalTunnelItmEgressAction(srcDpId, destDpId, lportTagOrVni);
1041 } else if (isVlan(elanInstance) || isFlat(elanInstance)) {
1042 String interfaceName = getExternalElanInterface(elanInstance.getElanInstanceName(), srcDpId);
1043 if (null == interfaceName) {
1044 LOG.info("buildRemoteDmacFlowEntry: Could not find interfaceName for {} {}", srcDpId,
1047 actions = getEgressActionsForInterface(interfaceName, null);
1049 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
1050 } catch (Exception e) {
1051 LOG.error("Could not get egress actions to add to flow for srcDpId {}, destDpId {}, lportTag/VNI {}",
1052 srcDpId, destDpId, lportTagOrVni, e);
1055 Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
1056 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, srcDpId, destDpId, macAddress, elanTag),
1058 displayName, 0, /* idleTimeout */
1059 0, /* hardTimeout */
1060 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
1066 public void deleteMacFlows(@Nullable ElanInstance elanInfo, @Nullable InterfaceInfo interfaceInfo,
1067 MacEntry macEntry, TypedReadWriteTransaction<Configuration> flowTx)
1068 throws ExecutionException, InterruptedException {
1069 if (elanInfo == null || interfaceInfo == null) {
1072 String macAddress = macEntry.getMacAddress().getValue();
1073 synchronized (getElanMacDPNKey(elanInfo.getElanTag(), macAddress, interfaceInfo.getDpId())) {
1074 deleteMacFlows(elanInfo, interfaceInfo, macAddress, /* alsoDeleteSMAC */ true, flowTx);
1078 public void deleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1079 boolean deleteSmac, TypedReadWriteTransaction<Configuration> flowTx)
1080 throws ExecutionException, InterruptedException {
1081 String elanInstanceName = elanInfo.getElanInstanceName();
1082 List<DpnInterfaces> remoteFEs = getInvolvedDpnsInElan(elanInstanceName);
1083 BigInteger srcdpId = interfaceInfo.getDpId();
1084 boolean isFlowsRemovedInSrcDpn = false;
1085 for (DpnInterfaces dpnInterface : remoteFEs) {
1086 Long elanTag = elanInfo.getElanTag();
1087 BigInteger dstDpId = dpnInterface.getDpId();
1088 if (executeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1089 elanTag, dstDpId, flowTx)) {
1090 isFlowsRemovedInSrcDpn = true;
1092 executeEtreeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1093 elanTag, dstDpId, flowTx);
1095 if (!isFlowsRemovedInSrcDpn) {
1096 deleteSmacAndDmacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, flowTx);
1100 private void executeEtreeDeleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1101 boolean deleteSmac, String elanInstanceName, BigInteger srcdpId, Long elanTag, BigInteger dstDpId,
1102 TypedReadWriteTransaction<Configuration> flowTx) throws ExecutionException, InterruptedException {
1103 EtreeLeafTagName etreeLeafTag = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
1104 if (etreeLeafTag != null) {
1105 executeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1106 etreeLeafTag.getEtreeLeafTag().getValue(), dstDpId, flowTx);
1110 private boolean executeDeleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1111 boolean deleteSmac, String elanInstanceName, BigInteger srcdpId, Long elanTag, BigInteger dstDpId,
1112 TypedReadWriteTransaction<Configuration> flowTx) throws ExecutionException, InterruptedException {
1113 boolean isFlowsRemovedInSrcDpn = false;
1114 if (dstDpId.equals(srcdpId)) {
1115 isFlowsRemovedInSrcDpn = true;
1116 deleteSmacAndDmacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, flowTx);
1117 } else if (isDpnPresent(dstDpId)) {
1119 .removeFlow(flowTx, dstDpId,
1120 MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, getKnownDynamicmacFlowRef(
1121 NwConstants.ELAN_DMAC_TABLE, dstDpId, srcdpId, macAddress, elanTag)));
1122 LOG.debug("Dmac flow entry deleted for elan:{}, logical interface port:{} and mac address:{} on dpn:{}",
1123 elanInstanceName, interfaceInfo.getPortName(), macAddress, dstDpId);
1125 return isFlowsRemovedInSrcDpn;
1128 private void deleteSmacAndDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1129 boolean deleteSmac, TypedReadWriteTransaction<Configuration> flowTx)
1130 throws ExecutionException, InterruptedException {
1131 String elanInstanceName = elanInfo.getElanInstanceName();
1132 long ifTag = interfaceInfo.getInterfaceTag();
1133 BigInteger srcdpId = interfaceInfo.getDpId();
1134 Long elanTag = elanInfo.getElanTag();
1137 .removeFlow(flowTx, srcdpId,
1138 MDSALUtil.buildFlow(NwConstants.ELAN_SMAC_TABLE, getKnownDynamicmacFlowRef(
1139 NwConstants.ELAN_SMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)));
1141 mdsalManager.removeFlow(flowTx, srcdpId,
1142 MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE,
1143 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)));
1144 LOG.debug("All the required flows deleted for elan:{}, logical Interface port:{} and MAC address:{} on dpn:{}",
1145 elanInstanceName, interfaceInfo.getPortName(), macAddress, srcdpId);
1149 * Updates the Elan information in the Operational DS. It also updates the
1150 * ElanInstance in the Config DS by setting the adquired elanTag.
1154 * @param elanInstanceAdded
1155 * the elan instance added
1156 * @param elanInterfaces
1157 * the elan interfaces
1161 * @return the updated ELAN instance.
1163 public static ElanInstance updateOperationalDataStore(IdManagerService idManager,
1164 ElanInstance elanInstanceAdded, List<String> elanInterfaces, TypedWriteTransaction<Configuration> confTx,
1165 TypedWriteTransaction<Operational> operTx) {
1166 String elanInstanceName = elanInstanceAdded.getElanInstanceName();
1167 Long elanTag = elanInstanceAdded.getElanTag();
1168 if (elanTag == null || elanTag == 0L) {
1169 elanTag = retrieveNewElanTag(idManager, elanInstanceName);
1171 Elan elanInfo = new ElanBuilder().setName(elanInstanceName).setElanInterfaces(elanInterfaces)
1172 .withKey(new ElanKey(elanInstanceName)).build();
1174 // Add the ElanState in the elan-state operational data-store
1175 operTx.put(getElanInstanceOperationalDataPath(elanInstanceName), elanInfo, CREATE_MISSING_PARENTS);
1177 // Add the ElanMacTable in the elan-mac-table operational data-store
1178 MacTable elanMacTable = new MacTableBuilder().withKey(new MacTableKey(elanInstanceName)).build();
1179 operTx.put(getElanMacTableOperationalDataPath(elanInstanceName), elanMacTable, CREATE_MISSING_PARENTS);
1181 ElanTagNameBuilder elanTagNameBuilder = new ElanTagNameBuilder().setElanTag(elanTag)
1182 .withKey(new ElanTagNameKey(elanTag)).setName(elanInstanceName);
1183 long etreeLeafTag = -1;
1184 if (isEtreeInstance(elanInstanceAdded)) {
1185 etreeLeafTag = retrieveNewElanTag(idManager,elanInstanceName + ElanConstants
1187 EtreeLeafTagName etreeLeafTagName = new EtreeLeafTagNameBuilder()
1188 .setEtreeLeafTag(new EtreeLeafTag(etreeLeafTag)).build();
1189 elanTagNameBuilder.addAugmentation(EtreeLeafTagName.class, etreeLeafTagName);
1190 addTheLeafTagAsElanTag(elanInstanceName, etreeLeafTag, operTx);
1192 ElanTagName elanTagName = elanTagNameBuilder.build();
1194 // Add the ElanTag to ElanName in the elan-tag-name Operational
1196 operTx.put(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 confTx.merge(ElanHelper.getElanInstanceConfigurationDataPath(elanInstanceName), elanInstanceWithTag,
1212 CREATE_MISSING_PARENTS);
1213 return elanInstanceWithTag;
1216 private static void addTheLeafTagAsElanTag(String elanInstanceName, long etreeLeafTag,
1217 TypedWriteTransaction<Operational> tx) {
1218 ElanTagName etreeTagAsElanTag = new ElanTagNameBuilder().setElanTag(etreeLeafTag)
1219 .withKey(new ElanTagNameKey(etreeLeafTag)).setName(elanInstanceName).build();
1220 tx.put(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);
1422 public static ListenableFuture<Void> waitForTransactionToComplete(ListenableFuture<Void> future) {
1425 } catch (InterruptedException | ExecutionException e) {
1426 // NETVIRT-1215: Do not log.error() here, only debug(); but callers *MUST* @CheckReturnValue
1427 LOG.debug("Error writing to datastore", e);
1432 public static boolean isVxlan(@Nullable ElanInstance elanInstance) {
1433 return elanInstance != null && elanInstance.getSegmentType() != null
1434 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1435 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId() != 0;
1438 private static boolean isVxlanSegment(ElanInstance elanInstance) {
1439 if (elanInstance != null) {
1440 List<ElanSegments> elanSegments = elanInstance.getElanSegments();
1441 if (elanSegments != null) {
1442 for (ElanSegments segment : elanSegments) {
1443 if (segment != null && segment.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1444 && segment.getSegmentationId() != null
1445 && segment.getSegmentationId().longValue() != 0) {
1454 public static boolean isVxlanNetworkOrVxlanSegment(ElanInstance elanInstance) {
1455 return isVxlan(elanInstance) || isVxlanSegment(elanInstance);
1458 public static Long getVxlanSegmentationId(ElanInstance elanInstance) {
1459 Long segmentationId = 0L;
1460 if (elanInstance == null) {
1461 return segmentationId;
1464 if (elanInstance.getSegmentType() != null
1465 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1466 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId().longValue() != 0) {
1467 segmentationId = elanInstance.getSegmentationId();
1469 for (ElanSegments segment: elanInstance.getElanSegments()) {
1470 if (segment != null && segment.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1471 && segment.getSegmentationId() != null
1472 && segment.getSegmentationId().longValue() != 0) {
1473 segmentationId = segment.getSegmentationId();
1477 return segmentationId;
1480 public static boolean isVlan(ElanInstance elanInstance) {
1481 return elanInstance != null && elanInstance.getSegmentType() != null
1482 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVlan.class)
1483 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId() != 0;
1486 public static boolean isFlat(ElanInstance elanInstance) {
1487 return elanInstance != null && elanInstance.getSegmentType() != null
1488 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeFlat.class);
1491 public void addDmacRedirectToDispatcherFlows(Long elanTag, String displayName,
1492 String macAddress, List<BigInteger> dpnIds) {
1493 for (BigInteger dpId : dpnIds) {
1494 ListenableFutures.addErrorLogging(txRunner.callWithNewWriteOnlyTransactionAndSubmit(CONFIGURATION,
1495 tx -> mdsalManager.addFlow(tx, buildDmacRedirectToDispatcherFlow(dpId, macAddress, displayName,
1497 "Error adding DMAC redirect to dispatcher flows");
1501 public void removeDmacRedirectToDispatcherFlows(Long elanTag, String macAddress, List<BigInteger> dpnIds) {
1502 ListenableFutures.addErrorLogging(
1503 txRunner.callWithNewReadWriteTransactionAndSubmit(Datastore.CONFIGURATION, tx -> {
1504 for (BigInteger dpId : dpnIds) {
1505 String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, macAddress, elanTag);
1506 mdsalManager.removeFlow(tx, dpId, MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, flowId));
1508 }), LOG, "Error removing DMAC redirect to dispatcher flows");
1511 public static FlowEntity buildDmacRedirectToDispatcherFlow(BigInteger dpId, String dstMacAddress,
1512 String displayName, long elanTag) {
1513 List<MatchInfo> matches = new ArrayList<>();
1514 matches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
1515 matches.add(new MatchEthernetDestination(new MacAddress(dstMacAddress)));
1516 List<InstructionInfo> instructions = new ArrayList<>();
1517 List<ActionInfo> actions = new ArrayList<>();
1518 actions.add(new ActionNxResubmit(NwConstants.LPORT_DISPATCHER_TABLE));
1520 instructions.add(new InstructionApplyActions(actions));
1521 String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, dstMacAddress, elanTag);
1522 return MDSALUtil.buildFlowEntity(dpId, NwConstants.ELAN_DMAC_TABLE, flowId, 20, displayName, 0, 0,
1523 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)),
1524 matches, instructions);
1527 public String getExternalElanInterface(String elanInstanceName, BigInteger dpnId) {
1528 DpnInterfaces dpnInterfaces = getElanInterfaceInfoByElanDpn(elanInstanceName, dpnId);
1529 if (dpnInterfaces == null || dpnInterfaces.getInterfaces() == null) {
1530 LOG.trace("Elan {} does not have interfaces in DPN {}", elanInstanceName, dpnId);
1534 for (String dpnInterface : dpnInterfaces.getInterfaces()) {
1535 if (interfaceManager.isExternalInterface(dpnInterface)) {
1536 return dpnInterface;
1540 LOG.trace("Elan {} does not have any external interace attached to DPN {}", elanInstanceName, dpnId);
1544 public static String getElanMacDPNKey(long elanTag, String macAddress, BigInteger dpnId) {
1545 String elanMacDmacDpnKey = "MAC-" + macAddress + " ELAN_TAG-" + elanTag + "DPN_ID-" + dpnId;
1546 return elanMacDmacDpnKey.intern();
1549 public static String getElanMacKey(long elanTag, String macAddress) {
1550 String elanMacKey = "MAC-" + macAddress + " ELAN_TAG-" + elanTag;
1551 return elanMacKey.intern();
1554 public static List<ListenableFuture<Void>>
1555 returnFailedListenableFutureIfTransactionCommitFailedExceptionCauseOrElseThrow(RuntimeException exception) {
1557 Throwable cause = exception.getCause();
1558 if (cause != null && cause instanceof TransactionCommitFailedException) {
1559 return Collections.singletonList(Futures.immediateFailedFuture(cause));
1565 public static List<PhysAddress> getPhysAddress(List<String> macAddress) {
1566 Preconditions.checkNotNull(macAddress, "macAddress cannot be null");
1567 List<PhysAddress> physAddresses = new ArrayList<>();
1568 for (String mac : macAddress) {
1569 physAddresses.add(new PhysAddress(mac));
1571 return physAddresses;
1574 public static List<StaticMacEntries> getStaticMacEntries(List<String> staticMacAddresses) {
1575 if (isEmpty(staticMacAddresses)) {
1576 return Collections.EMPTY_LIST;
1578 StaticMacEntriesBuilder staticMacEntriesBuilder = new StaticMacEntriesBuilder();
1579 List<StaticMacEntries> staticMacEntries = new ArrayList<>();
1580 List<PhysAddress> physAddressList = getPhysAddress(staticMacAddresses);
1581 for (PhysAddress physAddress : physAddressList) {
1582 staticMacEntries.add(staticMacEntriesBuilder.setMacAddress(physAddress).build());
1584 return staticMacEntries;
1587 public static InstanceIdentifier<StaticMacEntries> getStaticMacEntriesCfgDataPathIdentifier(String interfaceName,
1588 String macAddress) {
1589 return InstanceIdentifier.builder(ElanInterfaces.class)
1590 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).child(StaticMacEntries.class,
1591 new StaticMacEntriesKey(new PhysAddress(macAddress))).build();
1594 public static List<StaticMacEntries> getDeletedEntries(List<StaticMacEntries> originalStaticMacEntries,
1595 List<StaticMacEntries> updatedStaticMacEntries) {
1596 if (isEmpty(originalStaticMacEntries)) {
1597 return Collections.EMPTY_LIST;
1599 List<StaticMacEntries> deleted = Lists.newArrayList(originalStaticMacEntries);
1600 if (isNotEmpty(updatedStaticMacEntries)) {
1601 deleted.removeAll(updatedStaticMacEntries);
1606 public static <T> List<T> diffOf(List<T> orig, List<T> updated) {
1607 if (isEmpty(orig)) {
1608 return Collections.EMPTY_LIST;
1610 List<T> diff = Lists.newArrayList(orig);
1611 if (isNotEmpty(updated)) {
1612 diff.removeAll(updated);
1617 public static void segregateToBeDeletedAndAddEntries(List<StaticMacEntries> originalStaticMacEntries,
1618 List<StaticMacEntries> updatedStaticMacEntries) {
1619 if (isNotEmpty(updatedStaticMacEntries)) {
1620 List<StaticMacEntries> existingClonedStaticMacEntries = new ArrayList<>();
1621 if (isNotEmpty(originalStaticMacEntries)) {
1622 existingClonedStaticMacEntries.addAll(0, originalStaticMacEntries);
1623 originalStaticMacEntries.removeAll(updatedStaticMacEntries);
1624 updatedStaticMacEntries.removeAll(existingClonedStaticMacEntries);
1629 public static boolean isEmpty(Collection collection) {
1630 return collection == null || collection.isEmpty();
1633 public static boolean isNotEmpty(Collection collection) {
1634 return !isEmpty(collection);
1637 public Optional<IpAddress> getSourceIpAddress(Ethernet ethernet) {
1638 Optional<IpAddress> srcIpAddress = Optional.absent();
1639 if (ethernet.getPayload() == null) {
1640 return srcIpAddress;
1642 byte[] ipAddrBytes = null;
1643 if (ethernet.getPayload() instanceof IPv4) {
1644 IPv4 ipv4 = (IPv4) ethernet.getPayload();
1645 ipAddrBytes = Ints.toByteArray(ipv4.getSourceAddress());
1646 } else if (ethernet.getPayload() instanceof ARP) {
1647 ipAddrBytes = ((ARP) ethernet.getPayload()).getSenderProtocolAddress();
1649 if (ipAddrBytes != null) {
1650 String ipAddr = NWUtil.toStringIpAddress(ipAddrBytes);
1651 return Optional.of(IpAddressBuilder.getDefaultInstance(ipAddr));
1653 return srcIpAddress;
1656 public List<MacEntry> getElanMacEntries(String elanName) {
1657 MacTable macTable = getElanMacTable(elanName);
1658 if (macTable == null) {
1659 return Collections.emptyList();
1661 return macTable.getMacEntry();
1664 public boolean isTunnelInLogicalGroup(String interfaceName) {
1665 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1666 .ietf.interfaces.rev140508.interfaces.Interface configIface =
1667 interfaceManager.getInterfaceInfoFromConfigDataStore(interfaceName);
1668 if (configIface == null) {
1669 configIface = iitmProvider.getInterface(interfaceName);
1671 if (configIface == null) {
1674 IfTunnel ifTunnel = configIface.augmentation(IfTunnel.class);
1675 if (ifTunnel != null && ifTunnel.getTunnelInterfaceType().isAssignableFrom(TunnelTypeVxlan.class)) {
1676 ParentRefs refs = configIface.augmentation(ParentRefs.class);
1677 return refs != null && !Strings.isNullOrEmpty(refs.getParentInterface());
1682 public static InstanceIdentifier<Flow> getFlowIid(Flow flow, BigInteger dpnId) {
1683 FlowKey flowKey = new FlowKey(new FlowId(flow.getId()));
1684 org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId nodeId =
1685 new org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId("openflow:" + dpnId);
1686 org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node nodeDpn =
1687 new NodeBuilder().setId(nodeId).withKey(new NodeKey(nodeId)).build();
1688 return InstanceIdentifier.builder(Nodes.class)
1689 .child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node.class,
1690 nodeDpn.key()).augmentation(FlowCapableNode.class)
1691 .child(Table.class, new TableKey(flow.getTableId())).child(Flow.class, flowKey).build();
1694 public static String getElanInterfaceJobKey(String interfaceName) {
1695 return "elaninterface-" + interfaceName;
1698 public void removeArpResponderFlow(BigInteger dpnId, String ingressInterfaceName, String ipAddress,
1700 LOG.info("Removing the ARP responder flow on DPN {} of Interface {} with IP {}", dpnId, ingressInterfaceName,
1702 ListenableFutures.addErrorLogging(txRunner.callWithNewReadWriteTransactionAndSubmit(Datastore.CONFIGURATION,
1703 tx -> mdsalManager.removeFlow(tx, dpnId, ArpResponderUtil.getFlowId(lportTag, ipAddress),
1704 NwConstants.ARP_RESPONDER_TABLE)), LOG, "Error removing ARP responder flow");
1707 public static String getRouterPordIdFromElanInstance(DataBroker dataBroker, String elanInstanceName) {
1708 Optional<Subnetmaps> subnetMapsData =
1709 read(dataBroker, LogicalDatastoreType.CONFIGURATION, buildSubnetMapsWildCardPath());
1710 if (subnetMapsData.isPresent()) {
1711 List<Subnetmap> subnetMapList = subnetMapsData.get().getSubnetmap();
1712 if (subnetMapList != null && !subnetMapList.isEmpty()) {
1713 for (Subnetmap subnet : subnetMapList) {
1714 if (subnet.getNetworkId().getValue().equals(elanInstanceName)) {
1715 if (subnet.getRouterInterfacePortId() != null) {
1716 return subnet.getRouterInterfacePortId().getValue();
1725 static InstanceIdentifier<Subnetmaps> buildSubnetMapsWildCardPath() {
1726 return InstanceIdentifier.create(Subnetmaps.class);
1729 public static InstanceIdentifier<Group> getGroupInstanceid(BigInteger dpnId, long groupId) {
1730 return InstanceIdentifier.builder(Nodes.class).child(Node.class, new NodeKey(new NodeId("openflow:" + dpnId)))
1731 .augmentation(FlowCapableNode.class).child(Group.class, new GroupKey(new GroupId(groupId))).build();