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.Configuration;
46 import org.opendaylight.genius.infra.Datastore.Operational;
47 import org.opendaylight.genius.infra.ManagedNewTransactionRunner;
48 import org.opendaylight.genius.infra.ManagedNewTransactionRunnerImpl;
49 import org.opendaylight.genius.infra.TypedReadTransaction;
50 import org.opendaylight.genius.infra.TypedReadWriteTransaction;
51 import org.opendaylight.genius.infra.TypedWriteTransaction;
52 import org.opendaylight.genius.interfacemanager.globals.InterfaceInfo;
53 import org.opendaylight.genius.interfacemanager.globals.InterfaceServiceUtil;
54 import org.opendaylight.genius.interfacemanager.interfaces.IInterfaceManager;
55 import org.opendaylight.genius.itm.api.IITMProvider;
56 import org.opendaylight.genius.itm.globals.ITMConstants;
57 import org.opendaylight.genius.mdsalutil.ActionInfo;
58 import org.opendaylight.genius.mdsalutil.FlowEntity;
59 import org.opendaylight.genius.mdsalutil.FlowEntityBuilder;
60 import org.opendaylight.genius.mdsalutil.InstructionInfo;
61 import org.opendaylight.genius.mdsalutil.MDSALUtil;
62 import org.opendaylight.genius.mdsalutil.MatchInfo;
63 import org.opendaylight.genius.mdsalutil.MetaDataUtil;
64 import org.opendaylight.genius.mdsalutil.NWUtil;
65 import org.opendaylight.genius.mdsalutil.NwConstants;
66 import org.opendaylight.genius.mdsalutil.actions.ActionNxResubmit;
67 import org.opendaylight.genius.mdsalutil.instructions.InstructionApplyActions;
68 import org.opendaylight.genius.mdsalutil.instructions.InstructionGotoTable;
69 import org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager;
70 import org.opendaylight.genius.mdsalutil.matches.MatchEthernetDestination;
71 import org.opendaylight.genius.mdsalutil.matches.MatchEthernetSource;
72 import org.opendaylight.genius.mdsalutil.matches.MatchMetadata;
73 import org.opendaylight.genius.mdsalutil.matches.MatchTunnelId;
74 import org.opendaylight.genius.mdsalutil.packet.ARP;
75 import org.opendaylight.genius.mdsalutil.packet.Ethernet;
76 import org.opendaylight.genius.mdsalutil.packet.IPv4;
77 import org.opendaylight.infrautils.utils.concurrent.JdkFutures;
78 import org.opendaylight.infrautils.utils.concurrent.ListenableFutures;
79 import org.opendaylight.netvirt.elan.arp.responder.ArpResponderUtil;
80 import org.opendaylight.netvirt.elan.cache.ElanInterfaceCache;
81 import org.opendaylight.netvirt.elanmanager.api.ElanHelper;
82 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
83 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddressBuilder;
84 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfacesState;
85 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface;
86 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.AdminStatus;
87 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.OperStatus;
88 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
89 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.PhysAddress;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
96 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
97 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
98 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInput;
99 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInputBuilder;
100 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdOutput;
101 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdManagerService;
102 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInput;
103 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInputBuilder;
104 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406.IfIndexesInterfaceMap;
105 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._if.indexes._interface.map.IfIndexInterface;
106 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._if.indexes._interface.map.IfIndexInterfaceKey;
107 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfTunnel;
108 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.ParentRefs;
109 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeBase;
110 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeVxlan;
111 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceInput;
112 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceInputBuilder;
113 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceOutput;
114 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.OdlInterfaceRpcService;
115 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceBindings;
116 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceModeIngress;
117 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceTypeFlowBased;
118 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflow;
119 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflowBuilder;
120 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.ServicesInfo;
121 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.ServicesInfoKey;
122 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServices;
123 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesBuilder;
124 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesKey;
125 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.ExternalTunnelList;
126 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnel;
127 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnelKey;
128 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.ItmRpcService;
129 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsInput;
130 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsInputBuilder;
131 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsOutput;
132 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupId;
133 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group;
134 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupKey;
135 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
136 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
137 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
138 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
139 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
140 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.config.rev150710.ElanConfig;
141 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInstance;
142 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInstanceBuilder;
143 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInterface;
144 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInterface.EtreeInterfaceType;
145 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTag;
146 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTagName;
147 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTagNameBuilder;
148 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanDpnInterfaces;
149 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanForwardingTables;
150 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInstances;
151 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaceForwardingEntries;
152 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaces;
153 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanState;
154 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanTagNameMap;
155 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeFlat;
156 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeVlan;
157 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeVxlan;
158 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan._interface.forwarding.entries.ElanInterfaceMac;
159 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan._interface.forwarding.entries.ElanInterfaceMacKey;
160 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesList;
161 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesListKey;
162 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfaces;
163 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfacesKey;
164 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTable;
165 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTableBuilder;
166 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTableKey;
167 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstance;
168 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstanceBuilder;
169 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.elan.instance.ElanSegments;
170 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterface;
171 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterfaceKey;
172 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntries;
173 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntriesBuilder;
174 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntriesKey;
175 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.Elan;
176 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.ElanBuilder;
177 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.ElanKey;
178 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagName;
179 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagNameBuilder;
180 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagNameKey;
181 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntry;
182 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntryKey;
183 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.Subnetmaps;
184 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.subnetmaps.Subnetmap;
185 import org.opendaylight.yangtools.yang.binding.DataObject;
186 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
187 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.InstanceIdentifierBuilder;
188 import org.opendaylight.yangtools.yang.common.RpcResult;
189 import org.slf4j.Logger;
190 import org.slf4j.LoggerFactory;
193 public class ElanUtils {
195 private static final Logger LOG = LoggerFactory.getLogger(ElanUtils.class);
197 private final DataBroker broker;
198 private final ManagedNewTransactionRunner txRunner;
199 private final IMdsalApiManager mdsalManager;
200 private final OdlInterfaceRpcService interfaceManagerRpcService;
201 private final ItmRpcService itmRpcService;
202 private final IInterfaceManager interfaceManager;
203 private final ElanConfig elanConfig;
204 private final ElanItmUtils elanItmUtils;
205 private final ElanEtreeUtils elanEtreeUtils;
206 private final ElanInterfaceCache elanInterfaceCache;
207 private final IITMProvider iitmProvider;
209 public static final FutureCallback<Void> DEFAULT_CALLBACK = new FutureCallback<Void>() {
211 public void onSuccess(Void result) {
212 LOG.debug("Success in Datastore operation");
216 public void onFailure(Throwable error) {
217 LOG.error("Error in Datastore operation", error);
222 public ElanUtils(DataBroker dataBroker, IMdsalApiManager mdsalManager,
223 OdlInterfaceRpcService interfaceManagerRpcService, ItmRpcService itmRpcService, ElanConfig elanConfig,
224 IInterfaceManager interfaceManager, ElanEtreeUtils elanEtreeUtils, ElanItmUtils elanItmUtils,
225 ElanInterfaceCache elanInterfaceCache, IITMProvider iitmProvider) {
226 this.broker = dataBroker;
227 this.txRunner = new ManagedNewTransactionRunnerImpl(dataBroker);
228 this.mdsalManager = mdsalManager;
229 this.interfaceManagerRpcService = interfaceManagerRpcService;
230 this.itmRpcService = itmRpcService;
231 this.interfaceManager = interfaceManager;
232 this.elanConfig = elanConfig;
233 this.elanEtreeUtils = elanEtreeUtils;
234 this.elanItmUtils = elanItmUtils;
235 this.elanInterfaceCache = elanInterfaceCache;
236 this.iitmProvider = iitmProvider;
239 public final Boolean isOpenstackVniSemanticsEnforced() {
240 return elanConfig.isOpenstackVniSemanticsEnforced() != null
241 ? elanConfig.isOpenstackVniSemanticsEnforced() : false;
245 * Uses the IdManager to retrieve a brand new ElanTag.
251 * @return the integer
253 public static Long retrieveNewElanTag(IdManagerService idManager, String idKey) {
255 AllocateIdInput getIdInput = new AllocateIdInputBuilder().setPoolName(ElanConstants.ELAN_ID_POOL_NAME)
256 .setIdKey(idKey).build();
259 Future<RpcResult<AllocateIdOutput>> result = idManager.allocateId(getIdInput);
260 RpcResult<AllocateIdOutput> rpcResult = result.get();
261 if (rpcResult.isSuccessful()) {
262 return rpcResult.getResult().getIdValue();
264 LOG.warn("RPC Call to Allocate Id returned with Errors {}", rpcResult.getErrors());
266 } catch (InterruptedException | ExecutionException e) {
267 LOG.warn("Exception when Allocating Id", e);
272 public static void releaseId(IdManagerService idManager, String poolName, String idKey) {
273 ReleaseIdInput releaseIdInput = new ReleaseIdInputBuilder().setPoolName(poolName).setIdKey(idKey).build();
274 JdkFutures.addErrorLogging(idManager.releaseId(releaseIdInput), LOG, "Release Id");
280 * @deprecated Consider using {@link #read2(LogicalDatastoreType, InstanceIdentifier)} with proper exception
282 * @param broker dataBroker
283 * @param datastoreType Logical DataStore type
284 * @param path IID to read
285 * @param <T> T extends DataObject
286 * @return the read value T
289 @SuppressWarnings("checkstyle:IllegalCatch")
290 public static <T extends DataObject> Optional<T> read(@Nonnull DataBroker broker,
291 LogicalDatastoreType datastoreType, InstanceIdentifier<T> path) {
292 try (ReadOnlyTransaction tx = broker.newReadOnlyTransaction()) {
293 return tx.read(datastoreType, path).get();
294 } catch (Exception e) {
295 throw new RuntimeException(e);
299 public <T extends DataObject> Optional<T> read2(LogicalDatastoreType datastoreType, InstanceIdentifier<T> path)
300 throws ReadFailedException {
301 try (ReadOnlyTransaction tx = broker.newReadOnlyTransaction()) {
302 CheckedFuture<Optional<T>, ReadFailedException> checkedFuture = tx.read(datastoreType, path);
303 return checkedFuture.checkedGet();
307 @SuppressWarnings("checkstyle:ForbidCertainMethod")
308 public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
309 InstanceIdentifier<T> path) {
310 WriteTransaction tx = broker.newWriteOnlyTransaction();
311 tx.delete(datastoreType, path);
312 Futures.addCallback(tx.submit(), DEFAULT_CALLBACK, MoreExecutors.directExecutor());
315 @SuppressWarnings("checkstyle:ForbidCertainMethod")
316 public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
317 InstanceIdentifier<T> path, FutureCallback<Void> callback) {
318 WriteTransaction tx = broker.newWriteOnlyTransaction();
319 tx.delete(datastoreType, path);
320 Futures.addCallback(tx.submit(), callback, MoreExecutors.directExecutor());
323 public static InstanceIdentifier<ElanInstance> getElanInstanceIdentifier() {
324 return InstanceIdentifier.builder(ElanInstances.class).child(ElanInstance.class).build();
327 public static InstanceIdentifier<ElanInterface> getElanInterfaceConfigurationDataPathId(String interfaceName) {
328 return InstanceIdentifier.builder(ElanInterfaces.class)
329 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).build();
332 // elan-state Operational container
333 public static Elan getElanByName(DataBroker broker, String elanInstanceName) {
334 InstanceIdentifier<Elan> elanIdentifier = getElanInstanceOperationalDataPath(elanInstanceName);
335 return MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL, elanIdentifier).orNull();
339 public static Elan getElanByName(TypedReadTransaction<Operational> tx, String elanInstanceName)
340 throws ExecutionException, InterruptedException {
341 return tx.read(getElanInstanceOperationalDataPath(elanInstanceName)).get().orNull();
344 public static InstanceIdentifier<Elan> getElanInstanceOperationalDataPath(String elanInstanceName) {
345 return InstanceIdentifier.builder(ElanState.class).child(Elan.class, new ElanKey(elanInstanceName)).build();
348 // grouping of forwarding-entries
349 public MacEntry getInterfaceMacEntriesOperationalDataPath(String interfaceName, PhysAddress physAddress) {
350 InstanceIdentifier<MacEntry> existingMacEntryId = getInterfaceMacEntriesIdentifierOperationalDataPath(
351 interfaceName, physAddress);
352 return read(broker, LogicalDatastoreType.OPERATIONAL, existingMacEntryId).orNull();
355 public MacEntry getInterfaceMacEntriesOperationalDataPathFromId(InstanceIdentifier identifier) {
356 Optional<MacEntry> existingInterfaceMacEntry = read(broker,
357 LogicalDatastoreType.OPERATIONAL, identifier);
358 return existingInterfaceMacEntry.orNull();
361 public MacEntry getInterfaceMacEntriesOperationalDataPathFromId(TypedReadTransaction<Operational> tx,
362 InstanceIdentifier<MacEntry> identifier) throws ExecutionException, InterruptedException {
363 return tx.read(identifier).get().orNull();
366 public static InstanceIdentifier<MacEntry> getInterfaceMacEntriesIdentifierOperationalDataPath(String interfaceName,
367 PhysAddress physAddress) {
368 return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class)
369 .child(ElanInterfaceMac.class, new ElanInterfaceMacKey(interfaceName))
370 .child(MacEntry.class, new MacEntryKey(physAddress)).build();
374 // elan-forwarding-tables Operational container
375 public Optional<MacEntry> getMacEntryForElanInstance(String elanName, PhysAddress physAddress) {
376 InstanceIdentifier<MacEntry> macId = getMacEntryOperationalDataPath(elanName, physAddress);
377 return read(broker, LogicalDatastoreType.OPERATIONAL, macId);
380 public Optional<MacEntry> getMacEntryForElanInstance(TypedReadTransaction<Operational> tx, String elanName,
381 PhysAddress physAddress) throws ExecutionException, InterruptedException {
382 InstanceIdentifier<MacEntry> macId = getMacEntryOperationalDataPath(elanName, physAddress);
383 return tx.read(macId).get();
386 public MacEntry getMacEntryFromElanMacId(InstanceIdentifier identifier) {
387 Optional<MacEntry> existingInterfaceMacEntry = read(broker,
388 LogicalDatastoreType.OPERATIONAL, identifier);
389 return existingInterfaceMacEntry.orNull();
392 public MacEntry getMacEntryFromElanMacId(TypedReadTransaction<Operational> tx,
393 InstanceIdentifier<MacEntry> identifier) throws ExecutionException, InterruptedException {
394 return tx.read(identifier).get().orNull();
397 public static InstanceIdentifier<MacEntry> getMacEntryOperationalDataPath(String elanName,
398 PhysAddress physAddress) {
399 return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class, new MacTableKey(elanName))
400 .child(MacEntry.class, new MacEntryKey(physAddress)).build();
403 public static InstanceIdentifier<MacTable> getElanMacTableOperationalDataPath(String elanName) {
404 return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class, new MacTableKey(elanName))
408 // elan-interface-forwarding-entries Operational container
409 public ElanInterfaceMac getElanInterfaceMacByInterfaceName(String interfaceName) {
410 return getElanInterfaceMacByInterfaceName(broker, interfaceName);
414 public static ElanInterfaceMac getElanInterfaceMacByInterfaceName(DataBroker dataBroker, String interfaceName) {
415 InstanceIdentifier<ElanInterfaceMac> elanInterfaceId = getElanInterfaceMacEntriesOperationalDataPath(
417 return read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanInterfaceId).orNull();
421 * Gets the elan interface mac addresses.
423 * @param interfaceName
425 * @return the elan interface mac addresses
427 public List<PhysAddress> getElanInterfaceMacAddresses(String interfaceName) {
428 List<PhysAddress> macAddresses = new ArrayList<>();
429 ElanInterfaceMac elanInterfaceMac = getElanInterfaceMacByInterfaceName(interfaceName);
430 if (elanInterfaceMac != null && elanInterfaceMac.getMacEntry() != null) {
431 List<MacEntry> macEntries = elanInterfaceMac.getMacEntry();
432 for (MacEntry macEntry : macEntries) {
433 macAddresses.add(macEntry.getMacAddress());
439 public static InstanceIdentifier<ElanInterfaceMac> getElanInterfaceMacEntriesOperationalDataPath(
440 String interfaceName) {
441 return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class)
442 .child(ElanInterfaceMac.class, new ElanInterfaceMacKey(interfaceName)).build();
446 * Returns the list of Interfaces that belong to an Elan on an specific DPN.
447 * Data retrieved from Elan's operational DS: elan-dpn-interfaces container
449 * @param elanInstanceName
450 * name of the Elan to which the interfaces must belong to
452 * Id of the DPN where the interfaces are located
453 * @return the elan interface Info
455 public DpnInterfaces getElanInterfaceInfoByElanDpn(String elanInstanceName, BigInteger dpId) {
456 InstanceIdentifier<DpnInterfaces> elanDpnInterfacesId = getElanDpnInterfaceOperationalDataPath(elanInstanceName,
458 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfacesId).orNull();
462 * Returns the InstanceIdentifier that points to the Interfaces of an Elan
463 * in a given DPN in the Operational DS. Data retrieved from Elans's
464 * operational DS: dpn-interfaces list
466 * @param elanInstanceName
467 * name of the Elan to which the interfaces must belong to
469 * Id of the DPN where the interfaces are located
470 * @return the elan dpn interface
472 public static InstanceIdentifier<DpnInterfaces> getElanDpnInterfaceOperationalDataPath(String elanInstanceName,
474 return InstanceIdentifier.builder(ElanDpnInterfaces.class)
475 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName))
476 .child(DpnInterfaces.class, new DpnInterfacesKey(dpId)).build();
479 // elan-tag-name-map Operational Container
480 public ElanTagName getElanInfoByElanTag(long elanTag) {
481 InstanceIdentifier<ElanTagName> elanId = getElanInfoEntriesOperationalDataPath(elanTag);
482 Optional<ElanTagName> existingElanInfo = read(broker,
483 LogicalDatastoreType.OPERATIONAL, elanId);
484 return existingElanInfo.orNull();
487 public static InstanceIdentifier<ElanTagName> getElanInfoEntriesOperationalDataPath(long elanTag) {
488 return InstanceIdentifier.builder(ElanTagNameMap.class).child(ElanTagName.class, new ElanTagNameKey(elanTag))
492 // interface-index-tag operational container
493 public Optional<IfIndexInterface> getInterfaceInfoByInterfaceTag(long interfaceTag) {
494 InstanceIdentifier<IfIndexInterface> interfaceId = getInterfaceInfoEntriesOperationalDataPath(interfaceTag);
495 return read(broker, LogicalDatastoreType.OPERATIONAL, interfaceId);
498 public static InstanceIdentifier<IfIndexInterface> getInterfaceInfoEntriesOperationalDataPath(long interfaceTag) {
499 return InstanceIdentifier.builder(IfIndexesInterfaceMap.class)
500 .child(IfIndexInterface.class, new IfIndexInterfaceKey((int) interfaceTag)).build();
503 public static InstanceIdentifier<ElanDpnInterfacesList> getElanDpnOperationDataPath(String elanInstanceName) {
504 return InstanceIdentifier.builder(ElanDpnInterfaces.class)
505 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName)).build();
508 public ElanDpnInterfacesList getElanDpnInterfacesList(String elanName) {
509 InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanName);
510 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orNull();
513 public ElanDpnInterfaces getElanDpnInterfacesList() {
514 InstanceIdentifier<ElanDpnInterfaces> elanDpnInterfaceId = InstanceIdentifier.builder(ElanDpnInterfaces.class)
516 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orNull();
520 * This method is useful get all ELAN participating CSS dpIds to install
521 * program remote dmac entries and updating remote bc groups for tor
524 * @param elanInstanceName
525 * the elan instance name
526 * @return list of dpIds
529 public List<BigInteger> getParticipatingDpnsInElanInstance(String elanInstanceName) {
530 List<BigInteger> dpIds = new ArrayList<>();
531 InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
532 Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = read(broker,
533 LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
534 if (!existingElanDpnInterfaces.isPresent()) {
537 List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().getDpnInterfaces();
538 for (DpnInterfaces dpnInterface : dpnInterfaces) {
539 dpIds.add(dpnInterface.getDpId());
545 * To check given dpId is already present in Elan instance. This can be used
546 * to program flow entry in external tunnel table when a new access port
547 * added for first time into the ELAN instance
551 * @param elanInstanceName
552 * the elan instance name
553 * @return true if dpId is already present, otherwise return false
555 public boolean isDpnAlreadyPresentInElanInstance(BigInteger dpId, String elanInstanceName) {
556 InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
557 Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = read(broker,
558 LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
559 if (!existingElanDpnInterfaces.isPresent()) {
562 List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().getDpnInterfaces();
563 for (DpnInterfaces dpnInterface : dpnInterfaces) {
564 if (dpnInterface.getDpId().equals(dpId)) {
571 public ElanForwardingTables getElanForwardingList() {
572 InstanceIdentifier<ElanForwardingTables> elanForwardingTableId = InstanceIdentifier
573 .builder(ElanForwardingTables.class).build();
574 return read(broker, LogicalDatastoreType.OPERATIONAL, elanForwardingTableId).orNull();
577 public static long getElanRemoteBroadCastGroupID(long elanTag) {
578 return ElanConstants.ELAN_GID_MIN + elanTag % ElanConstants.ELAN_GID_MIN * 2;
582 * Gets the elan mac table.
586 * @return the elan mac table
588 public MacTable getElanMacTable(String elanName) {
589 return getElanMacTable(broker, elanName);
593 public static MacTable getElanMacTable(DataBroker dataBroker, String elanName) {
594 InstanceIdentifier<MacTable> elanMacTableId = getElanMacTableOperationalDataPath(elanName);
595 return read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanMacTableId).orNull();
598 public static long getElanLocalBCGId(long elanTag) {
599 return ElanConstants.ELAN_GID_MIN + (elanTag % ElanConstants.ELAN_GID_MIN * 2 - 1);
602 public static long getElanRemoteBCGId(long elanTag) {
603 return ElanConstants.ELAN_GID_MIN + elanTag % ElanConstants.ELAN_GID_MIN * 2;
606 public static long getEtreeLeafLocalBCGId(long etreeLeafTag) {
607 return ElanConstants.ELAN_GID_MIN + (etreeLeafTag % ElanConstants.ELAN_GID_MIN * 2 - 1);
610 public static long getEtreeLeafRemoteBCGId(long etreeLeafTag) {
611 return ElanConstants.ELAN_GID_MIN + etreeLeafTag % ElanConstants.ELAN_GID_MIN * 2;
614 public static BigInteger getElanMetadataLabel(long elanTag, boolean isSHFlagSet) {
615 int shBit = isSHFlagSet ? 1 : 0;
616 return BigInteger.valueOf(elanTag).shiftLeft(24).or(BigInteger.valueOf(shBit));
620 * Setting SMAC, DMAC, UDMAC in this DPN and optionally in other DPNs.
624 * @param interfaceInfo
630 * @param configureRemoteFlows
631 * true if remote dmac flows should be configured as well
632 * @param writeFlowGroupTx
635 public void setupMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo,
636 long macTimeout, String macAddress, boolean configureRemoteFlows,
637 TypedWriteTransaction<Configuration> writeFlowGroupTx) {
638 synchronized (getElanMacDPNKey(elanInfo.getElanTag(), macAddress, interfaceInfo.getDpId())) {
639 setupKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress, mdsalManager,
641 setupOrigDmacFlows(elanInfo, interfaceInfo, macAddress, configureRemoteFlows, mdsalManager,
646 public void setupDMacFlowOnRemoteDpn(ElanInstance elanInfo, InterfaceInfo interfaceInfo, BigInteger dstDpId,
647 String macAddress, TypedWriteTransaction<Configuration> writeFlowTx) {
648 String elanInstanceName = elanInfo.getElanInstanceName();
649 setupRemoteDmacFlow(dstDpId, interfaceInfo.getDpId(), interfaceInfo.getInterfaceTag(), elanInfo.getElanTag(),
650 macAddress, elanInstanceName, writeFlowTx, interfaceInfo.getInterfaceName(), elanInfo);
651 LOG.info("Remote Dmac flow entry created for elan Name:{}, logical port Name:{} and"
652 + " mac address {} on dpn:{}", elanInstanceName, interfaceInfo.getPortName(),
653 macAddress, dstDpId);
657 * Inserts a Flow in SMAC table to state that the MAC has already been
660 private void setupKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
661 String macAddress, IMdsalApiManager mdsalApiManager,
662 TypedWriteTransaction<Configuration> writeFlowGroupTx) {
663 FlowEntity flowEntity = buildKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress);
664 mdsalApiManager.addFlow(writeFlowGroupTx, flowEntity);
665 LOG.debug("Known Smac flow entry created for elan Name:{}, logical Interface port:{} and mac address:{}",
666 elanInfo.getElanInstanceName(), elanInfo.getDescription(), macAddress);
669 public FlowEntity buildKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
671 int lportTag = interfaceInfo.getInterfaceTag();
672 // Matching metadata and eth_src fields
673 List<MatchInfo> mkMatches = new ArrayList<>();
674 mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanInfo.getElanTag(), lportTag),
675 ElanHelper.getElanMetadataMask()));
676 mkMatches.add(new MatchEthernetSource(new MacAddress(macAddress)));
677 List<InstructionInfo> mkInstructions = new ArrayList<>();
678 mkInstructions.add(new InstructionGotoTable(NwConstants.ELAN_DMAC_TABLE));
679 BigInteger dpId = interfaceInfo.getDpId();
680 long elanTag = getElanTag(elanInfo, interfaceInfo);
681 return new FlowEntityBuilder()
683 .setTableId(NwConstants.ELAN_SMAC_TABLE)
684 .setFlowId(getKnownDynamicmacFlowRef(NwConstants.ELAN_SMAC_TABLE, dpId, lportTag, macAddress, elanTag))
686 .setFlowName(elanInfo.getDescription())
687 .setIdleTimeOut((int) macTimeout)
689 .setCookie(ElanConstants.COOKIE_ELAN_KNOWN_SMAC.add(BigInteger.valueOf(elanTag)))
690 .setMatchInfoList(mkMatches)
691 .setInstructionInfoList(mkInstructions)
693 // If Mac timeout is 0, the flow won't be deleted automatically, so no need to get notified
694 .setSendFlowRemFlag(macTimeout != 0)
698 private Long getElanTag(ElanInstance elanInfo, InterfaceInfo interfaceInfo) {
699 EtreeInterface etreeInterface = elanInterfaceCache.getEtreeInterface(interfaceInfo.getInterfaceName()).orNull();
700 if (etreeInterface == null || etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
701 return elanInfo.getElanTag();
703 EtreeInstance etreeInstance = elanInfo.augmentation(EtreeInstance.class);
704 if (etreeInstance == null) {
705 LOG.warn("EtreeInterface {} is connected to a non-Etree network: {}",
706 interfaceInfo.getInterfaceName(), elanInfo.getElanInstanceName());
707 return elanInfo.getElanTag();
709 return etreeInstance.getEtreeLeafTagVal().getValue();
715 * Installs a Flow in INTERNAL_TUNNEL_TABLE of the affected DPN that sends
716 * the packet through the specified interface if the tunnel_id matches the
717 * interface's lportTag.
719 * @param interfaceInfo
721 * @param mdsalApiManager
722 * the mdsal API manager
723 * @param writeFlowGroupTx
724 * the writeFLowGroup tx
726 public void setupTermDmacFlows(InterfaceInfo interfaceInfo, IMdsalApiManager mdsalApiManager,
727 TypedWriteTransaction<Configuration> writeFlowGroupTx) {
728 BigInteger dpId = interfaceInfo.getDpId();
729 int lportTag = interfaceInfo.getInterfaceTag();
730 Flow flow = MDSALUtil.buildFlowNew(NwConstants.INTERNAL_TUNNEL_TABLE,
731 getIntTunnelTableFlowRef(NwConstants.INTERNAL_TUNNEL_TABLE, lportTag), 5,
732 String.format("%s:%d", "ITM Flow Entry ", lportTag), 0, 0,
733 ITMConstants.COOKIE_ITM.add(BigInteger.valueOf(lportTag)),
734 getTunnelIdMatchForFilterEqualsLPortTag(lportTag),
735 getInstructionsInPortForOutGroup(interfaceInfo.getInterfaceName()));
736 mdsalApiManager.addFlow(writeFlowGroupTx, dpId, flow);
737 LOG.debug("Terminating service table flow entry created on dpn:{} for logical Interface port:{}", dpId,
738 interfaceInfo.getPortName());
742 * Constructs the FlowName for flows installed in the Internal Tunnel Table,
743 * consisting in tableId + elanTag.
749 * @return the Internal tunnel
751 public static String getIntTunnelTableFlowRef(short tableId, int elanTag) {
752 return new StringBuffer().append(tableId).append(elanTag).toString();
756 * Constructs the Matches that checks that the tunnel_id field contains a
760 * lportTag that must be checked against the tunnel_id field
761 * @return the list of match Info
763 public static List<MatchInfo> getTunnelIdMatchForFilterEqualsLPortTag(int lportTag) {
764 List<MatchInfo> mkMatches = new ArrayList<>();
766 mkMatches.add(new MatchTunnelId(BigInteger.valueOf(lportTag)));
771 * Constructs the Instructions that take the packet over a given interface.
774 * Name of the interface where the packet must be sent over. It
775 * can be a local interface or a tunnel interface (internal or
777 * @return the Instruction
779 public List<Instruction> getInstructionsInPortForOutGroup(String ifName) {
780 List<Instruction> mkInstructions = new ArrayList<>();
781 List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
783 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
784 return mkInstructions;
788 * Returns the list of Actions to be taken when sending the packet through
789 * an Elan interface. Note that this interface can refer to an ElanInterface
790 * where the Elan VM is attached to a DPN or an ITM tunnel interface where
791 * Elan traffic can be sent through. In this latter case, the tunnelKey is
792 * mandatory and it can hold serviceId for internal tunnels or the VNI for
799 * @return the egress actions for interface
801 @SuppressWarnings("checkstyle:IllegalCatch")
802 public List<Action> getEgressActionsForInterface(String ifName, Long tunnelKey) {
803 List<Action> listAction = new ArrayList<>();
805 GetEgressActionsForInterfaceInput getEgressActionInput = new GetEgressActionsForInterfaceInputBuilder()
806 .setIntfName(ifName).setTunnelKey(tunnelKey).build();
807 Future<RpcResult<GetEgressActionsForInterfaceOutput>> result = interfaceManagerRpcService
808 .getEgressActionsForInterface(getEgressActionInput);
809 RpcResult<GetEgressActionsForInterfaceOutput> rpcResult = result.get();
810 if (!rpcResult.isSuccessful()) {
811 LOG.debug("RPC Call to Get egress actions for interface {} returned with Errors {}", ifName,
812 rpcResult.getErrors());
814 List<Action> actions = rpcResult.getResult().getAction();
815 listAction = actions;
817 } catch (Exception e) {
818 LOG.warn("Exception when egress actions for interface {}", ifName, e);
823 private void setupOrigDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
824 boolean configureRemoteFlows, IMdsalApiManager mdsalApiManager,
825 TypedWriteTransaction<Configuration> writeFlowGroupTx) {
826 BigInteger dpId = interfaceInfo.getDpId();
827 String ifName = interfaceInfo.getInterfaceName();
828 long ifTag = interfaceInfo.getInterfaceTag();
829 String elanInstanceName = elanInfo.getElanInstanceName();
831 Long elanTag = elanInfo.getElanTag();
833 setupLocalDmacFlow(elanTag, dpId, ifName, macAddress, elanInfo, mdsalApiManager, ifTag,
835 LOG.debug("Dmac flow entry created for elan Name:{}, logical port Name:{} mand mac address:{} "
836 + "on dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, dpId);
838 if (!configureRemoteFlows) {
842 List<DpnInterfaces> elanDpns = getInvolvedDpnsInElan(elanInstanceName);
843 for (DpnInterfaces elanDpn : elanDpns) {
845 if (elanDpn.getDpId().equals(dpId)) {
849 // Check for the Remote DPN present in Inventory Manager
850 if (!isDpnPresent(elanDpn.getDpId())) {
854 // For remote DPNs a flow is needed to indicate that packets of this ELAN going to this MAC need to be
855 // forwarded through the appropriate ITM tunnel
856 setupRemoteDmacFlow(elanDpn.getDpId(), // srcDpn (the remote DPN in this case)
857 dpId, // dstDpn (the local DPN)
858 interfaceInfo.getInterfaceTag(), // lportTag of the local interface
859 elanTag, // identifier of the Elan
860 macAddress, // MAC to be programmed in remote DPN
861 elanInstanceName, writeFlowGroupTx, ifName, elanInfo
863 LOG.debug("Remote Dmac flow entry created for elan Name:{}, logical port Name:{} and mac address:{} on"
864 + " dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, elanDpn.getDpId());
867 // TODO: Make sure that the same is performed against the ElanDevices.
871 public List<DpnInterfaces> getInvolvedDpnsInElan(String elanName) {
872 return getElanDPNByName(elanName);
876 public List<DpnInterfaces> getElanDPNByName(String elanInstanceName) {
877 InstanceIdentifier<ElanDpnInterfacesList> elanIdentifier = getElanDpnOperationDataPath(elanInstanceName);
878 return MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL, elanIdentifier).toJavaUtil().map(
879 ElanDpnInterfacesList::getDpnInterfaces).orElse(Collections.emptyList());
882 private void setupLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
883 ElanInstance elanInfo, IMdsalApiManager mdsalApiManager, long ifTag,
884 TypedWriteTransaction<Configuration> writeFlowGroupTx) {
885 Flow flowEntity = buildLocalDmacFlowEntry(elanTag, dpId, ifName, macAddress, elanInfo, ifTag);
886 mdsalApiManager.addFlow(writeFlowGroupTx, dpId, flowEntity);
887 installEtreeLocalDmacFlow(elanTag, dpId, ifName, macAddress, elanInfo, ifTag, writeFlowGroupTx);
890 private void installEtreeLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
891 ElanInstance elanInfo, long ifTag, TypedWriteTransaction<Configuration> writeFlowGroupTx) {
892 EtreeInterface etreeInterface = elanInterfaceCache.getEtreeInterface(ifName).orNull();
893 if (etreeInterface != null && etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
894 EtreeLeafTagName etreeTagName = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
895 if (etreeTagName == null) {
896 LOG.warn("Interface {} seems like it belongs to Etree but etreeTagName from elanTag {} is null",
899 Flow flowEntity = buildLocalDmacFlowEntry(etreeTagName.getEtreeLeafTag().getValue(), dpId, ifName,
900 macAddress, elanInfo, ifTag);
901 mdsalManager.addFlow(writeFlowGroupTx, dpId, flowEntity);
906 public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, long lporTag, String macAddress,
908 return String.valueOf(tableId) + elanTag + dpId + lporTag + macAddress;
911 public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, BigInteger remoteDpId,
912 String macAddress, long elanTag) {
913 return String.valueOf(tableId) + elanTag + dpId + remoteDpId + macAddress;
916 public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, String macAddress, long elanTag) {
917 return String.valueOf(tableId) + elanTag + dpId + macAddress;
920 public static String getKnownDynamicmacFlowRef(short elanDmacTable, BigInteger dpId, String extDeviceNodeId,
921 String dstMacAddress, long elanTag, boolean shFlag) {
922 return String.valueOf(elanDmacTable) + elanTag + dpId + extDeviceNodeId + dstMacAddress + shFlag;
926 * Builds the flow to be programmed in the DMAC table of the local DPN (that
927 * is, where the MAC is attached to). This flow consists in:
929 * <p>Match: + elanTag in metadata + packet goes to a MAC locally attached
930 * Actions: + optionally, pop-vlan + set-vlan-id + output to ifName's
947 public Flow buildLocalDmacFlowEntry(long elanTag, BigInteger dpId, String ifName, String macAddress,
948 ElanInstance elanInfo, long ifTag) {
950 List<MatchInfo> mkMatches = new ArrayList<>();
951 mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
952 mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddress)));
954 List<Instruction> mkInstructions = new ArrayList<>();
955 List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
956 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
957 Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
958 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, ifTag, macAddress, elanTag), 20,
959 elanInfo.getElanInstanceName(), 0, 0, ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(
960 BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
965 public void setupRemoteDmacFlow(BigInteger srcDpId, BigInteger destDpId, int lportTag, long elanTag,
966 String macAddress, String displayName, TypedWriteTransaction<Configuration> writeFlowGroupTx,
967 String interfaceName, ElanInstance elanInstance) {
968 if (interfaceManager.isExternalInterface(interfaceName)) {
969 LOG.debug("Ignoring install remote DMAC {} flow on provider interface {} elan {}",
970 macAddress, interfaceName, elanInstance.getElanInstanceName());
974 // if openstack-vni-semantics are enforced, segmentation ID is passed as network VNI for VxLAN based provider
975 // networks, 0 otherwise
976 long lportTagOrVni = !isOpenstackVniSemanticsEnforced() ? lportTag : isVxlanNetworkOrVxlanSegment(elanInstance)
977 ? getVxlanSegmentationId(elanInstance) : 0;
978 flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTagOrVni, elanTag, macAddress, displayName,
980 mdsalManager.addFlow(writeFlowGroupTx, srcDpId, flowEntity);
981 setupEtreeRemoteDmacFlow(srcDpId, destDpId, lportTagOrVni, elanTag, macAddress, displayName, interfaceName,
982 writeFlowGroupTx, elanInstance);
985 private void setupEtreeRemoteDmacFlow(BigInteger srcDpId, BigInteger destDpId, long lportTagOrVni, long elanTag,
986 String macAddress, String displayName, String interfaceName,
987 TypedWriteTransaction<Configuration> writeFlowGroupTx,
988 ElanInstance elanInstance) {
990 EtreeInterface etreeInterface = elanInterfaceCache.getEtreeInterface(interfaceName).orNull();
991 if (etreeInterface != null && etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
992 EtreeLeafTagName etreeTagName = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
993 if (etreeTagName == null) {
994 LOG.warn("Interface {} seems like it belongs to Etree but etreeTagName from elanTag {} is null.",
995 interfaceName, elanTag);
997 flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTagOrVni,
998 etreeTagName.getEtreeLeafTag().getValue(), macAddress, displayName, elanInstance);
999 mdsalManager.addFlow(writeFlowGroupTx, srcDpId, flowEntity);
1005 * Builds a Flow to be programmed in a remote DPN's DMAC table. This flow
1006 * consists in: Match: + elanTag in packet's metadata + packet going to a
1007 * MAC known to be located in another DPN Actions: + set_tunnel_id
1008 * + output ITM internal tunnel interface with the other DPN
1014 * @param lportTagOrVni
1015 * lportTag or network VNI
1020 * @param displayName
1022 * @param elanInstance
1024 * @return the flow remote Dmac
1026 @SuppressWarnings("checkstyle:IllegalCatch")
1027 public Flow buildRemoteDmacFlowEntry(BigInteger srcDpId, BigInteger destDpId, long lportTagOrVni, long elanTag,
1028 String macAddress, String displayName, ElanInstance elanInstance) {
1029 List<MatchInfo> mkMatches = new ArrayList<>();
1030 mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
1031 mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddress)));
1033 List<Instruction> mkInstructions = new ArrayList<>();
1035 // List of Action for the provided Source and Destination DPIDs
1037 List<Action> actions = null;
1038 if (isVxlanNetworkOrVxlanSegment(elanInstance)) {
1039 actions = elanItmUtils.getInternalTunnelItmEgressAction(srcDpId, destDpId, lportTagOrVni);
1040 } else if (isVlan(elanInstance) || isFlat(elanInstance)) {
1041 String interfaceName = getExternalElanInterface(elanInstance.getElanInstanceName(), srcDpId);
1042 if (null == interfaceName) {
1043 LOG.info("buildRemoteDmacFlowEntry: Could not find interfaceName for {} {}", srcDpId,
1046 actions = getEgressActionsForInterface(interfaceName, null);
1048 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
1049 } catch (Exception e) {
1050 LOG.error("Could not get egress actions to add to flow for srcDpId {}, destDpId {}, lportTag/VNI {}",
1051 srcDpId, destDpId, lportTagOrVni, e);
1054 Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
1055 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, srcDpId, destDpId, macAddress, elanTag),
1057 displayName, 0, /* idleTimeout */
1058 0, /* hardTimeout */
1059 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
1065 public void deleteMacFlows(@Nullable ElanInstance elanInfo, @Nullable InterfaceInfo interfaceInfo,
1066 MacEntry macEntry, TypedReadWriteTransaction<Configuration> flowTx)
1067 throws ExecutionException, InterruptedException {
1068 if (elanInfo == null || interfaceInfo == null) {
1071 String macAddress = macEntry.getMacAddress().getValue();
1072 synchronized (getElanMacDPNKey(elanInfo.getElanTag(), macAddress, interfaceInfo.getDpId())) {
1073 deleteMacFlows(elanInfo, interfaceInfo, macAddress, /* alsoDeleteSMAC */ true, flowTx);
1077 public void deleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1078 boolean deleteSmac, TypedReadWriteTransaction<Configuration> flowTx)
1079 throws ExecutionException, InterruptedException {
1080 String elanInstanceName = elanInfo.getElanInstanceName();
1081 List<DpnInterfaces> remoteFEs = getInvolvedDpnsInElan(elanInstanceName);
1082 BigInteger srcdpId = interfaceInfo.getDpId();
1083 boolean isFlowsRemovedInSrcDpn = false;
1084 for (DpnInterfaces dpnInterface : remoteFEs) {
1085 Long elanTag = elanInfo.getElanTag();
1086 BigInteger dstDpId = dpnInterface.getDpId();
1087 if (executeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1088 elanTag, dstDpId, flowTx)) {
1089 isFlowsRemovedInSrcDpn = true;
1091 executeEtreeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1092 elanTag, dstDpId, flowTx);
1094 if (!isFlowsRemovedInSrcDpn) {
1095 deleteSmacAndDmacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, flowTx);
1099 private void executeEtreeDeleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1100 boolean deleteSmac, String elanInstanceName, BigInteger srcdpId, Long elanTag, BigInteger dstDpId,
1101 TypedReadWriteTransaction<Configuration> flowTx) throws ExecutionException, InterruptedException {
1102 EtreeLeafTagName etreeLeafTag = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
1103 if (etreeLeafTag != null) {
1104 executeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1105 etreeLeafTag.getEtreeLeafTag().getValue(), dstDpId, flowTx);
1109 private boolean executeDeleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1110 boolean deleteSmac, String elanInstanceName, BigInteger srcdpId, Long elanTag, BigInteger dstDpId,
1111 TypedReadWriteTransaction<Configuration> flowTx) throws ExecutionException, InterruptedException {
1112 boolean isFlowsRemovedInSrcDpn = false;
1113 if (dstDpId.equals(srcdpId)) {
1114 isFlowsRemovedInSrcDpn = true;
1115 deleteSmacAndDmacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, flowTx);
1116 } else if (isDpnPresent(dstDpId)) {
1118 .removeFlow(flowTx, dstDpId,
1119 MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, getKnownDynamicmacFlowRef(
1120 NwConstants.ELAN_DMAC_TABLE, dstDpId, srcdpId, macAddress, elanTag)));
1121 LOG.debug("Dmac flow entry deleted for elan:{}, logical interface port:{} and mac address:{} on dpn:{}",
1122 elanInstanceName, interfaceInfo.getPortName(), macAddress, dstDpId);
1124 return isFlowsRemovedInSrcDpn;
1127 private void deleteSmacAndDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1128 boolean deleteSmac, TypedReadWriteTransaction<Configuration> flowTx)
1129 throws ExecutionException, InterruptedException {
1130 String elanInstanceName = elanInfo.getElanInstanceName();
1131 long ifTag = interfaceInfo.getInterfaceTag();
1132 BigInteger srcdpId = interfaceInfo.getDpId();
1133 Long elanTag = elanInfo.getElanTag();
1136 .removeFlow(flowTx, srcdpId,
1137 MDSALUtil.buildFlow(NwConstants.ELAN_SMAC_TABLE, getKnownDynamicmacFlowRef(
1138 NwConstants.ELAN_SMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)));
1140 mdsalManager.removeFlow(flowTx, srcdpId,
1141 MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE,
1142 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)));
1143 LOG.debug("All the required flows deleted for elan:{}, logical Interface port:{} and MAC address:{} on dpn:{}",
1144 elanInstanceName, interfaceInfo.getPortName(), macAddress, srcdpId);
1148 * Updates the Elan information in the Operational DS. It also updates the
1149 * ElanInstance in the Config DS by setting the adquired elanTag.
1153 * @param elanInstanceAdded
1154 * the elan instance added
1155 * @param elanInterfaces
1156 * the elan interfaces
1160 * @return the updated ELAN instance.
1162 public static ElanInstance updateOperationalDataStore(IdManagerService idManager,
1163 ElanInstance elanInstanceAdded, List<String> elanInterfaces, TypedWriteTransaction<Configuration> confTx,
1164 TypedWriteTransaction<Operational> operTx) {
1165 String elanInstanceName = elanInstanceAdded.getElanInstanceName();
1166 Long elanTag = elanInstanceAdded.getElanTag();
1167 if (elanTag == null || elanTag == 0L) {
1168 elanTag = retrieveNewElanTag(idManager, elanInstanceName);
1170 Elan elanInfo = new ElanBuilder().setName(elanInstanceName).setElanInterfaces(elanInterfaces)
1171 .withKey(new ElanKey(elanInstanceName)).build();
1173 // Add the ElanState in the elan-state operational data-store
1174 operTx.put(getElanInstanceOperationalDataPath(elanInstanceName), elanInfo, CREATE_MISSING_PARENTS);
1176 // Add the ElanMacTable in the elan-mac-table operational data-store
1177 MacTable elanMacTable = new MacTableBuilder().withKey(new MacTableKey(elanInstanceName)).build();
1178 operTx.put(getElanMacTableOperationalDataPath(elanInstanceName), elanMacTable, 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, operTx);
1191 ElanTagName elanTagName = elanTagNameBuilder.build();
1193 // Add the ElanTag to ElanName in the elan-tag-name Operational
1195 operTx.put(getElanInfoEntriesOperationalDataPath(elanTag), elanTagName);
1197 // Updates the ElanInstance Config DS by setting the just acquired
1199 ElanInstanceBuilder elanInstanceBuilder = new ElanInstanceBuilder().setElanInstanceName(elanInstanceName)
1200 .setDescription(elanInstanceAdded.getDescription())
1201 .setMacTimeout(elanInstanceAdded.getMacTimeout() == null
1202 ? Long.valueOf(ElanConstants.DEFAULT_MAC_TIME_OUT) : elanInstanceAdded.getMacTimeout())
1203 .withKey(elanInstanceAdded.key()).setElanTag(elanTag);
1204 if (isEtreeInstance(elanInstanceAdded)) {
1205 EtreeInstance etreeInstance = new EtreeInstanceBuilder().setEtreeLeafTagVal(new EtreeLeafTag(etreeLeafTag))
1207 elanInstanceBuilder.addAugmentation(EtreeInstance.class, etreeInstance);
1209 ElanInstance elanInstanceWithTag = elanInstanceBuilder.build();
1210 confTx.merge(ElanHelper.getElanInstanceConfigurationDataPath(elanInstanceName), elanInstanceWithTag,
1211 CREATE_MISSING_PARENTS);
1212 return elanInstanceWithTag;
1215 private static void addTheLeafTagAsElanTag(String elanInstanceName, long etreeLeafTag,
1216 TypedWriteTransaction<Operational> tx) {
1217 ElanTagName etreeTagAsElanTag = new ElanTagNameBuilder().setElanTag(etreeLeafTag)
1218 .withKey(new ElanTagNameKey(etreeLeafTag)).setName(elanInstanceName).build();
1219 tx.put(getElanInfoEntriesOperationalDataPath(etreeLeafTag), etreeTagAsElanTag);
1222 private static boolean isEtreeInstance(ElanInstance elanInstanceAdded) {
1223 return elanInstanceAdded.augmentation(EtreeInstance.class) != null;
1226 public boolean isDpnPresent(BigInteger dpnId) {
1227 String dpn = String.format("%s:%s", "openflow", dpnId);
1228 NodeId nodeId = new NodeId(dpn);
1230 InstanceIdentifier<Node> node = InstanceIdentifier.builder(Nodes.class).child(Node.class, new NodeKey(nodeId))
1232 return read(broker, LogicalDatastoreType.CONFIGURATION, node).isPresent();
1235 public static ServicesInfo getServiceInfo(String elanInstanceName, String interfaceName) {
1236 return InterfaceServiceUtil.buildServiceInfo(elanInstanceName + "." + interfaceName,
1237 ElanConstants.ELAN_SERVICE_PRIORITY);
1240 public static String getElanServiceName(String elanName, String interfaceName) {
1241 return "elan." + elanName + interfaceName;
1244 public static BoundServices getBoundServices(String serviceName, short servicePriority, int flowPriority,
1245 BigInteger cookie, List<Instruction> instructions) {
1246 StypeOpenflowBuilder augBuilder = new StypeOpenflowBuilder().setFlowCookie(cookie).setFlowPriority(flowPriority)
1247 .setInstruction(instructions);
1248 return new BoundServicesBuilder().withKey(new BoundServicesKey(servicePriority)).setServiceName(serviceName)
1249 .setServicePriority(servicePriority).setServiceType(ServiceTypeFlowBased.class)
1250 .addAugmentation(StypeOpenflow.class, augBuilder.build()).build();
1253 public static InstanceIdentifier<BoundServices> buildServiceId(String interfaceName, short serviceIndex) {
1254 return InstanceIdentifier.builder(ServiceBindings.class)
1255 .child(ServicesInfo.class, new ServicesInfoKey(interfaceName, ServiceModeIngress.class))
1256 .child(BoundServices.class, new BoundServicesKey(serviceIndex)).build();
1259 public static List<MatchInfo> getTunnelMatchesForServiceId(int elanTag) {
1260 List<MatchInfo> mkMatches = new ArrayList<>();
1261 // Matching metadata
1262 mkMatches.add(new MatchTunnelId(BigInteger.valueOf(elanTag)));
1267 public void removeTerminatingServiceAction(BigInteger destDpId, int serviceId) {
1268 RemoveTerminatingServiceActionsInput input = new RemoveTerminatingServiceActionsInputBuilder()
1269 .setDpnId(destDpId).setServiceId(serviceId).build();
1270 Future<RpcResult<RemoveTerminatingServiceActionsOutput>> futureObject =
1271 itmRpcService.removeTerminatingServiceActions(input);
1273 RpcResult<RemoveTerminatingServiceActionsOutput> result = futureObject.get();
1274 if (result.isSuccessful()) {
1275 LOG.debug("Successfully completed removeTerminatingServiceActions for ELAN with serviceId {} on "
1276 + "dpn {}", serviceId, destDpId);
1278 LOG.debug("Failure in removeTerminatingServiceAction RPC call for ELAN with serviceId {} on "
1279 + "dpn {}", serviceId, destDpId);
1281 } catch (InterruptedException | ExecutionException e) {
1282 LOG.error("Error in RPC call removeTerminatingServiceActions for ELAN with serviceId {} on "
1283 + "dpn {}", serviceId, destDpId, e);
1288 * Gets the external tunnel.
1290 * @param sourceDevice
1292 * @param destinationDevice
1293 * the destination device
1294 * @param datastoreType
1295 * the datastore type
1296 * @return the external tunnel
1298 public ExternalTunnel getExternalTunnel(String sourceDevice, String destinationDevice,
1299 LogicalDatastoreType datastoreType) {
1300 Class<? extends TunnelTypeBase> tunType = TunnelTypeVxlan.class;
1301 InstanceIdentifier<ExternalTunnel> iid = InstanceIdentifier.builder(ExternalTunnelList.class)
1302 .child(ExternalTunnel.class, new ExternalTunnelKey(destinationDevice, sourceDevice, tunType)).build();
1303 return read(broker, datastoreType, iid).orNull();
1307 * Gets the external tunnel.
1309 * @param interfaceName
1310 * the interface name
1311 * @param datastoreType
1312 * the datastore type
1313 * @return the external tunnel
1315 public ExternalTunnel getExternalTunnel(String interfaceName, LogicalDatastoreType datastoreType) {
1316 ExternalTunnel externalTunnel = null;
1317 List<ExternalTunnel> externalTunnels = getAllExternalTunnels(datastoreType);
1318 for (ExternalTunnel tunnel : externalTunnels) {
1319 if (StringUtils.equalsIgnoreCase(interfaceName, tunnel.getTunnelInterfaceName())) {
1320 externalTunnel = tunnel;
1324 return externalTunnel;
1328 * Gets the all external tunnels.
1330 * @param datastoreType
1331 * the data store type
1332 * @return the all external tunnels
1334 public List<ExternalTunnel> getAllExternalTunnels(LogicalDatastoreType datastoreType) {
1335 InstanceIdentifier<ExternalTunnelList> iid = InstanceIdentifier.builder(ExternalTunnelList.class).build();
1336 return read(broker, datastoreType, iid).toJavaUtil().map(ExternalTunnelList::getExternalTunnel).orElse(
1337 Collections.emptyList());
1340 public static List<MatchInfo> buildMatchesForElanTagShFlagAndDstMac(long elanTag, boolean shFlag, String macAddr) {
1341 List<MatchInfo> mkMatches = new ArrayList<>();
1343 new MatchMetadata(getElanMetadataLabel(elanTag, shFlag), MetaDataUtil.METADATA_MASK_SERVICE_SH_FLAG));
1344 mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddr)));
1349 * Checks if is interface operational.
1351 * @param interfaceName
1352 * the interface name
1355 * @return true, if is interface operational
1357 public static boolean isInterfaceOperational(String interfaceName, DataBroker dataBroker) {
1358 if (StringUtils.isBlank(interfaceName)) {
1361 Interface ifState = getInterfaceStateFromOperDS(interfaceName, dataBroker);
1362 if (ifState == null) {
1365 return ifState.getOperStatus() == OperStatus.Up && ifState.getAdminStatus() == AdminStatus.Up;
1369 * Gets the interface state from operational ds.
1371 * @param interfaceName
1372 * the interface name
1375 * @return the interface state from oper ds
1377 public static org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1378 .ietf.interfaces.rev140508.interfaces.state.Interface getInterfaceStateFromOperDS(
1379 String interfaceName, DataBroker dataBroker) {
1380 InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1381 .ietf.interfaces.rev140508.interfaces.state.Interface> ifStateId = createInterfaceStateInstanceIdentifier(
1383 return MDSALUtil.read(dataBroker, LogicalDatastoreType.OPERATIONAL, ifStateId).orNull();
1387 * Creates the interface state instance identifier.
1389 * @param interfaceName
1390 * the interface name
1391 * @return the instance identifier
1393 public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1394 .ietf.interfaces.rev140508.interfaces.state.Interface> createInterfaceStateInstanceIdentifier(
1395 String interfaceName) {
1396 InstanceIdentifierBuilder<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1397 .ietf.interfaces.rev140508.interfaces.state.Interface> idBuilder = InstanceIdentifier
1398 .builder(InterfacesState.class)
1399 .child(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1400 .ietf.interfaces.rev140508.interfaces.state.Interface.class,
1401 new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1402 .ietf.interfaces.rev140508.interfaces.state.InterfaceKey(
1404 return idBuilder.build();
1408 public static CheckedFuture<Void, TransactionCommitFailedException> waitForTransactionToComplete(
1409 WriteTransaction tx) {
1410 CheckedFuture<Void, TransactionCommitFailedException> futures = tx.submit();
1413 } catch (InterruptedException | ExecutionException e) {
1414 // NETVIRT-1215: Do not log.error() here, only debug(); but callers *MUST* @CheckReturnValue
1415 LOG.debug("Error writing to datastore", e);
1421 public static ListenableFuture<Void> waitForTransactionToComplete(ListenableFuture<Void> future) {
1424 } catch (InterruptedException | ExecutionException e) {
1425 // NETVIRT-1215: Do not log.error() here, only debug(); but callers *MUST* @CheckReturnValue
1426 LOG.debug("Error writing to datastore", e);
1431 public static boolean isVxlan(@Nullable ElanInstance elanInstance) {
1432 return elanInstance != null && elanInstance.getSegmentType() != null
1433 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1434 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId() != 0;
1437 private static boolean isVxlanSegment(ElanInstance elanInstance) {
1438 if (elanInstance != null) {
1439 List<ElanSegments> elanSegments = elanInstance.getElanSegments();
1440 if (elanSegments != null) {
1441 for (ElanSegments segment : elanSegments) {
1442 if (segment != null && segment.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1443 && segment.getSegmentationId() != null
1444 && segment.getSegmentationId().longValue() != 0) {
1453 public static boolean isVxlanNetworkOrVxlanSegment(ElanInstance elanInstance) {
1454 return isVxlan(elanInstance) || isVxlanSegment(elanInstance);
1457 public static Long getVxlanSegmentationId(ElanInstance elanInstance) {
1458 Long segmentationId = 0L;
1459 if (elanInstance == null) {
1460 return segmentationId;
1463 if (elanInstance.getSegmentType() != null
1464 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1465 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId().longValue() != 0) {
1466 segmentationId = elanInstance.getSegmentationId();
1468 for (ElanSegments segment: elanInstance.getElanSegments()) {
1469 if (segment != null && segment.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1470 && segment.getSegmentationId() != null
1471 && segment.getSegmentationId().longValue() != 0) {
1472 segmentationId = segment.getSegmentationId();
1476 return segmentationId;
1479 public static boolean isVlan(ElanInstance elanInstance) {
1480 return elanInstance != null && elanInstance.getSegmentType() != null
1481 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVlan.class)
1482 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId() != 0;
1485 public static boolean isFlat(ElanInstance elanInstance) {
1486 return elanInstance != null && elanInstance.getSegmentType() != null
1487 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeFlat.class);
1490 public void addDmacRedirectToDispatcherFlows(Long elanTag, String displayName,
1491 String macAddress, List<BigInteger> dpnIds) {
1492 for (BigInteger dpId : dpnIds) {
1493 ListenableFutures.addErrorLogging(txRunner.callWithNewWriteOnlyTransactionAndSubmit(CONFIGURATION,
1494 tx -> mdsalManager.addFlow(tx, buildDmacRedirectToDispatcherFlow(dpId, macAddress, displayName,
1496 "Error adding DMAC redirect to dispatcher flows");
1500 public void removeDmacRedirectToDispatcherFlows(Long elanTag, String macAddress, List<BigInteger> dpnIds) {
1501 for (BigInteger dpId : dpnIds) {
1502 String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, macAddress, elanTag);
1503 mdsalManager.removeFlow(dpId, MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, flowId));
1507 public static FlowEntity buildDmacRedirectToDispatcherFlow(BigInteger dpId, String dstMacAddress,
1508 String displayName, long elanTag) {
1509 List<MatchInfo> matches = new ArrayList<>();
1510 matches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
1511 matches.add(new MatchEthernetDestination(new MacAddress(dstMacAddress)));
1512 List<InstructionInfo> instructions = new ArrayList<>();
1513 List<ActionInfo> actions = new ArrayList<>();
1514 actions.add(new ActionNxResubmit(NwConstants.LPORT_DISPATCHER_TABLE));
1516 instructions.add(new InstructionApplyActions(actions));
1517 String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, dstMacAddress, elanTag);
1518 return MDSALUtil.buildFlowEntity(dpId, NwConstants.ELAN_DMAC_TABLE, flowId, 20, displayName, 0, 0,
1519 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)),
1520 matches, instructions);
1523 public String getExternalElanInterface(String elanInstanceName, BigInteger dpnId) {
1524 DpnInterfaces dpnInterfaces = getElanInterfaceInfoByElanDpn(elanInstanceName, dpnId);
1525 if (dpnInterfaces == null || dpnInterfaces.getInterfaces() == null) {
1526 LOG.trace("Elan {} does not have interfaces in DPN {}", elanInstanceName, dpnId);
1530 for (String dpnInterface : dpnInterfaces.getInterfaces()) {
1531 if (interfaceManager.isExternalInterface(dpnInterface)) {
1532 return dpnInterface;
1536 LOG.trace("Elan {} does not have any external interace attached to DPN {}", elanInstanceName, dpnId);
1540 public static String getElanMacDPNKey(long elanTag, String macAddress, BigInteger dpnId) {
1541 String elanMacDmacDpnKey = "MAC-" + macAddress + " ELAN_TAG-" + elanTag + "DPN_ID-" + dpnId;
1542 return elanMacDmacDpnKey.intern();
1545 public static String getElanMacKey(long elanTag, String macAddress) {
1546 String elanMacKey = "MAC-" + macAddress + " ELAN_TAG-" + elanTag;
1547 return elanMacKey.intern();
1550 public static List<ListenableFuture<Void>>
1551 returnFailedListenableFutureIfTransactionCommitFailedExceptionCauseOrElseThrow(RuntimeException exception) {
1553 Throwable cause = exception.getCause();
1554 if (cause != null && cause instanceof TransactionCommitFailedException) {
1555 return Collections.singletonList(Futures.immediateFailedFuture(cause));
1561 public static List<PhysAddress> getPhysAddress(List<String> macAddress) {
1562 Preconditions.checkNotNull(macAddress, "macAddress cannot be null");
1563 List<PhysAddress> physAddresses = new ArrayList<>();
1564 for (String mac : macAddress) {
1565 physAddresses.add(new PhysAddress(mac));
1567 return physAddresses;
1570 public static List<StaticMacEntries> getStaticMacEntries(List<String> staticMacAddresses) {
1571 if (isEmpty(staticMacAddresses)) {
1572 return Collections.EMPTY_LIST;
1574 StaticMacEntriesBuilder staticMacEntriesBuilder = new StaticMacEntriesBuilder();
1575 List<StaticMacEntries> staticMacEntries = new ArrayList<>();
1576 List<PhysAddress> physAddressList = getPhysAddress(staticMacAddresses);
1577 for (PhysAddress physAddress : physAddressList) {
1578 staticMacEntries.add(staticMacEntriesBuilder.setMacAddress(physAddress).build());
1580 return staticMacEntries;
1583 public static InstanceIdentifier<StaticMacEntries> getStaticMacEntriesCfgDataPathIdentifier(String interfaceName,
1584 String macAddress) {
1585 return InstanceIdentifier.builder(ElanInterfaces.class)
1586 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).child(StaticMacEntries.class,
1587 new StaticMacEntriesKey(new PhysAddress(macAddress))).build();
1590 public static List<StaticMacEntries> getDeletedEntries(List<StaticMacEntries> originalStaticMacEntries,
1591 List<StaticMacEntries> updatedStaticMacEntries) {
1592 if (isEmpty(originalStaticMacEntries)) {
1593 return Collections.EMPTY_LIST;
1595 List<StaticMacEntries> deleted = Lists.newArrayList(originalStaticMacEntries);
1596 if (isNotEmpty(updatedStaticMacEntries)) {
1597 deleted.removeAll(updatedStaticMacEntries);
1602 public static <T> List<T> diffOf(List<T> orig, List<T> updated) {
1603 if (isEmpty(orig)) {
1604 return Collections.EMPTY_LIST;
1606 List<T> diff = Lists.newArrayList(orig);
1607 if (isNotEmpty(updated)) {
1608 diff.removeAll(updated);
1613 public static void segregateToBeDeletedAndAddEntries(List<StaticMacEntries> originalStaticMacEntries,
1614 List<StaticMacEntries> updatedStaticMacEntries) {
1615 if (isNotEmpty(updatedStaticMacEntries)) {
1616 List<StaticMacEntries> existingClonedStaticMacEntries = new ArrayList<>();
1617 if (isNotEmpty(originalStaticMacEntries)) {
1618 existingClonedStaticMacEntries.addAll(0, originalStaticMacEntries);
1619 originalStaticMacEntries.removeAll(updatedStaticMacEntries);
1620 updatedStaticMacEntries.removeAll(existingClonedStaticMacEntries);
1625 public static boolean isEmpty(Collection collection) {
1626 return collection == null || collection.isEmpty();
1629 public static boolean isNotEmpty(Collection collection) {
1630 return !isEmpty(collection);
1633 public Optional<IpAddress> getSourceIpAddress(Ethernet ethernet) {
1634 Optional<IpAddress> srcIpAddress = Optional.absent();
1635 if (ethernet.getPayload() == null) {
1636 return srcIpAddress;
1638 byte[] ipAddrBytes = null;
1639 if (ethernet.getPayload() instanceof IPv4) {
1640 IPv4 ipv4 = (IPv4) ethernet.getPayload();
1641 ipAddrBytes = Ints.toByteArray(ipv4.getSourceAddress());
1642 } else if (ethernet.getPayload() instanceof ARP) {
1643 ipAddrBytes = ((ARP) ethernet.getPayload()).getSenderProtocolAddress();
1645 if (ipAddrBytes != null) {
1646 String ipAddr = NWUtil.toStringIpAddress(ipAddrBytes);
1647 return Optional.of(IpAddressBuilder.getDefaultInstance(ipAddr));
1649 return srcIpAddress;
1652 public List<MacEntry> getElanMacEntries(String elanName) {
1653 MacTable macTable = getElanMacTable(elanName);
1654 if (macTable == null) {
1655 return Collections.emptyList();
1657 return macTable.getMacEntry();
1660 public boolean isTunnelInLogicalGroup(String interfaceName) {
1661 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1662 .ietf.interfaces.rev140508.interfaces.Interface configIface =
1663 interfaceManager.getInterfaceInfoFromConfigDataStore(interfaceName);
1664 if (configIface == null) {
1665 configIface = iitmProvider.getInterface(interfaceName);
1667 if (configIface == null) {
1670 IfTunnel ifTunnel = configIface.augmentation(IfTunnel.class);
1671 if (ifTunnel != null && ifTunnel.getTunnelInterfaceType().isAssignableFrom(TunnelTypeVxlan.class)) {
1672 ParentRefs refs = configIface.augmentation(ParentRefs.class);
1673 return refs != null && !Strings.isNullOrEmpty(refs.getParentInterface());
1678 public static InstanceIdentifier<Flow> getFlowIid(Flow flow, BigInteger dpnId) {
1679 FlowKey flowKey = new FlowKey(new FlowId(flow.getId()));
1680 org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId nodeId =
1681 new org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId("openflow:" + dpnId);
1682 org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node nodeDpn =
1683 new NodeBuilder().setId(nodeId).withKey(new NodeKey(nodeId)).build();
1684 return InstanceIdentifier.builder(Nodes.class)
1685 .child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node.class,
1686 nodeDpn.key()).augmentation(FlowCapableNode.class)
1687 .child(Table.class, new TableKey(flow.getTableId())).child(Flow.class, flowKey).build();
1690 public static String getElanInterfaceJobKey(String interfaceName) {
1691 return "elaninterface-" + interfaceName;
1694 public void removeArpResponderFlow(BigInteger dpnId, String ingressInterfaceName, String ipAddress,
1696 LOG.info("Removing the ARP responder flow on DPN {} of Interface {} with IP {}", dpnId, ingressInterfaceName,
1698 ArpResponderUtil.removeFlow(mdsalManager, dpnId, ArpResponderUtil.getFlowId(lportTag, ipAddress));
1701 public static String getRouterPordIdFromElanInstance(DataBroker dataBroker, String elanInstanceName) {
1702 Optional<Subnetmaps> subnetMapsData =
1703 read(dataBroker, LogicalDatastoreType.CONFIGURATION, buildSubnetMapsWildCardPath());
1704 if (subnetMapsData.isPresent()) {
1705 List<Subnetmap> subnetMapList = subnetMapsData.get().getSubnetmap();
1706 if (subnetMapList != null && !subnetMapList.isEmpty()) {
1707 for (Subnetmap subnet : subnetMapList) {
1708 if (subnet.getNetworkId().getValue().equals(elanInstanceName)) {
1709 if (subnet.getRouterInterfacePortId() != null) {
1710 return subnet.getRouterInterfacePortId().getValue();
1719 static InstanceIdentifier<Subnetmaps> buildSubnetMapsWildCardPath() {
1720 return InstanceIdentifier.create(Subnetmaps.class);
1723 public static InstanceIdentifier<Group> getGroupInstanceid(BigInteger dpnId, long groupId) {
1724 return InstanceIdentifier.builder(Nodes.class).child(Node.class, new NodeKey(new NodeId("openflow:" + dpnId)))
1725 .augmentation(FlowCapableNode.class).child(Group.class, new GroupKey(new GroupId(groupId))).build();