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 java.util.Collections.emptyList;
11 import static org.opendaylight.controller.md.sal.binding.api.WriteTransaction.CREATE_MISSING_PARENTS;
12 import static org.opendaylight.genius.infra.Datastore.CONFIGURATION;
14 import com.google.common.base.Optional;
15 import com.google.common.base.Preconditions;
16 import com.google.common.base.Strings;
17 import com.google.common.collect.Lists;
18 import com.google.common.primitives.Ints;
19 import com.google.common.util.concurrent.CheckedFuture;
20 import com.google.common.util.concurrent.FutureCallback;
21 import com.google.common.util.concurrent.Futures;
22 import com.google.common.util.concurrent.ListenableFuture;
23 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.Objects;
30 import java.util.concurrent.ExecutionException;
31 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;
37 import org.apache.commons.lang3.StringUtils;
38 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
39 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
40 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
41 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
42 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
43 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
44 import org.opendaylight.genius.infra.Datastore;
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
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
351 public MacEntry getInterfaceMacEntriesOperationalDataPath(String interfaceName, PhysAddress physAddress) {
352 InstanceIdentifier<MacEntry> existingMacEntryId = getInterfaceMacEntriesIdentifierOperationalDataPath(
353 interfaceName, physAddress);
354 return read(broker, LogicalDatastoreType.OPERATIONAL, existingMacEntryId).orNull();
358 public MacEntry getInterfaceMacEntriesOperationalDataPathFromId(TypedReadTransaction<Operational> tx,
359 InstanceIdentifier<MacEntry> identifier) throws ExecutionException, InterruptedException {
360 return tx.read(identifier).get().orNull();
363 public static InstanceIdentifier<MacEntry> getInterfaceMacEntriesIdentifierOperationalDataPath(String interfaceName,
364 PhysAddress physAddress) {
365 return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class)
366 .child(ElanInterfaceMac.class, new ElanInterfaceMacKey(interfaceName))
367 .child(MacEntry.class, new MacEntryKey(physAddress)).build();
371 // elan-forwarding-tables Operational container
372 public Optional<MacEntry> getMacEntryForElanInstance(String elanName, PhysAddress physAddress) {
373 InstanceIdentifier<MacEntry> macId = getMacEntryOperationalDataPath(elanName, physAddress);
374 return read(broker, LogicalDatastoreType.OPERATIONAL, macId);
377 public Optional<MacEntry> getMacEntryForElanInstance(TypedReadTransaction<Operational> tx, String elanName,
378 PhysAddress physAddress) throws ExecutionException, InterruptedException {
379 InstanceIdentifier<MacEntry> macId = getMacEntryOperationalDataPath(elanName, physAddress);
380 return tx.read(macId).get();
384 public MacEntry getMacEntryFromElanMacId(TypedReadTransaction<Operational> tx,
385 InstanceIdentifier<MacEntry> identifier) throws ExecutionException, InterruptedException {
386 return tx.read(identifier).get().orNull();
389 public static InstanceIdentifier<MacEntry> getMacEntryOperationalDataPath(String elanName,
390 PhysAddress physAddress) {
391 return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class, new MacTableKey(elanName))
392 .child(MacEntry.class, new MacEntryKey(physAddress)).build();
395 public static InstanceIdentifier<MacTable> getElanMacTableOperationalDataPath(String elanName) {
396 return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class, new MacTableKey(elanName))
400 // elan-interface-forwarding-entries Operational container
401 public ElanInterfaceMac getElanInterfaceMacByInterfaceName(String interfaceName) {
402 return getElanInterfaceMacByInterfaceName(broker, interfaceName);
406 public static ElanInterfaceMac getElanInterfaceMacByInterfaceName(DataBroker dataBroker, String interfaceName) {
407 InstanceIdentifier<ElanInterfaceMac> elanInterfaceId = getElanInterfaceMacEntriesOperationalDataPath(
409 return read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanInterfaceId).orNull();
413 * Gets the elan interface mac addresses.
415 * @param interfaceName
417 * @return the elan interface mac addresses
419 public List<PhysAddress> getElanInterfaceMacAddresses(String interfaceName) {
420 List<PhysAddress> macAddresses = new ArrayList<>();
421 ElanInterfaceMac elanInterfaceMac = getElanInterfaceMacByInterfaceName(interfaceName);
422 if (elanInterfaceMac != null && elanInterfaceMac.getMacEntry() != null) {
423 List<MacEntry> macEntries = elanInterfaceMac.getMacEntry();
424 for (MacEntry macEntry : macEntries) {
425 macAddresses.add(macEntry.getMacAddress());
431 public static InstanceIdentifier<ElanInterfaceMac> getElanInterfaceMacEntriesOperationalDataPath(
432 String interfaceName) {
433 return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class)
434 .child(ElanInterfaceMac.class, new ElanInterfaceMacKey(interfaceName)).build();
438 * Returns the list of Interfaces that belong to an Elan on an specific DPN.
439 * Data retrieved from Elan's operational DS: elan-dpn-interfaces container.
441 * @param elanInstanceName
442 * name of the Elan to which the interfaces must belong to
444 * Id of the DPN where the interfaces are located
445 * @return the elan interface Info
448 public DpnInterfaces getElanInterfaceInfoByElanDpn(String elanInstanceName, BigInteger dpId) {
449 InstanceIdentifier<DpnInterfaces> elanDpnInterfacesId = getElanDpnInterfaceOperationalDataPath(elanInstanceName,
451 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfacesId).orNull();
455 * Returns the InstanceIdentifier that points to the Interfaces of an Elan
456 * in a given DPN in the Operational DS. Data retrieved from Elans's
457 * operational DS: dpn-interfaces list
459 * @param elanInstanceName
460 * name of the Elan to which the interfaces must belong to
462 * Id of the DPN where the interfaces are located
463 * @return the elan dpn interface
465 public static InstanceIdentifier<DpnInterfaces> getElanDpnInterfaceOperationalDataPath(String elanInstanceName,
467 return InstanceIdentifier.builder(ElanDpnInterfaces.class)
468 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName))
469 .child(DpnInterfaces.class, new DpnInterfacesKey(dpId)).build();
472 // elan-tag-name-map Operational Container
474 public ElanTagName getElanInfoByElanTag(long elanTag) {
475 InstanceIdentifier<ElanTagName> elanId = getElanInfoEntriesOperationalDataPath(elanTag);
476 Optional<ElanTagName> existingElanInfo = read(broker,
477 LogicalDatastoreType.OPERATIONAL, elanId);
478 return existingElanInfo.orNull();
481 public static InstanceIdentifier<ElanTagName> getElanInfoEntriesOperationalDataPath(long elanTag) {
482 return InstanceIdentifier.builder(ElanTagNameMap.class).child(ElanTagName.class, new ElanTagNameKey(elanTag))
486 // interface-index-tag operational container
487 public Optional<IfIndexInterface> getInterfaceInfoByInterfaceTag(long interfaceTag) {
488 InstanceIdentifier<IfIndexInterface> interfaceId = getInterfaceInfoEntriesOperationalDataPath(interfaceTag);
489 return read(broker, LogicalDatastoreType.OPERATIONAL, interfaceId);
492 public static InstanceIdentifier<IfIndexInterface> getInterfaceInfoEntriesOperationalDataPath(long interfaceTag) {
493 return InstanceIdentifier.builder(IfIndexesInterfaceMap.class)
494 .child(IfIndexInterface.class, new IfIndexInterfaceKey((int) interfaceTag)).build();
497 public static InstanceIdentifier<ElanDpnInterfacesList> getElanDpnOperationDataPath(String elanInstanceName) {
498 return InstanceIdentifier.builder(ElanDpnInterfaces.class)
499 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName)).build();
503 public ElanDpnInterfacesList getElanDpnInterfacesList(String elanName) {
504 InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanName);
505 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orNull();
509 public ElanDpnInterfaces getElanDpnInterfacesList() {
510 InstanceIdentifier<ElanDpnInterfaces> elanDpnInterfaceId = InstanceIdentifier.builder(ElanDpnInterfaces.class)
512 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orNull();
516 * This method is useful get all ELAN participating CSS dpIds to install
517 * program remote dmac entries and updating remote bc groups for tor
520 * @param elanInstanceName
521 * the elan instance name
522 * @return list of dpIds
525 public List<BigInteger> getParticipatingDpnsInElanInstance(String elanInstanceName) {
526 List<BigInteger> dpIds = new ArrayList<>();
527 InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
528 Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = read(broker,
529 LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
530 if (!existingElanDpnInterfaces.isPresent()) {
533 List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().nonnullDpnInterfaces();
534 for (DpnInterfaces dpnInterface : dpnInterfaces) {
535 dpIds.add(dpnInterface.getDpId());
541 * To check given dpId is already present in Elan instance. This can be used
542 * to program flow entry in external tunnel table when a new access port
543 * added for first time into the ELAN instance
547 * @param elanInstanceName
548 * the elan instance name
549 * @return true if dpId is already present, otherwise return false
551 public boolean isDpnAlreadyPresentInElanInstance(BigInteger dpId, String elanInstanceName) {
552 InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
553 Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = read(broker,
554 LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
555 if (!existingElanDpnInterfaces.isPresent()) {
558 List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().nonnullDpnInterfaces();
559 for (DpnInterfaces dpnInterface : dpnInterfaces) {
560 if (Objects.equals(dpnInterface.getDpId(), dpId)) {
568 public ElanForwardingTables getElanForwardingList() {
569 InstanceIdentifier<ElanForwardingTables> elanForwardingTableId = InstanceIdentifier
570 .builder(ElanForwardingTables.class).build();
571 return read(broker, LogicalDatastoreType.OPERATIONAL, elanForwardingTableId).orNull();
574 public static long getElanRemoteBroadCastGroupID(long elanTag) {
575 return ElanConstants.ELAN_GID_MIN + elanTag % ElanConstants.ELAN_GID_MIN * 2;
579 * Gets the elan mac table.
583 * @return the elan mac table
586 public MacTable getElanMacTable(String elanName) {
587 return getElanMacTable(broker, elanName);
591 public static MacTable getElanMacTable(DataBroker dataBroker, String elanName) {
592 InstanceIdentifier<MacTable> elanMacTableId = getElanMacTableOperationalDataPath(elanName);
593 return read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanMacTableId).orNull();
596 public static long getElanLocalBCGId(long elanTag) {
597 return ElanConstants.ELAN_GID_MIN + (elanTag % ElanConstants.ELAN_GID_MIN * 2 - 1);
600 public static long getElanRemoteBCGId(long elanTag) {
601 return ElanConstants.ELAN_GID_MIN + elanTag % ElanConstants.ELAN_GID_MIN * 2;
604 public static long getEtreeLeafLocalBCGId(long etreeLeafTag) {
605 return ElanConstants.ELAN_GID_MIN + (etreeLeafTag % ElanConstants.ELAN_GID_MIN * 2 - 1);
608 public static long getEtreeLeafRemoteBCGId(long etreeLeafTag) {
609 return ElanConstants.ELAN_GID_MIN + etreeLeafTag % ElanConstants.ELAN_GID_MIN * 2;
612 public static BigInteger getElanMetadataLabel(long elanTag, boolean isSHFlagSet) {
613 int shBit = isSHFlagSet ? 1 : 0;
614 return BigInteger.valueOf(elanTag).shiftLeft(24).or(BigInteger.valueOf(shBit));
618 * Setting SMAC, DMAC, UDMAC in this DPN and optionally in other DPNs.
622 * @param interfaceInfo
628 * @param configureRemoteFlows
629 * true if remote dmac flows should be configured as well
630 * @param writeFlowGroupTx
633 public void setupMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo,
634 long macTimeout, String macAddress, boolean configureRemoteFlows,
635 TypedWriteTransaction<Configuration> writeFlowGroupTx) {
636 synchronized (getElanMacDPNKey(elanInfo.getElanTag(), macAddress, interfaceInfo.getDpId())) {
637 setupKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress, mdsalManager,
639 setupOrigDmacFlows(elanInfo, interfaceInfo, macAddress, configureRemoteFlows, mdsalManager,
644 public void setupDMacFlowOnRemoteDpn(ElanInstance elanInfo, InterfaceInfo interfaceInfo, BigInteger dstDpId,
645 String macAddress, TypedWriteTransaction<Configuration> writeFlowTx) {
646 String elanInstanceName = elanInfo.getElanInstanceName();
647 setupRemoteDmacFlow(dstDpId, interfaceInfo.getDpId(), interfaceInfo.getInterfaceTag(), elanInfo.getElanTag(),
648 macAddress, elanInstanceName, writeFlowTx, interfaceInfo.getInterfaceName(), elanInfo);
649 LOG.info("Remote Dmac flow entry created for elan Name:{}, logical port Name:{} and"
650 + " mac address {} on dpn:{}", elanInstanceName, interfaceInfo.getPortName(),
651 macAddress, dstDpId);
655 * Inserts a Flow in SMAC table to state that the MAC has already been
658 private void setupKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
659 String macAddress, IMdsalApiManager mdsalApiManager,
660 TypedWriteTransaction<Configuration> writeFlowGroupTx) {
661 FlowEntity flowEntity = buildKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress);
662 mdsalApiManager.addFlow(writeFlowGroupTx, flowEntity);
663 LOG.debug("Known Smac flow entry created for elan Name:{}, logical Interface port:{} and mac address:{}",
664 elanInfo.getElanInstanceName(), elanInfo.getDescription(), macAddress);
667 public FlowEntity buildKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
669 int lportTag = interfaceInfo.getInterfaceTag();
670 // Matching metadata and eth_src fields
671 List<MatchInfo> mkMatches = new ArrayList<>();
672 mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanInfo.getElanTag(), lportTag),
673 ElanHelper.getElanMetadataMask()));
674 mkMatches.add(new MatchEthernetSource(new MacAddress(macAddress)));
675 List<InstructionInfo> mkInstructions = new ArrayList<>();
676 mkInstructions.add(new InstructionGotoTable(NwConstants.ELAN_DMAC_TABLE));
677 BigInteger dpId = interfaceInfo.getDpId();
678 long elanTag = getElanTag(elanInfo, interfaceInfo);
679 return new FlowEntityBuilder()
681 .setTableId(NwConstants.ELAN_SMAC_TABLE)
682 .setFlowId(getKnownDynamicmacFlowRef(NwConstants.ELAN_SMAC_TABLE, dpId, lportTag, macAddress, elanTag))
684 .setFlowName(elanInfo.getDescription())
685 .setIdleTimeOut((int) macTimeout)
687 .setCookie(ElanConstants.COOKIE_ELAN_KNOWN_SMAC.add(BigInteger.valueOf(elanTag)))
688 .setMatchInfoList(mkMatches)
689 .setInstructionInfoList(mkInstructions)
691 // If Mac timeout is 0, the flow won't be deleted automatically, so no need to get notified
692 .setSendFlowRemFlag(macTimeout != 0)
696 private Long getElanTag(ElanInstance elanInfo, InterfaceInfo interfaceInfo) {
697 EtreeInterface etreeInterface = elanInterfaceCache.getEtreeInterface(interfaceInfo.getInterfaceName()).orNull();
698 if (etreeInterface == null || etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
699 return elanInfo.getElanTag();
701 EtreeInstance etreeInstance = elanInfo.augmentation(EtreeInstance.class);
702 if (etreeInstance == null) {
703 LOG.warn("EtreeInterface {} is connected to a non-Etree network: {}",
704 interfaceInfo.getInterfaceName(), elanInfo.getElanInstanceName());
705 return elanInfo.getElanTag();
707 return etreeInstance.getEtreeLeafTagVal().getValue();
713 * Installs a Flow in INTERNAL_TUNNEL_TABLE of the affected DPN that sends
714 * the packet through the specified interface if the tunnel_id matches the
715 * interface's lportTag.
717 * @param interfaceInfo
719 * @param mdsalApiManager
720 * the mdsal API manager
721 * @param writeFlowGroupTx
722 * the writeFLowGroup tx
724 public void setupTermDmacFlows(InterfaceInfo interfaceInfo, IMdsalApiManager mdsalApiManager,
725 TypedWriteTransaction<Configuration> writeFlowGroupTx) {
726 BigInteger dpId = interfaceInfo.getDpId();
727 int lportTag = interfaceInfo.getInterfaceTag();
728 Flow flow = MDSALUtil.buildFlowNew(NwConstants.INTERNAL_TUNNEL_TABLE,
729 getIntTunnelTableFlowRef(NwConstants.INTERNAL_TUNNEL_TABLE, lportTag), 5,
730 String.format("%s:%d", "ITM Flow Entry ", lportTag), 0, 0,
731 ITMConstants.COOKIE_ITM.add(BigInteger.valueOf(lportTag)),
732 getTunnelIdMatchForFilterEqualsLPortTag(lportTag),
733 getInstructionsInPortForOutGroup(interfaceInfo.getInterfaceName()));
734 mdsalApiManager.addFlow(writeFlowGroupTx, dpId, flow);
735 LOG.debug("Terminating service table flow entry created on dpn:{} for logical Interface port:{}", dpId,
736 interfaceInfo.getPortName());
740 * Constructs the FlowName for flows installed in the Internal Tunnel Table,
741 * consisting in tableId + elanTag.
747 * @return the Internal tunnel
749 public static String getIntTunnelTableFlowRef(short tableId, int elanTag) {
750 return new StringBuffer().append(tableId).append(elanTag).toString();
754 * Constructs the Matches that checks that the tunnel_id field contains a
758 * lportTag that must be checked against the tunnel_id field
759 * @return the list of match Info
761 public static List<MatchInfo> getTunnelIdMatchForFilterEqualsLPortTag(int lportTag) {
762 List<MatchInfo> mkMatches = new ArrayList<>();
764 mkMatches.add(new MatchTunnelId(BigInteger.valueOf(lportTag)));
769 * Constructs the Instructions that take the packet over a given interface.
772 * Name of the interface where the packet must be sent over. It
773 * can be a local interface or a tunnel interface (internal or
775 * @return the Instruction
777 public List<Instruction> getInstructionsInPortForOutGroup(String ifName) {
778 List<Instruction> mkInstructions = new ArrayList<>();
779 List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
781 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
782 return mkInstructions;
786 * Returns the list of Actions to be taken when sending the packet through
787 * an Elan interface. Note that this interface can refer to an ElanInterface
788 * where the Elan VM is attached to a DPN or an ITM tunnel interface where
789 * Elan traffic can be sent through. In this latter case, the tunnelKey is
790 * mandatory and it can hold serviceId for internal tunnels or the VNI for
797 * @return the egress actions for interface
799 @SuppressWarnings("checkstyle:IllegalCatch")
801 public List<Action> getEgressActionsForInterface(String ifName, @Nullable Long tunnelKey) {
802 List<Action> listAction = new ArrayList<>();
804 GetEgressActionsForInterfaceInput getEgressActionInput = new GetEgressActionsForInterfaceInputBuilder()
805 .setIntfName(ifName).setTunnelKey(tunnelKey).build();
806 Future<RpcResult<GetEgressActionsForInterfaceOutput>> result = interfaceManagerRpcService
807 .getEgressActionsForInterface(getEgressActionInput);
808 RpcResult<GetEgressActionsForInterfaceOutput> rpcResult = result.get();
809 if (!rpcResult.isSuccessful()) {
810 LOG.debug("RPC Call to Get egress actions for interface {} returned with Errors {}", ifName,
811 rpcResult.getErrors());
813 listAction = rpcResult.getResult().nonnullAction();
815 } catch (Exception e) {
816 LOG.warn("Exception when egress actions for interface {}", ifName, e);
821 private void setupOrigDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
822 boolean configureRemoteFlows, IMdsalApiManager mdsalApiManager,
823 TypedWriteTransaction<Configuration> writeFlowGroupTx) {
824 BigInteger dpId = interfaceInfo.getDpId();
825 String ifName = interfaceInfo.getInterfaceName();
826 long ifTag = interfaceInfo.getInterfaceTag();
827 String elanInstanceName = elanInfo.getElanInstanceName();
829 Long elanTag = elanInfo.getElanTag();
831 setupLocalDmacFlow(elanTag, dpId, ifName, macAddress, elanInfo, mdsalApiManager, ifTag,
833 LOG.debug("Dmac flow entry created for elan Name:{}, logical port Name:{} mand mac address:{} "
834 + "on dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, dpId);
836 if (!configureRemoteFlows) {
840 List<DpnInterfaces> elanDpns = getInvolvedDpnsInElan(elanInstanceName);
841 for (DpnInterfaces elanDpn : elanDpns) {
843 if (Objects.equals(elanDpn.getDpId(), dpId)) {
847 // Check for the Remote DPN present in Inventory Manager
848 if (!isDpnPresent(elanDpn.getDpId())) {
852 // For remote DPNs a flow is needed to indicate that packets of this ELAN going to this MAC need to be
853 // forwarded through the appropriate ITM tunnel
854 setupRemoteDmacFlow(elanDpn.getDpId(), // srcDpn (the remote DPN in this case)
855 dpId, // dstDpn (the local DPN)
856 interfaceInfo.getInterfaceTag(), // lportTag of the local interface
857 elanTag, // identifier of the Elan
858 macAddress, // MAC to be programmed in remote DPN
859 elanInstanceName, writeFlowGroupTx, ifName, elanInfo
861 LOG.debug("Remote Dmac flow entry created for elan Name:{}, logical port Name:{} and mac address:{} on"
862 + " dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, elanDpn.getDpId());
865 // TODO: Make sure that the same is performed against the ElanDevices.
869 public List<DpnInterfaces> getInvolvedDpnsInElan(String elanName) {
870 return getElanDPNByName(elanName);
874 public List<DpnInterfaces> getElanDPNByName(String elanInstanceName) {
875 InstanceIdentifier<ElanDpnInterfacesList> elanIdentifier = getElanDpnOperationDataPath(elanInstanceName);
876 return MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL, elanIdentifier).toJavaUtil().map(
877 ElanDpnInterfacesList::getDpnInterfaces).orElse(emptyList());
880 private void setupLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
881 ElanInstance elanInfo, IMdsalApiManager mdsalApiManager, long ifTag,
882 TypedWriteTransaction<Configuration> writeFlowGroupTx) {
883 Flow flowEntity = buildLocalDmacFlowEntry(elanTag, dpId, ifName, macAddress, elanInfo, ifTag);
884 mdsalApiManager.addFlow(writeFlowGroupTx, dpId, flowEntity);
885 installEtreeLocalDmacFlow(elanTag, dpId, ifName, macAddress, elanInfo, ifTag, writeFlowGroupTx);
888 private void installEtreeLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
889 ElanInstance elanInfo, long ifTag, TypedWriteTransaction<Configuration> writeFlowGroupTx) {
890 EtreeInterface etreeInterface = elanInterfaceCache.getEtreeInterface(ifName).orNull();
891 if (etreeInterface != null && etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
892 EtreeLeafTagName etreeTagName = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
893 if (etreeTagName == null) {
894 LOG.warn("Interface {} seems like it belongs to Etree but etreeTagName from elanTag {} is null",
897 Flow flowEntity = buildLocalDmacFlowEntry(etreeTagName.getEtreeLeafTag().getValue(), dpId, ifName,
898 macAddress, elanInfo, ifTag);
899 mdsalManager.addFlow(writeFlowGroupTx, dpId, flowEntity);
904 public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, long lporTag, String macAddress,
906 return String.valueOf(tableId) + elanTag + dpId + lporTag + macAddress;
909 public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, BigInteger remoteDpId,
910 String macAddress, long elanTag) {
911 return String.valueOf(tableId) + elanTag + dpId + remoteDpId + macAddress;
914 public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, String macAddress, long elanTag) {
915 return String.valueOf(tableId) + elanTag + dpId + macAddress;
918 public static String getKnownDynamicmacFlowRef(short elanDmacTable, BigInteger dpId, String extDeviceNodeId,
919 String dstMacAddress, long elanTag, boolean shFlag) {
920 return String.valueOf(elanDmacTable) + elanTag + dpId + extDeviceNodeId + dstMacAddress + shFlag;
924 * Builds the flow to be programmed in the DMAC table of the local DPN (that
925 * is, where the MAC is attached to). This flow consists in:
927 * <p>Match: + elanTag in metadata + packet goes to a MAC locally attached
928 * Actions: + optionally, pop-vlan + set-vlan-id + output to ifName's
945 public Flow buildLocalDmacFlowEntry(long elanTag, BigInteger dpId, String ifName, String macAddress,
946 ElanInstance elanInfo, long ifTag) {
948 List<MatchInfo> mkMatches = new ArrayList<>();
949 mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
950 mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddress)));
952 List<Instruction> mkInstructions = new ArrayList<>();
953 List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
954 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
955 Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
956 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, ifTag, macAddress, elanTag), 20,
957 elanInfo.getElanInstanceName(), 0, 0, ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(
958 BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
963 public void setupRemoteDmacFlow(BigInteger srcDpId, BigInteger destDpId, int lportTag, long elanTag,
964 String macAddress, String displayName, TypedWriteTransaction<Configuration> writeFlowGroupTx,
965 String interfaceName, ElanInstance elanInstance) {
966 if (interfaceManager.isExternalInterface(interfaceName)) {
967 LOG.debug("Ignoring install remote DMAC {} flow on provider interface {} elan {}",
968 macAddress, interfaceName, elanInstance.getElanInstanceName());
972 // if openstack-vni-semantics are enforced, segmentation ID is passed as network VNI for VxLAN based provider
973 // networks, 0 otherwise
974 long lportTagOrVni = !isOpenstackVniSemanticsEnforced() ? lportTag : isVxlanNetworkOrVxlanSegment(elanInstance)
975 ? getVxlanSegmentationId(elanInstance) : 0;
976 flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTagOrVni, elanTag, macAddress, displayName,
978 mdsalManager.addFlow(writeFlowGroupTx, srcDpId, flowEntity);
979 setupEtreeRemoteDmacFlow(srcDpId, destDpId, lportTagOrVni, elanTag, macAddress, displayName, interfaceName,
980 writeFlowGroupTx, elanInstance);
983 private void setupEtreeRemoteDmacFlow(BigInteger srcDpId, BigInteger destDpId, long lportTagOrVni, long elanTag,
984 String macAddress, String displayName, String interfaceName,
985 TypedWriteTransaction<Configuration> writeFlowGroupTx,
986 ElanInstance elanInstance) {
988 EtreeInterface etreeInterface = elanInterfaceCache.getEtreeInterface(interfaceName).orNull();
989 if (etreeInterface != null && etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
990 EtreeLeafTagName etreeTagName = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
991 if (etreeTagName == null) {
992 LOG.warn("Interface {} seems like it belongs to Etree but etreeTagName from elanTag {} is null.",
993 interfaceName, elanTag);
995 flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTagOrVni,
996 etreeTagName.getEtreeLeafTag().getValue(), macAddress, displayName, elanInstance);
997 mdsalManager.addFlow(writeFlowGroupTx, srcDpId, flowEntity);
1003 * Builds a Flow to be programmed in a remote DPN's DMAC table. This flow
1004 * consists in: Match: + elanTag in packet's metadata + packet going to a
1005 * MAC known to be located in another DPN Actions: + set_tunnel_id
1006 * + output ITM internal tunnel interface with the other DPN
1012 * @param lportTagOrVni
1013 * lportTag or network VNI
1018 * @param displayName
1020 * @param elanInstance
1022 * @return the flow remote Dmac
1024 @SuppressWarnings("checkstyle:IllegalCatch")
1025 public Flow buildRemoteDmacFlowEntry(BigInteger srcDpId, BigInteger destDpId, long lportTagOrVni, long elanTag,
1026 String macAddress, String displayName, ElanInstance elanInstance) {
1027 List<MatchInfo> mkMatches = new ArrayList<>();
1028 mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
1029 mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddress)));
1031 List<Instruction> mkInstructions = new ArrayList<>();
1033 // List of Action for the provided Source and Destination DPIDs
1035 List<Action> actions = null;
1036 if (isVxlanNetworkOrVxlanSegment(elanInstance)) {
1037 actions = elanItmUtils.getInternalTunnelItmEgressAction(srcDpId, destDpId, lportTagOrVni);
1038 } else if (isVlan(elanInstance) || isFlat(elanInstance)) {
1039 String interfaceName = getExternalElanInterface(elanInstance.getElanInstanceName(), srcDpId);
1040 if (null == interfaceName) {
1041 LOG.info("buildRemoteDmacFlowEntry: Could not find interfaceName for {} {}", srcDpId,
1044 actions = getEgressActionsForInterface(interfaceName, null);
1046 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
1047 } catch (Exception e) {
1048 LOG.error("Could not get egress actions to add to flow for srcDpId {}, destDpId {}, lportTag/VNI {}",
1049 srcDpId, destDpId, lportTagOrVni, e);
1052 Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
1053 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, srcDpId, destDpId, macAddress, elanTag),
1055 displayName, 0, /* idleTimeout */
1056 0, /* hardTimeout */
1057 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
1063 public void deleteMacFlows(@Nullable ElanInstance elanInfo, @Nullable InterfaceInfo interfaceInfo,
1064 MacEntry macEntry, TypedReadWriteTransaction<Configuration> flowTx)
1065 throws ExecutionException, InterruptedException {
1066 if (elanInfo == null || interfaceInfo == null) {
1069 String macAddress = macEntry.getMacAddress().getValue();
1070 synchronized (getElanMacDPNKey(elanInfo.getElanTag(), macAddress, interfaceInfo.getDpId())) {
1071 deleteMacFlows(elanInfo, interfaceInfo, macAddress, /* alsoDeleteSMAC */ true, flowTx);
1075 public void deleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1076 boolean deleteSmac, TypedReadWriteTransaction<Configuration> flowTx)
1077 throws ExecutionException, InterruptedException {
1078 String elanInstanceName = elanInfo.getElanInstanceName();
1079 List<DpnInterfaces> remoteFEs = getInvolvedDpnsInElan(elanInstanceName);
1080 BigInteger srcdpId = interfaceInfo.getDpId();
1081 boolean isFlowsRemovedInSrcDpn = false;
1082 for (DpnInterfaces dpnInterface : remoteFEs) {
1083 Long elanTag = elanInfo.getElanTag();
1084 BigInteger dstDpId = dpnInterface.getDpId();
1085 if (executeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1086 elanTag, dstDpId, flowTx)) {
1087 isFlowsRemovedInSrcDpn = true;
1089 executeEtreeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1090 elanTag, dstDpId, flowTx);
1092 if (!isFlowsRemovedInSrcDpn) {
1093 deleteSmacAndDmacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, flowTx);
1097 private void executeEtreeDeleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1098 boolean deleteSmac, String elanInstanceName, BigInteger srcdpId, Long elanTag, BigInteger dstDpId,
1099 TypedReadWriteTransaction<Configuration> flowTx) throws ExecutionException, InterruptedException {
1100 EtreeLeafTagName etreeLeafTag = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
1101 if (etreeLeafTag != null) {
1102 executeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1103 etreeLeafTag.getEtreeLeafTag().getValue(), dstDpId, flowTx);
1107 private boolean executeDeleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1108 boolean deleteSmac, String elanInstanceName, BigInteger srcdpId, Long elanTag, BigInteger dstDpId,
1109 TypedReadWriteTransaction<Configuration> flowTx) throws ExecutionException, InterruptedException {
1110 boolean isFlowsRemovedInSrcDpn = false;
1111 if (dstDpId.equals(srcdpId)) {
1112 isFlowsRemovedInSrcDpn = true;
1113 deleteSmacAndDmacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, flowTx);
1114 } else if (isDpnPresent(dstDpId)) {
1116 .removeFlow(flowTx, dstDpId,
1117 MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, getKnownDynamicmacFlowRef(
1118 NwConstants.ELAN_DMAC_TABLE, dstDpId, srcdpId, macAddress, elanTag)));
1119 LOG.debug("Dmac flow entry deleted for elan:{}, logical interface port:{} and mac address:{} on dpn:{}",
1120 elanInstanceName, interfaceInfo.getPortName(), macAddress, dstDpId);
1122 return isFlowsRemovedInSrcDpn;
1125 private void deleteSmacAndDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1126 boolean deleteSmac, TypedReadWriteTransaction<Configuration> flowTx)
1127 throws ExecutionException, InterruptedException {
1128 String elanInstanceName = elanInfo.getElanInstanceName();
1129 long ifTag = interfaceInfo.getInterfaceTag();
1130 BigInteger srcdpId = interfaceInfo.getDpId();
1131 Long elanTag = elanInfo.getElanTag();
1134 .removeFlow(flowTx, srcdpId,
1135 MDSALUtil.buildFlow(NwConstants.ELAN_SMAC_TABLE, getKnownDynamicmacFlowRef(
1136 NwConstants.ELAN_SMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)));
1138 mdsalManager.removeFlow(flowTx, srcdpId,
1139 MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE,
1140 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)));
1141 LOG.debug("All the required flows deleted for elan:{}, logical Interface port:{} and MAC address:{} on dpn:{}",
1142 elanInstanceName, interfaceInfo.getPortName(), macAddress, srcdpId);
1146 * Updates the Elan information in the Operational DS. It also updates the
1147 * ElanInstance in the Config DS by setting the adquired elanTag.
1151 * @param elanInstanceAdded
1152 * the elan instance added
1153 * @param elanInterfaces
1154 * the elan interfaces
1158 * @return the updated ELAN instance.
1160 public static ElanInstance updateOperationalDataStore(IdManagerService idManager,
1161 ElanInstance elanInstanceAdded, List<String> elanInterfaces, TypedWriteTransaction<Configuration> confTx,
1162 TypedWriteTransaction<Operational> operTx) {
1163 String elanInstanceName = elanInstanceAdded.getElanInstanceName();
1164 Long elanTag = elanInstanceAdded.getElanTag();
1165 if (elanTag == null || elanTag == 0L) {
1166 elanTag = retrieveNewElanTag(idManager, elanInstanceName);
1168 Elan elanInfo = new ElanBuilder().setName(elanInstanceName).setElanInterfaces(elanInterfaces)
1169 .withKey(new ElanKey(elanInstanceName)).build();
1171 // Add the ElanState in the elan-state operational data-store
1172 operTx.put(getElanInstanceOperationalDataPath(elanInstanceName), elanInfo, CREATE_MISSING_PARENTS);
1174 // Add the ElanMacTable in the elan-mac-table operational data-store
1175 MacTable elanMacTable = new MacTableBuilder().withKey(new MacTableKey(elanInstanceName)).build();
1176 operTx.put(getElanMacTableOperationalDataPath(elanInstanceName), elanMacTable, CREATE_MISSING_PARENTS);
1178 ElanTagNameBuilder elanTagNameBuilder = new ElanTagNameBuilder().setElanTag(elanTag)
1179 .withKey(new ElanTagNameKey(elanTag)).setName(elanInstanceName);
1180 long etreeLeafTag = -1;
1181 if (isEtreeInstance(elanInstanceAdded)) {
1182 etreeLeafTag = retrieveNewElanTag(idManager,elanInstanceName + ElanConstants
1184 EtreeLeafTagName etreeLeafTagName = new EtreeLeafTagNameBuilder()
1185 .setEtreeLeafTag(new EtreeLeafTag(etreeLeafTag)).build();
1186 elanTagNameBuilder.addAugmentation(EtreeLeafTagName.class, etreeLeafTagName);
1187 addTheLeafTagAsElanTag(elanInstanceName, etreeLeafTag, operTx);
1189 ElanTagName elanTagName = elanTagNameBuilder.build();
1191 // Add the ElanTag to ElanName in the elan-tag-name Operational
1193 operTx.put(getElanInfoEntriesOperationalDataPath(elanTag), elanTagName);
1195 // Updates the ElanInstance Config DS by setting the just acquired
1197 ElanInstanceBuilder elanInstanceBuilder = new ElanInstanceBuilder().setElanInstanceName(elanInstanceName)
1198 .setDescription(elanInstanceAdded.getDescription())
1199 .setMacTimeout(elanInstanceAdded.getMacTimeout() == null
1200 ? Long.valueOf(ElanConstants.DEFAULT_MAC_TIME_OUT) : elanInstanceAdded.getMacTimeout())
1201 .withKey(elanInstanceAdded.key()).setElanTag(elanTag);
1202 if (isEtreeInstance(elanInstanceAdded)) {
1203 EtreeInstance etreeInstance = new EtreeInstanceBuilder().setEtreeLeafTagVal(new EtreeLeafTag(etreeLeafTag))
1205 elanInstanceBuilder.addAugmentation(EtreeInstance.class, etreeInstance);
1207 ElanInstance elanInstanceWithTag = elanInstanceBuilder.build();
1208 confTx.merge(ElanHelper.getElanInstanceConfigurationDataPath(elanInstanceName), elanInstanceWithTag,
1209 CREATE_MISSING_PARENTS);
1210 return elanInstanceWithTag;
1213 private static void addTheLeafTagAsElanTag(String elanInstanceName, long etreeLeafTag,
1214 TypedWriteTransaction<Operational> tx) {
1215 ElanTagName etreeTagAsElanTag = new ElanTagNameBuilder().setElanTag(etreeLeafTag)
1216 .withKey(new ElanTagNameKey(etreeLeafTag)).setName(elanInstanceName).build();
1217 tx.put(getElanInfoEntriesOperationalDataPath(etreeLeafTag), etreeTagAsElanTag);
1220 private static boolean isEtreeInstance(ElanInstance elanInstanceAdded) {
1221 return elanInstanceAdded.augmentation(EtreeInstance.class) != null;
1224 public boolean isDpnPresent(BigInteger dpnId) {
1225 String dpn = String.format("%s:%s", "openflow", dpnId);
1226 NodeId nodeId = new NodeId(dpn);
1228 InstanceIdentifier<Node> node = InstanceIdentifier.builder(Nodes.class).child(Node.class, new NodeKey(nodeId))
1230 return read(broker, LogicalDatastoreType.CONFIGURATION, node).isPresent();
1233 public static ServicesInfo getServiceInfo(String elanInstanceName, String interfaceName) {
1234 return InterfaceServiceUtil.buildServiceInfo(elanInstanceName + "." + interfaceName,
1235 ElanConstants.ELAN_SERVICE_PRIORITY);
1238 public static String getElanServiceName(String elanName, String interfaceName) {
1239 return "elan." + elanName + interfaceName;
1242 public static BoundServices getBoundServices(String serviceName, short servicePriority, int flowPriority,
1243 BigInteger cookie, List<Instruction> instructions) {
1244 StypeOpenflowBuilder augBuilder = new StypeOpenflowBuilder().setFlowCookie(cookie).setFlowPriority(flowPriority)
1245 .setInstruction(instructions);
1246 return new BoundServicesBuilder().withKey(new BoundServicesKey(servicePriority)).setServiceName(serviceName)
1247 .setServicePriority(servicePriority).setServiceType(ServiceTypeFlowBased.class)
1248 .addAugmentation(StypeOpenflow.class, augBuilder.build()).build();
1251 public static InstanceIdentifier<BoundServices> buildServiceId(String interfaceName, short serviceIndex) {
1252 return InstanceIdentifier.builder(ServiceBindings.class)
1253 .child(ServicesInfo.class, new ServicesInfoKey(interfaceName, ServiceModeIngress.class))
1254 .child(BoundServices.class, new BoundServicesKey(serviceIndex)).build();
1257 public static List<MatchInfo> getTunnelMatchesForServiceId(int elanTag) {
1258 List<MatchInfo> mkMatches = new ArrayList<>();
1259 // Matching metadata
1260 mkMatches.add(new MatchTunnelId(BigInteger.valueOf(elanTag)));
1265 public void removeTerminatingServiceAction(BigInteger destDpId, int serviceId) {
1266 RemoveTerminatingServiceActionsInput input = new RemoveTerminatingServiceActionsInputBuilder()
1267 .setDpnId(destDpId).setServiceId(serviceId).build();
1268 Future<RpcResult<RemoveTerminatingServiceActionsOutput>> futureObject =
1269 itmRpcService.removeTerminatingServiceActions(input);
1271 RpcResult<RemoveTerminatingServiceActionsOutput> result = futureObject.get();
1272 if (result.isSuccessful()) {
1273 LOG.debug("Successfully completed removeTerminatingServiceActions for ELAN with serviceId {} on "
1274 + "dpn {}", serviceId, destDpId);
1276 LOG.debug("Failure in removeTerminatingServiceAction RPC call for ELAN with serviceId {} on "
1277 + "dpn {}", serviceId, destDpId);
1279 } catch (InterruptedException | ExecutionException e) {
1280 LOG.error("Error in RPC call removeTerminatingServiceActions for ELAN with serviceId {} on "
1281 + "dpn {}", serviceId, destDpId, e);
1286 * Gets the external tunnel.
1288 * @param sourceDevice
1290 * @param destinationDevice
1291 * the destination device
1292 * @param datastoreType
1293 * the datastore type
1294 * @return the external tunnel
1297 public ExternalTunnel getExternalTunnel(String sourceDevice, String destinationDevice,
1298 LogicalDatastoreType datastoreType) {
1299 Class<? extends TunnelTypeBase> tunType = TunnelTypeVxlan.class;
1300 InstanceIdentifier<ExternalTunnel> iid = InstanceIdentifier.builder(ExternalTunnelList.class)
1301 .child(ExternalTunnel.class, new ExternalTunnelKey(destinationDevice, sourceDevice, tunType)).build();
1302 return read(broker, datastoreType, iid).orNull();
1306 * Gets the external tunnel.
1308 * @param interfaceName
1309 * the interface name
1310 * @param datastoreType
1311 * the datastore type
1312 * @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(
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
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(@Nullable 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(@Nullable 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);
1528 public String getExternalElanInterface(String elanInstanceName, BigInteger dpnId) {
1529 DpnInterfaces dpnInterfaces = getElanInterfaceInfoByElanDpn(elanInstanceName, dpnId);
1530 if (dpnInterfaces == null || dpnInterfaces.getInterfaces() == null) {
1531 LOG.trace("Elan {} does not have interfaces in DPN {}", elanInstanceName, dpnId);
1535 for (String dpnInterface : dpnInterfaces.getInterfaces()) {
1536 if (interfaceManager.isExternalInterface(dpnInterface)) {
1537 return dpnInterface;
1541 LOG.trace("Elan {} does not have any external interace attached to DPN {}", elanInstanceName, dpnId);
1545 public static String getElanMacDPNKey(long elanTag, String macAddress, BigInteger dpnId) {
1546 String elanMacDmacDpnKey = "MAC-" + macAddress + " ELAN_TAG-" + elanTag + "DPN_ID-" + dpnId;
1547 return elanMacDmacDpnKey.intern();
1550 public static String getElanMacKey(long elanTag, String macAddress) {
1551 String elanMacKey = "MAC-" + macAddress + " ELAN_TAG-" + elanTag;
1552 return elanMacKey.intern();
1555 public static List<ListenableFuture<Void>>
1556 returnFailedListenableFutureIfTransactionCommitFailedExceptionCauseOrElseThrow(RuntimeException exception) {
1558 Throwable cause = exception.getCause();
1559 if (cause != null && cause instanceof TransactionCommitFailedException) {
1560 return Collections.singletonList(Futures.immediateFailedFuture(cause));
1566 public static List<PhysAddress> getPhysAddress(List<String> macAddress) {
1567 Preconditions.checkNotNull(macAddress, "macAddress cannot be null");
1568 List<PhysAddress> physAddresses = new ArrayList<>();
1569 for (String mac : macAddress) {
1570 physAddresses.add(new PhysAddress(mac));
1572 return physAddresses;
1575 public static List<StaticMacEntries> getStaticMacEntries(List<String> staticMacAddresses) {
1576 if (isEmpty(staticMacAddresses)) {
1577 return Collections.EMPTY_LIST;
1579 StaticMacEntriesBuilder staticMacEntriesBuilder = new StaticMacEntriesBuilder();
1580 List<StaticMacEntries> staticMacEntries = new ArrayList<>();
1581 List<PhysAddress> physAddressList = getPhysAddress(staticMacAddresses);
1582 for (PhysAddress physAddress : physAddressList) {
1583 staticMacEntries.add(staticMacEntriesBuilder.setMacAddress(physAddress).build());
1585 return staticMacEntries;
1588 public static InstanceIdentifier<StaticMacEntries> getStaticMacEntriesCfgDataPathIdentifier(String interfaceName,
1589 String macAddress) {
1590 return InstanceIdentifier.builder(ElanInterfaces.class)
1591 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).child(StaticMacEntries.class,
1592 new StaticMacEntriesKey(new PhysAddress(macAddress))).build();
1595 public static List<StaticMacEntries> getDeletedEntries(List<StaticMacEntries> originalStaticMacEntries,
1596 List<StaticMacEntries> updatedStaticMacEntries) {
1597 if (isEmpty(originalStaticMacEntries)) {
1598 return Collections.EMPTY_LIST;
1600 List<StaticMacEntries> deleted = Lists.newArrayList(originalStaticMacEntries);
1601 if (isNotEmpty(updatedStaticMacEntries)) {
1602 deleted.removeAll(updatedStaticMacEntries);
1607 public static <T> List<T> diffOf(List<T> orig, List<T> updated) {
1608 if (isEmpty(orig)) {
1609 return Collections.EMPTY_LIST;
1611 List<T> diff = Lists.newArrayList(orig);
1612 if (isNotEmpty(updated)) {
1613 diff.removeAll(updated);
1618 public static void segregateToBeDeletedAndAddEntries(List<StaticMacEntries> originalStaticMacEntries,
1619 List<StaticMacEntries> updatedStaticMacEntries) {
1620 if (isNotEmpty(updatedStaticMacEntries)) {
1621 List<StaticMacEntries> existingClonedStaticMacEntries = new ArrayList<>();
1622 if (isNotEmpty(originalStaticMacEntries)) {
1623 existingClonedStaticMacEntries.addAll(0, originalStaticMacEntries);
1624 originalStaticMacEntries.removeAll(updatedStaticMacEntries);
1625 updatedStaticMacEntries.removeAll(existingClonedStaticMacEntries);
1630 public static boolean isEmpty(Collection collection) {
1631 return collection == null || collection.isEmpty();
1634 public static boolean isNotEmpty(Collection collection) {
1635 return !isEmpty(collection);
1638 public Optional<IpAddress> getSourceIpAddress(Ethernet ethernet) {
1639 Optional<IpAddress> srcIpAddress = Optional.absent();
1640 if (ethernet.getPayload() == null) {
1641 return srcIpAddress;
1643 byte[] ipAddrBytes = null;
1644 if (ethernet.getPayload() instanceof IPv4) {
1645 IPv4 ipv4 = (IPv4) ethernet.getPayload();
1646 ipAddrBytes = Ints.toByteArray(ipv4.getSourceAddress());
1647 } else if (ethernet.getPayload() instanceof ARP) {
1648 ipAddrBytes = ((ARP) ethernet.getPayload()).getSenderProtocolAddress();
1650 if (ipAddrBytes != null) {
1651 String ipAddr = NWUtil.toStringIpAddress(ipAddrBytes);
1652 return Optional.of(IpAddressBuilder.getDefaultInstance(ipAddr));
1654 return srcIpAddress;
1657 public List<MacEntry> getElanMacEntries(String elanName) {
1658 MacTable macTable = getElanMacTable(elanName);
1659 if (macTable == null) {
1662 return macTable.getMacEntry();
1665 public boolean isTunnelInLogicalGroup(String interfaceName) {
1666 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1667 .ietf.interfaces.rev140508.interfaces.Interface configIface =
1668 interfaceManager.getInterfaceInfoFromConfigDataStore(interfaceName);
1669 if (configIface == null) {
1670 configIface = iitmProvider.getInterface(interfaceName);
1672 if (configIface == null) {
1675 IfTunnel ifTunnel = configIface.augmentation(IfTunnel.class);
1676 if (ifTunnel != null && ifTunnel.getTunnelInterfaceType().isAssignableFrom(TunnelTypeVxlan.class)) {
1677 ParentRefs refs = configIface.augmentation(ParentRefs.class);
1678 return refs != null && !Strings.isNullOrEmpty(refs.getParentInterface());
1683 public static InstanceIdentifier<Flow> getFlowIid(Flow flow, BigInteger dpnId) {
1684 FlowKey flowKey = new FlowKey(new FlowId(flow.getId()));
1685 org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId nodeId =
1686 new org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId("openflow:" + dpnId);
1687 org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node nodeDpn =
1688 new NodeBuilder().setId(nodeId).withKey(new NodeKey(nodeId)).build();
1689 return InstanceIdentifier.builder(Nodes.class)
1690 .child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node.class,
1691 nodeDpn.key()).augmentation(FlowCapableNode.class)
1692 .child(Table.class, new TableKey(flow.getTableId())).child(Flow.class, flowKey).build();
1695 public static String getElanInterfaceJobKey(String interfaceName) {
1696 return "elaninterface-" + interfaceName;
1699 public void removeArpResponderFlow(BigInteger dpnId, String ingressInterfaceName, String ipAddress,
1701 LOG.info("Removing the ARP responder flow on DPN {} of Interface {} with IP {}", dpnId, ingressInterfaceName,
1703 ListenableFutures.addErrorLogging(txRunner.callWithNewReadWriteTransactionAndSubmit(Datastore.CONFIGURATION,
1704 tx -> mdsalManager.removeFlow(tx, dpnId, ArpResponderUtil.getFlowId(lportTag, ipAddress),
1705 NwConstants.ARP_RESPONDER_TABLE)), LOG, "Error removing ARP responder flow");
1709 public static String getRouterPordIdFromElanInstance(DataBroker dataBroker, String elanInstanceName) {
1710 Optional<Subnetmaps> subnetMapsData =
1711 read(dataBroker, LogicalDatastoreType.CONFIGURATION, buildSubnetMapsWildCardPath());
1712 if (subnetMapsData.isPresent()) {
1713 List<Subnetmap> subnetMapList = subnetMapsData.get().getSubnetmap();
1714 if (subnetMapList != null && !subnetMapList.isEmpty()) {
1715 for (Subnetmap subnet : subnetMapList) {
1716 if (subnet.getNetworkId().getValue().equals(elanInstanceName)) {
1717 if (subnet.getRouterInterfacePortId() != null) {
1718 return subnet.getRouterInterfacePortId().getValue();
1727 static InstanceIdentifier<Subnetmaps> buildSubnetMapsWildCardPath() {
1728 return InstanceIdentifier.create(Subnetmaps.class);
1731 public static InstanceIdentifier<Group> getGroupInstanceid(BigInteger dpnId, long groupId) {
1732 return InstanceIdentifier.builder(Nodes.class).child(Node.class, new NodeKey(new NodeId("openflow:" + dpnId)))
1733 .augmentation(FlowCapableNode.class).child(Group.class, new GroupKey(new GroupId(groupId))).build();