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.genius.infra.Datastore.CONFIGURATION;
12 import static org.opendaylight.mdsal.binding.api.WriteTransaction.CREATE_MISSING_PARENTS;
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.FluentFuture;
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;
23 import edu.umd.cs.findbugs.annotations.CheckReturnValue;
24 import java.math.BigInteger;
25 import java.util.ArrayList;
26 import java.util.Collection;
27 import java.util.Collections;
28 import java.util.LinkedHashSet;
29 import java.util.List;
30 import java.util.Locale;
31 import java.util.Objects;
32 import java.util.Optional;
34 import java.util.concurrent.ExecutionException;
35 import java.util.concurrent.Future;
36 import java.util.concurrent.atomic.AtomicLong;
37 import java.util.function.BiFunction;
38 import java.util.function.Function;
39 import java.util.stream.Collectors;
40 import javax.inject.Inject;
41 import javax.inject.Singleton;
42 import org.apache.commons.lang3.StringUtils;
43 import org.eclipse.jdt.annotation.NonNull;
44 import org.eclipse.jdt.annotation.Nullable;
45 import org.opendaylight.genius.datastoreutils.SingleTransactionDataBroker;
46 import org.opendaylight.genius.infra.Datastore;
47 import org.opendaylight.genius.infra.Datastore.Configuration;
48 import org.opendaylight.genius.infra.Datastore.Operational;
49 import org.opendaylight.genius.infra.ManagedNewTransactionRunner;
50 import org.opendaylight.genius.infra.ManagedNewTransactionRunnerImpl;
51 import org.opendaylight.genius.infra.TypedReadTransaction;
52 import org.opendaylight.genius.infra.TypedReadWriteTransaction;
53 import org.opendaylight.genius.infra.TypedWriteTransaction;
54 import org.opendaylight.genius.interfacemanager.globals.InterfaceInfo;
55 import org.opendaylight.genius.interfacemanager.interfaces.IInterfaceManager;
56 import org.opendaylight.genius.itm.api.IITMProvider;
57 import org.opendaylight.genius.itm.globals.ITMConstants;
58 import org.opendaylight.genius.mdsalutil.ActionInfo;
59 import org.opendaylight.genius.mdsalutil.FlowEntity;
60 import org.opendaylight.genius.mdsalutil.FlowEntityBuilder;
61 import org.opendaylight.genius.mdsalutil.InstructionInfo;
62 import org.opendaylight.genius.mdsalutil.MDSALUtil;
63 import org.opendaylight.genius.mdsalutil.MatchInfo;
64 import org.opendaylight.genius.mdsalutil.MetaDataUtil;
65 import org.opendaylight.genius.mdsalutil.NWUtil;
66 import org.opendaylight.genius.mdsalutil.NwConstants;
67 import org.opendaylight.genius.mdsalutil.actions.ActionNxResubmit;
68 import org.opendaylight.genius.mdsalutil.instructions.InstructionApplyActions;
69 import org.opendaylight.genius.mdsalutil.instructions.InstructionGotoTable;
70 import org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager;
71 import org.opendaylight.genius.mdsalutil.matches.MatchEthernetDestination;
72 import org.opendaylight.genius.mdsalutil.matches.MatchEthernetSource;
73 import org.opendaylight.genius.mdsalutil.matches.MatchMetadata;
74 import org.opendaylight.genius.mdsalutil.matches.MatchTunnelId;
75 import org.opendaylight.genius.mdsalutil.packet.ARP;
76 import org.opendaylight.genius.mdsalutil.packet.Ethernet;
77 import org.opendaylight.genius.mdsalutil.packet.IPv4;
78 import org.opendaylight.infrautils.utils.concurrent.LoggingFutures;
79 import org.opendaylight.infrautils.utils.concurrent.NamedLocks;
80 import org.opendaylight.infrautils.utils.concurrent.NamedSimpleReentrantLock.Acquired;
81 import org.opendaylight.mdsal.binding.api.DataBroker;
82 import org.opendaylight.mdsal.binding.api.ReadTransaction;
83 import org.opendaylight.mdsal.binding.api.WriteTransaction;
84 import org.opendaylight.mdsal.common.api.CommitInfo;
85 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
86 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
87 import org.opendaylight.netvirt.elan.arp.responder.ArpResponderUtil;
88 import org.opendaylight.netvirt.elan.cache.ElanInterfaceCache;
89 import org.opendaylight.netvirt.elan.internal.ElanGroupCache;
90 import org.opendaylight.netvirt.elanmanager.api.ElanHelper;
91 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
92 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddressBuilder;
93 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfacesState;
94 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface;
95 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.AdminStatus;
96 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.OperStatus;
97 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
98 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.PhysAddress;
99 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
100 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
101 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
102 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
103 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
104 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
105 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
106 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
107 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInput;
108 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInputBuilder;
109 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdOutput;
110 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdManagerService;
111 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInput;
112 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInputBuilder;
113 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406.IfIndexesInterfaceMap;
114 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._if.indexes._interface.map.IfIndexInterface;
115 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._if.indexes._interface.map.IfIndexInterfaceKey;
116 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfTunnel;
117 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.ParentRefs;
118 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeBase;
119 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeVxlan;
120 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceInput;
121 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceInputBuilder;
122 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceOutput;
123 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.OdlInterfaceRpcService;
124 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceBindings;
125 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceModeIngress;
126 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceTypeFlowBased;
127 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflow;
128 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflowBuilder;
129 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.ServicesInfo;
130 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.ServicesInfoKey;
131 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServices;
132 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesBuilder;
133 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesKey;
134 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.ExternalTunnelList;
135 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnel;
136 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnelKey;
137 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.ItmRpcService;
138 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsInput;
139 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsInputBuilder;
140 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsOutput;
141 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.BucketId;
142 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupId;
143 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupTypes;
144 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.Buckets;
145 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.buckets.Bucket;
146 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.buckets.BucketBuilder;
147 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group;
148 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupKey;
149 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
150 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
151 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
152 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
153 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
154 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.config.rev150710.ElanConfig;
155 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInstance;
156 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInstanceBuilder;
157 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInterface;
158 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInterface.EtreeInterfaceType;
159 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTag;
160 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTagName;
161 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTagNameBuilder;
162 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanDpnInterfaces;
163 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanForwardingTables;
164 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaceForwardingEntries;
165 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaces;
166 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanState;
167 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanTagNameMap;
168 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeFlat;
169 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeVlan;
170 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeVxlan;
171 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan._interface.forwarding.entries.ElanInterfaceMac;
172 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan._interface.forwarding.entries.ElanInterfaceMacKey;
173 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesList;
174 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesListKey;
175 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfaces;
176 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfacesKey;
177 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTable;
178 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTableBuilder;
179 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTableKey;
180 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstance;
181 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstanceBuilder;
182 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.elan.instance.ElanSegments;
183 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterface;
184 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterfaceKey;
185 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntries;
186 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntriesBuilder;
187 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntriesKey;
188 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.Elan;
189 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.ElanBuilder;
190 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.ElanKey;
191 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagName;
192 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagNameBuilder;
193 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagNameKey;
194 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntry;
195 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntryKey;
196 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.Subnetmaps;
197 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.subnetmaps.Subnetmap;
198 import org.opendaylight.yangtools.yang.binding.DataObject;
199 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
200 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.InstanceIdentifierBuilder;
201 import org.opendaylight.yangtools.yang.common.RpcResult;
202 import org.opendaylight.yangtools.yang.common.Uint32;
203 import org.opendaylight.yangtools.yang.common.Uint64;
204 import org.slf4j.Logger;
205 import org.slf4j.LoggerFactory;
208 public class ElanUtils {
209 private static final class ElanLockName {
210 private final String macAddress;
211 private final Uint64 dpnId;
212 private final long elanTag;
214 ElanLockName(long elanTag, String macAddress, Uint64 dpnId) {
215 this.elanTag = elanTag;
216 this.macAddress = macAddress;
221 public int hashCode() {
222 return 31 * Long.hashCode(elanTag) + Objects.hash(macAddress, dpnId);
226 public boolean equals(Object obj) {
230 if (!(obj instanceof ElanLockName)) {
233 final ElanLockName other = (ElanLockName) obj;
234 return elanTag == other.elanTag && Objects.equals(macAddress, other.macAddress)
235 && Objects.equals(dpnId, other.dpnId);
239 private static final Logger LOG = LoggerFactory.getLogger(ElanUtils.class);
240 private static final NamedLocks<ElanLockName> ELAN_LOCKS = new NamedLocks<>();
242 private final DataBroker broker;
243 private final ManagedNewTransactionRunner txRunner;
244 private final IMdsalApiManager mdsalManager;
245 private final OdlInterfaceRpcService interfaceManagerRpcService;
246 private final ItmRpcService itmRpcService;
247 private final IInterfaceManager interfaceManager;
248 private final ElanConfig elanConfig;
249 private final ElanItmUtils elanItmUtils;
250 private final ElanEtreeUtils elanEtreeUtils;
251 private final ElanInterfaceCache elanInterfaceCache;
252 private final IITMProvider iitmProvider;
253 private final ElanGroupCache elanGroupCache;
255 private static final Function<Bucket, Bucket> TO_BUCKET_WITHOUT_ID = (bucket) -> new BucketBuilder(bucket)
256 .setBucketId(new BucketId(0L))
259 private static final BiFunction<Bucket, AtomicLong, Bucket> TO_BUCKET_WITH_ID = (bucket, id)
260 -> new BucketBuilder(bucket)
261 .setBucketId(new BucketId(id.incrementAndGet()))
264 public static final FutureCallback<CommitInfo> DEFAULT_CALLBACK = new FutureCallback<CommitInfo>() {
266 public void onSuccess(CommitInfo result) {
267 LOG.debug("Success in Datastore operation");
271 public void onFailure(Throwable error) {
272 LOG.error("Error in Datastore operation", error);
277 public ElanUtils(DataBroker dataBroker, IMdsalApiManager mdsalManager,
278 OdlInterfaceRpcService interfaceManagerRpcService, ItmRpcService itmRpcService, ElanConfig elanConfig,
279 IInterfaceManager interfaceManager, ElanEtreeUtils elanEtreeUtils, ElanItmUtils elanItmUtils,
280 ElanInterfaceCache elanInterfaceCache, IITMProvider iitmProvider, ElanGroupCache elanGroupCache) {
281 this.broker = dataBroker;
282 this.txRunner = new ManagedNewTransactionRunnerImpl(dataBroker);
283 this.mdsalManager = mdsalManager;
284 this.interfaceManagerRpcService = interfaceManagerRpcService;
285 this.itmRpcService = itmRpcService;
286 this.interfaceManager = interfaceManager;
287 this.elanConfig = elanConfig;
288 this.elanEtreeUtils = elanEtreeUtils;
289 this.elanItmUtils = elanItmUtils;
290 this.elanInterfaceCache = elanInterfaceCache;
291 this.iitmProvider = iitmProvider;
292 this.elanGroupCache = elanGroupCache;
295 public final Boolean isOpenstackVniSemanticsEnforced() {
296 return elanConfig.isOpenstackVniSemanticsEnforced() != null
297 ? elanConfig.isOpenstackVniSemanticsEnforced() : false;
301 * Uses the IdManager to retrieve a brand new ElanTag.
307 * @return the integer
309 public static Uint32 retrieveNewElanTag(IdManagerService idManager, String idKey) {
311 AllocateIdInput getIdInput = new AllocateIdInputBuilder().setPoolName(ElanConstants.ELAN_ID_POOL_NAME)
312 .setIdKey(idKey).build();
315 Future<RpcResult<AllocateIdOutput>> result = idManager.allocateId(getIdInput);
316 RpcResult<AllocateIdOutput> rpcResult = result.get();
317 if (rpcResult.isSuccessful()) {
318 return rpcResult.getResult().getIdValue();
320 LOG.warn("RPC Call to Allocate Id returned with Errors {}", rpcResult.getErrors());
322 } catch (InterruptedException | ExecutionException e) {
323 LOG.warn("Exception when Allocating Id", e);
325 return Uint32.valueOf(0L);
328 public static void releaseId(IdManagerService idManager, String poolName, String idKey) {
329 ReleaseIdInput releaseIdInput = new ReleaseIdInputBuilder().setPoolName(poolName).setIdKey(idKey).build();
330 LoggingFutures.addErrorLogging(idManager.releaseId(releaseIdInput), LOG, "Release Id");
336 * @deprecated Consider using {@link #read2(LogicalDatastoreType, InstanceIdentifier)} with proper exception
338 * @param broker dataBroker
339 * @param datastoreType Logical DataStore type
340 * @param path IID to read
341 * @param <T> T extends DataObject
342 * @return the read value T
345 @SuppressWarnings("checkstyle:IllegalCatch")
346 public static <T extends DataObject> Optional<T> read(@NonNull DataBroker broker,
347 LogicalDatastoreType datastoreType, InstanceIdentifier<T> path) {
348 try (ReadTransaction tx = broker.newReadOnlyTransaction()) {
349 return tx.read(datastoreType, path).get();
350 } catch (ExecutionException | InterruptedException e) {
351 throw new RuntimeException(e);
355 public <T extends DataObject> Optional<T> read2(LogicalDatastoreType datastoreType, InstanceIdentifier<T> path)
356 throws InterruptedException, ExecutionException {
357 try (ReadTransaction tx = broker.newReadOnlyTransaction()) {
358 FluentFuture<Optional<T>> checkedFuture = tx.read(datastoreType, path);
359 return checkedFuture.get();
363 @SuppressWarnings("checkstyle:ForbidCertainMethod")
364 public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
365 InstanceIdentifier<T> path) {
366 WriteTransaction tx = broker.newWriteOnlyTransaction();
367 tx.delete(datastoreType, path);
368 FluentFuture<? extends @NonNull CommitInfo> future = tx.commit();
369 future.addCallback(DEFAULT_CALLBACK, MoreExecutors.directExecutor());
372 public static InstanceIdentifier<ElanInterface> getElanInterfaceConfigurationDataPathId(String interfaceName) {
373 return InstanceIdentifier.builder(ElanInterfaces.class)
374 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).build();
377 // elan-state Operational container
379 public static Elan getElanByName(DataBroker broker, String elanInstanceName) {
380 InstanceIdentifier<Elan> elanIdentifier = getElanInstanceOperationalDataPath(elanInstanceName);
382 return SingleTransactionDataBroker.syncReadOptional(broker, LogicalDatastoreType.OPERATIONAL,
383 elanIdentifier).orElse(null);
384 } catch (ExecutionException | InterruptedException e) {
385 LOG.error("getElanByName: Exception while reading elan-instance DS for the elan instance {}",
386 elanInstanceName, e);
392 public static Elan getElanByName(TypedReadTransaction<Operational> tx, String elanInstanceName)
393 throws ExecutionException, InterruptedException {
394 return tx.read(getElanInstanceOperationalDataPath(elanInstanceName)).get().orElse(null);
397 public static InstanceIdentifier<Elan> getElanInstanceOperationalDataPath(String elanInstanceName) {
398 return InstanceIdentifier.builder(ElanState.class).child(Elan.class, new ElanKey(elanInstanceName)).build();
401 // grouping of forwarding-entries
403 public MacEntry getInterfaceMacEntriesOperationalDataPath(String interfaceName, PhysAddress physAddress) {
404 InstanceIdentifier<MacEntry> existingMacEntryId = getInterfaceMacEntriesIdentifierOperationalDataPath(
405 interfaceName, physAddress);
406 return read(broker, LogicalDatastoreType.OPERATIONAL, existingMacEntryId).orElse(null);
410 public MacEntry getInterfaceMacEntriesOperationalDataPathFromId(TypedReadTransaction<Operational> tx,
411 InstanceIdentifier<MacEntry> identifier) throws ExecutionException, InterruptedException {
412 return tx.read(identifier).get().orElse(null);
415 public static InstanceIdentifier<MacEntry> getInterfaceMacEntriesIdentifierOperationalDataPath(String interfaceName,
416 PhysAddress physAddress) {
417 return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class)
418 .child(ElanInterfaceMac.class, new ElanInterfaceMacKey(interfaceName))
419 .child(MacEntry.class, new MacEntryKey(physAddress)).build();
423 // elan-forwarding-tables Operational container
424 public Optional<MacEntry> getMacEntryForElanInstance(String elanName, PhysAddress physAddress) {
425 InstanceIdentifier<MacEntry> macId = getMacEntryOperationalDataPath(elanName, physAddress);
426 return read(broker, LogicalDatastoreType.OPERATIONAL, macId);
429 public Optional<MacEntry> getMacEntryForElanInstance(TypedReadTransaction<Operational> tx, String elanName,
430 PhysAddress physAddress) throws ExecutionException, InterruptedException {
431 InstanceIdentifier<MacEntry> macId = getMacEntryOperationalDataPath(elanName, physAddress);
432 return tx.read(macId).get();
436 public MacEntry getMacEntryFromElanMacId(TypedReadTransaction<Operational> tx,
437 InstanceIdentifier<MacEntry> identifier) throws ExecutionException, InterruptedException {
438 return tx.read(identifier).get().orElse(null);
441 public static InstanceIdentifier<MacEntry> getMacEntryOperationalDataPath(String elanName,
442 PhysAddress physAddress) {
443 return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class, new MacTableKey(elanName))
444 .child(MacEntry.class, new MacEntryKey(physAddress)).build();
447 public static InstanceIdentifier<MacTable> getElanMacTableOperationalDataPath(String elanName) {
448 return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class, new MacTableKey(elanName))
452 // elan-interface-forwarding-entries Operational container
453 public ElanInterfaceMac getElanInterfaceMacByInterfaceName(String interfaceName) {
454 return getElanInterfaceMacByInterfaceName(broker, interfaceName);
458 public static ElanInterfaceMac getElanInterfaceMacByInterfaceName(DataBroker dataBroker, String interfaceName) {
459 InstanceIdentifier<ElanInterfaceMac> elanInterfaceId = getElanInterfaceMacEntriesOperationalDataPath(
461 return read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanInterfaceId).orElse(null);
464 public static InstanceIdentifier<ElanInterfaceMac> getElanInterfaceMacEntriesOperationalDataPath(
465 String interfaceName) {
466 return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class)
467 .child(ElanInterfaceMac.class, new ElanInterfaceMacKey(interfaceName)).build();
471 * Returns the list of Interfaces that belong to an Elan on an specific DPN.
472 * Data retrieved from Elan's operational DS: elan-dpn-interfaces container.
474 * @param elanInstanceName
475 * name of the Elan to which the interfaces must belong to
477 * Id of the DPN where the interfaces are located
478 * @return the elan interface Info
481 public DpnInterfaces getElanInterfaceInfoByElanDpn(String elanInstanceName, Uint64 dpId) {
482 InstanceIdentifier<DpnInterfaces> elanDpnInterfacesId = getElanDpnInterfaceOperationalDataPath(elanInstanceName,
484 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfacesId).orElse(null);
488 * Returns the InstanceIdentifier that points to the Interfaces of an Elan
489 * in a given DPN in the Operational DS. Data retrieved from Elans's
490 * operational DS: dpn-interfaces list
492 * @param elanInstanceName
493 * name of the Elan to which the interfaces must belong to
495 * Id of the DPN where the interfaces are located
496 * @return the elan dpn interface
498 public static InstanceIdentifier<DpnInterfaces> getElanDpnInterfaceOperationalDataPath(String elanInstanceName,
500 return InstanceIdentifier.builder(ElanDpnInterfaces.class)
501 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName))
502 .child(DpnInterfaces.class, new DpnInterfacesKey(dpId)).build();
505 // elan-tag-name-map Operational Container
507 public ElanTagName getElanInfoByElanTag(Uint32 elanTag) {
508 InstanceIdentifier<ElanTagName> elanId = getElanInfoEntriesOperationalDataPath(elanTag);
509 Optional<ElanTagName> existingElanInfo = read(broker,
510 LogicalDatastoreType.OPERATIONAL, elanId);
511 return existingElanInfo.orElse(null);
514 public static InstanceIdentifier<ElanTagName> getElanInfoEntriesOperationalDataPath(Uint32 elanTag) {
515 return InstanceIdentifier.builder(ElanTagNameMap.class).child(ElanTagName.class, new ElanTagNameKey(elanTag))
519 // interface-index-tag operational container
520 public Optional<IfIndexInterface> getInterfaceInfoByInterfaceTag(Uint32 interfaceTag) {
521 InstanceIdentifier<IfIndexInterface> interfaceId = getInterfaceInfoEntriesOperationalDataPath(interfaceTag);
522 return read(broker, LogicalDatastoreType.OPERATIONAL, interfaceId);
525 public static InstanceIdentifier<IfIndexInterface> getInterfaceInfoEntriesOperationalDataPath(Uint32 interfaceTag) {
526 return InstanceIdentifier.builder(IfIndexesInterfaceMap.class)
527 .child(IfIndexInterface.class,
528 new IfIndexInterfaceKey(Integer.valueOf(interfaceTag.intValue()))).build();
531 public static InstanceIdentifier<ElanDpnInterfacesList> getElanDpnOperationDataPath(String elanInstanceName) {
532 return InstanceIdentifier.builder(ElanDpnInterfaces.class)
533 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName)).build();
537 public ElanDpnInterfacesList getElanDpnInterfacesList(String elanName) {
538 InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanName);
539 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orElse(null);
543 public ElanDpnInterfaces getElanDpnInterfacesList() {
544 InstanceIdentifier<ElanDpnInterfaces> elanDpnInterfaceId = InstanceIdentifier.builder(ElanDpnInterfaces.class)
546 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orElse(null);
550 * This method is useful get all ELAN participating CSS dpIds to install
551 * program remote dmac entries and updating remote bc groups for tor
554 * @param elanInstanceName
555 * the elan instance name
556 * @return list of dpIds
559 public List<Uint64> getParticipatingDpnsInElanInstance(String elanInstanceName) {
560 List<Uint64> dpIds = new ArrayList<>();
561 InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
562 Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = read(broker,
563 LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
564 if (!existingElanDpnInterfaces.isPresent()) {
567 List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().nonnullDpnInterfaces();
568 for (DpnInterfaces dpnInterface : dpnInterfaces) {
569 dpIds.add(dpnInterface.getDpId());
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).orElse(null);
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 Uint64 getElanMetadataLabel(long elanTag, boolean isSHFlagSet) {
613 int shBit = isSHFlagSet ? 1 : 0;
614 return Uint64.valueOf(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 try (Acquired lock = lockElanMacDPN(elanInfo.getElanTag().toJava(), 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, Uint64 dstDpId,
645 String macAddress, TypedWriteTransaction<Configuration> writeFlowTx) {
646 String elanInstanceName = elanInfo.getElanInstanceName();
647 setupRemoteDmacFlow(dstDpId, interfaceInfo.getDpId(), interfaceInfo.getInterfaceTag(),
648 elanInfo.getElanTag(), macAddress, elanInstanceName, writeFlowTx,
649 interfaceInfo.getInterfaceName(), elanInfo);
650 LOG.info("Remote Dmac flow entry created for elan Name:{}, logical port Name:{} and"
651 + " mac address {} on dpn:{}", elanInstanceName, interfaceInfo.getPortName(),
652 macAddress, dstDpId);
656 * Inserts a Flow in SMAC table to state that the MAC has already been
659 private void setupKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
660 String macAddress, IMdsalApiManager mdsalApiManager,
661 TypedWriteTransaction<Configuration> writeFlowGroupTx) {
662 FlowEntity flowEntity = buildKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress);
663 mdsalApiManager.addFlow(writeFlowGroupTx, flowEntity);
664 LOG.debug("Known Smac flow entry created for elan Name:{}, logical Interface port:{} and mac address:{}",
665 elanInfo.getElanInstanceName(), elanInfo.getDescription(), macAddress);
668 public FlowEntity buildKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
670 int lportTag = interfaceInfo.getInterfaceTag();
671 // Matching metadata and eth_src fields
672 List<MatchInfo> mkMatches = new ArrayList<>();
673 mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanInfo.getElanTag().toJava(), lportTag),
674 ElanHelper.getElanMetadataMask()));
675 mkMatches.add(new MatchEthernetSource(new MacAddress(macAddress)));
676 List<InstructionInfo> mkInstructions = new ArrayList<>();
677 mkInstructions.add(new InstructionGotoTable(NwConstants.ELAN_DMAC_TABLE));
678 Uint64 dpId = interfaceInfo.getDpId();
679 Uint32 elanTag = getElanTag(elanInfo, interfaceInfo);
680 return new FlowEntityBuilder()
682 .setTableId(NwConstants.ELAN_SMAC_TABLE)
683 .setFlowId(getKnownDynamicmacFlowRef(elanTag, macAddress))
685 .setFlowName(elanInfo.getDescription())
686 .setIdleTimeOut((int) macTimeout)
688 .setCookie(Uint64.valueOf(ElanConstants.COOKIE_ELAN_KNOWN_SMAC.longValue() + elanTag.longValue()))
689 .setMatchInfoList(mkMatches)
690 .setInstructionInfoList(mkInstructions)
692 // If Mac timeout is 0, the flow won't be deleted automatically, so no need to get notified
693 .setSendFlowRemFlag(macTimeout != 0)
697 private Uint32 getElanTag(ElanInstance elanInfo, InterfaceInfo interfaceInfo) {
698 EtreeInterface etreeInterface = elanInterfaceCache
699 .getEtreeInterface(interfaceInfo.getInterfaceName()).orElse(null);
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 Uint64 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 Uint64.valueOf(ITMConstants.COOKIE_ITM.longValue() + 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 StringBuilder().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(Uint64.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")
803 public List<Action> getEgressActionsForInterface(String ifName, @Nullable Long tunnelKey) {
804 List<Action> listAction = new ArrayList<>();
806 GetEgressActionsForInterfaceInput getEgressActionInput = new GetEgressActionsForInterfaceInputBuilder()
807 .setIntfName(ifName).setTunnelKey(tunnelKey).build();
808 Future<RpcResult<GetEgressActionsForInterfaceOutput>> result = interfaceManagerRpcService
809 .getEgressActionsForInterface(getEgressActionInput);
810 RpcResult<GetEgressActionsForInterfaceOutput> rpcResult = result.get();
811 if (!rpcResult.isSuccessful()) {
812 LOG.debug("RPC Call to Get egress actions for interface {} returned with Errors {}", ifName,
813 rpcResult.getErrors());
815 listAction = rpcResult.getResult().nonnullAction();
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 Uint64 dpId = interfaceInfo.getDpId();
827 String ifName = interfaceInfo.getInterfaceName();
828 long ifTag = interfaceInfo.getInterfaceTag();
829 String elanInstanceName = elanInfo.getElanInstanceName();
831 Uint32 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 (Objects.equals(elanDpn.getDpId(), 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);
879 return SingleTransactionDataBroker.syncReadOptional(broker, LogicalDatastoreType.OPERATIONAL,
880 elanIdentifier).map(ElanDpnInterfacesList::getDpnInterfaces).orElse(emptyList());
881 } catch (ExecutionException | InterruptedException e) {
882 LOG.error("getElanDPNByName: Exception while reading elanDpnInterfaceList DS for the elan "
883 + "instance {}", elanInstanceName, e);
888 private void setupLocalDmacFlow(Uint32 elanTag, Uint64 dpId, String ifName, String macAddress,
889 ElanInstance elanInfo, IMdsalApiManager mdsalApiManager, long ifTag,
890 TypedWriteTransaction<Configuration> writeFlowGroupTx) {
891 Flow flowEntity = buildLocalDmacFlowEntry(elanTag, dpId, ifName, macAddress, elanInfo, ifTag);
892 mdsalApiManager.addFlow(writeFlowGroupTx, dpId, flowEntity);
893 installEtreeLocalDmacFlow(elanTag, dpId, ifName, macAddress, elanInfo, ifTag, writeFlowGroupTx);
896 private void installEtreeLocalDmacFlow(Uint32 elanTag, Uint64 dpId, String ifName, String macAddress,
897 ElanInstance elanInfo, long ifTag, TypedWriteTransaction<Configuration> writeFlowGroupTx) {
898 EtreeInterface etreeInterface = elanInterfaceCache.getEtreeInterface(ifName).orElse(null);
899 if (etreeInterface != null && etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
900 EtreeLeafTagName etreeTagName = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag.longValue());
901 if (etreeTagName == null) {
902 LOG.warn("Interface {} seems like it belongs to Etree but etreeTagName from elanTag {} is null",
905 Flow flowEntity = buildLocalDmacFlowEntry(etreeTagName.getEtreeLeafTag().getValue(), dpId,
906 ifName, macAddress, elanInfo, ifTag);
907 mdsalManager.addFlow(writeFlowGroupTx, dpId, flowEntity);
912 public static String getKnownDynamicmacFlowRef(Uint32 elanTag, String macAddress) {
913 return new StringBuffer().append(elanTag).append(macAddress.toLowerCase(Locale.getDefault())).toString();
916 public static String getKnownDynamicmacFlowRef(short elanDmacTable, Uint64 dpId, String extDeviceNodeId,
917 String dstMacAddress, long elanTag, boolean shFlag) {
918 return String.valueOf(elanDmacTable) + elanTag + dpId + extDeviceNodeId + dstMacAddress + shFlag;
922 * Builds the flow to be programmed in the DMAC table of the local DPN (that
923 * is, where the MAC is attached to). This flow consists in:
925 * <p>Match: + elanTag in metadata + packet goes to a MAC locally attached
926 * Actions: + optionally, pop-vlan + set-vlan-id + output to ifName's
943 public Flow buildLocalDmacFlowEntry(Uint32 elanTag, Uint64 dpId, String ifName, String macAddress,
944 ElanInstance elanInfo, long ifTag) {
946 List<MatchInfo> mkMatches = new ArrayList<>();
947 mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag.longValue()),
948 MetaDataUtil.METADATA_MASK_SERVICE));
949 mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddress)));
951 List<Instruction> mkInstructions = new ArrayList<>();
952 List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
953 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
954 Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
955 getKnownDynamicmacFlowRef(elanTag, macAddress), 20,
956 elanInfo.getElanInstanceName(), 0, 0,
957 Uint64.valueOf(ElanConstants.COOKIE_ELAN_KNOWN_DMAC.longValue() + elanTag.longValue()),
958 mkMatches, mkInstructions);
963 public void setupRemoteDmacFlow(Uint64 srcDpId, Uint64 destDpId, int lportTag, Uint32 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());
971 // if openstack-vni-semantics are enforced, segmentation ID is passed as network VNI for VxLAN based provider
972 // networks, 0 otherwise
973 long lportTagOrVni = !isOpenstackVniSemanticsEnforced() ? lportTag : isVxlanNetworkOrVxlanSegment(elanInstance)
974 ? getVxlanSegmentationId(elanInstance).longValue() : 0;
975 Flow flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTagOrVni, elanTag, macAddress, displayName,
977 mdsalManager.addFlow(writeFlowGroupTx, srcDpId, flowEntity);
978 setupEtreeRemoteDmacFlow(srcDpId, destDpId, lportTagOrVni, elanTag, macAddress, displayName, interfaceName,
979 writeFlowGroupTx, elanInstance);
982 private void setupEtreeRemoteDmacFlow(Uint64 srcDpId, Uint64 destDpId, long lportTagOrVni, Uint32 elanTag,
983 String macAddress, String displayName, String interfaceName,
984 TypedWriteTransaction<Configuration> writeFlowGroupTx,
985 ElanInstance elanInstance) {
987 EtreeInterface etreeInterface = elanInterfaceCache.getEtreeInterface(interfaceName).orElse(null);
988 if (etreeInterface != null && etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
989 EtreeLeafTagName etreeTagName = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag.longValue());
990 if (etreeTagName == null) {
991 LOG.warn("Interface {} seems like it belongs to Etree but etreeTagName from elanTag {} is null.",
992 interfaceName, elanTag);
994 flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTagOrVni,
995 etreeTagName.getEtreeLeafTag().getValue(), macAddress, displayName, elanInstance);
996 mdsalManager.addFlow(writeFlowGroupTx, srcDpId, flowEntity);
1002 * Builds a Flow to be programmed in a remote DPN's DMAC table. This flow
1003 * consists in: Match: + elanTag in packet's metadata + packet going to a
1004 * MAC known to be located in another DPN Actions: + set_tunnel_id
1005 * + output ITM internal tunnel interface with the other DPN
1011 * @param lportTagOrVni
1012 * lportTag or network VNI
1017 * @param displayName
1019 * @param elanInstance
1021 * @return the flow remote Dmac
1023 @SuppressWarnings("checkstyle:IllegalCatch")
1024 public Flow buildRemoteDmacFlowEntry(Uint64 srcDpId, Uint64 destDpId, long lportTagOrVni, Uint32 elanTag,
1025 String macAddress, String displayName, ElanInstance elanInstance) {
1026 List<MatchInfo> mkMatches = new ArrayList<>();
1027 mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag.longValue()),
1028 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(elanTag, macAddress),
1055 displayName, 0, /* idleTimeout */
1056 0, /* hardTimeout */
1057 Uint64.valueOf(ElanConstants.COOKIE_ELAN_KNOWN_DMAC.longValue() + elanTag.longValue()),
1058 mkMatches, mkInstructions);
1064 public void deleteMacFlows(@Nullable ElanInstance elanInfo, @Nullable InterfaceInfo interfaceInfo,
1065 MacEntry macEntry, TypedReadWriteTransaction<Configuration> flowTx)
1066 throws ExecutionException, InterruptedException {
1067 if (elanInfo == null || interfaceInfo == null) {
1070 String macAddress = macEntry.getMacAddress().getValue();
1071 try (Acquired lock = lockElanMacDPN(elanInfo.getElanTag().toJava(),
1072 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 Uint64 srcdpId = interfaceInfo.getDpId();
1083 boolean isFlowsRemovedInSrcDpn = false;
1084 for (DpnInterfaces dpnInterface : remoteFEs) {
1085 Uint32 elanTag = elanInfo.getElanTag();
1086 Uint64 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, Uint64 srcdpId, Uint32 elanTag, Uint64 dstDpId,
1101 TypedReadWriteTransaction<Configuration> flowTx) throws ExecutionException, InterruptedException {
1102 EtreeLeafTagName etreeLeafTag = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag.longValue());
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, Uint64 srcdpId, Uint32 elanTag, Uint64 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(elanTag, macAddress)));
1120 LOG.debug("Dmac flow entry deleted for elan:{}, logical interface port:{} and mac address:{} on dpn:{}",
1121 elanInstanceName, interfaceInfo.getPortName(), macAddress, dstDpId);
1123 return isFlowsRemovedInSrcDpn;
1126 public void deleteSmacFlowOnly(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1127 TypedReadWriteTransaction<Configuration> flowTx) throws ExecutionException,
1128 InterruptedException {
1129 Uint64 srcdpId = interfaceInfo.getDpId();
1130 Uint32 elanTag = elanInfo.getElanTag();
1131 LOG.debug("Deleting SMAC flow with id {}", getKnownDynamicmacFlowRef(elanTag, macAddress));
1132 mdsalManager.removeFlow(flowTx, srcdpId,
1133 MDSALUtil.buildFlow(NwConstants.ELAN_SMAC_TABLE, getKnownDynamicmacFlowRef(elanTag, macAddress)));
1136 private void deleteSmacAndDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1137 boolean deleteSmac, TypedReadWriteTransaction<Configuration> flowTx)
1138 throws ExecutionException, InterruptedException {
1139 String elanInstanceName = elanInfo.getElanInstanceName();
1140 Uint64 srcdpId = interfaceInfo.getDpId();
1141 Uint32 elanTag = elanInfo.getElanTag();
1143 LOG.debug("Deleting SMAC flow with id {}", getKnownDynamicmacFlowRef(elanTag, macAddress));
1145 .removeFlow(flowTx, srcdpId,
1146 MDSALUtil.buildFlow(NwConstants.ELAN_SMAC_TABLE,
1147 getKnownDynamicmacFlowRef(elanTag, macAddress)));
1149 mdsalManager.removeFlow(flowTx, srcdpId,
1150 MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE,
1151 getKnownDynamicmacFlowRef(elanTag, macAddress)));
1152 LOG.debug("All the required flows deleted for elan:{}, logical Interface port:{} and MAC address:{} on dpn:{}",
1153 elanInstanceName, interfaceInfo.getPortName(), macAddress, srcdpId);
1157 * Updates the Elan information in the Operational DS. It also updates the
1158 * ElanInstance in the Config DS by setting the adquired elanTag.
1162 * @param elanInstanceAdded
1163 * the elan instance added
1164 * @param elanInterfaces
1165 * the elan interfaces
1169 * @return the updated ELAN instance.
1171 public static ElanInstance updateOperationalDataStore(IdManagerService idManager,
1172 ElanInstance elanInstanceAdded, List<String> elanInterfaces, TypedWriteTransaction<Configuration> confTx,
1173 TypedWriteTransaction<Operational> operTx) {
1174 String elanInstanceName = elanInstanceAdded.getElanInstanceName();
1175 Uint32 elanTag = elanInstanceAdded.getElanTag();
1176 if (elanTag == null || elanTag.longValue() == 0L) {
1177 elanTag = retrieveNewElanTag(idManager, elanInstanceName);
1179 if (elanTag.longValue() == 0L) {
1180 LOG.error("ELAN tag creation failed for elan instance {}. Not updating the ELAN DS. "
1181 + "Recreate network for recovery", elanInstanceName);
1184 Elan elanInfo = new ElanBuilder().setName(elanInstanceName).setElanInterfaces(elanInterfaces)
1185 .withKey(new ElanKey(elanInstanceName)).build();
1187 // Add the ElanState in the elan-state operational data-store
1188 operTx.put(getElanInstanceOperationalDataPath(elanInstanceName), elanInfo, CREATE_MISSING_PARENTS);
1190 // Add the ElanMacTable in the elan-mac-table operational data-store
1191 MacTable elanMacTable = new MacTableBuilder().withKey(new MacTableKey(elanInstanceName)).build();
1192 operTx.put(getElanMacTableOperationalDataPath(elanInstanceName), elanMacTable, CREATE_MISSING_PARENTS);
1194 ElanTagNameBuilder elanTagNameBuilder = new ElanTagNameBuilder().setElanTag(elanTag)
1195 .withKey(new ElanTagNameKey(elanTag)).setName(elanInstanceName);
1196 Uint32 etreeLeafTag = Uint32.valueOf(0L);
1197 if (isEtreeInstance(elanInstanceAdded)) {
1198 etreeLeafTag = retrieveNewElanTag(idManager,elanInstanceName + ElanConstants
1200 EtreeLeafTagName etreeLeafTagName = new EtreeLeafTagNameBuilder()
1201 .setEtreeLeafTag(new EtreeLeafTag(etreeLeafTag)).build();
1202 elanTagNameBuilder.addAugmentation(EtreeLeafTagName.class, etreeLeafTagName);
1203 addTheLeafTagAsElanTag(elanInstanceName, etreeLeafTag, operTx);
1205 ElanTagName elanTagName = elanTagNameBuilder.build();
1207 // Add the ElanTag to ElanName in the elan-tag-name Operational
1209 operTx.put(getElanInfoEntriesOperationalDataPath(elanTag), elanTagName);
1211 // Updates the ElanInstance Config DS by setting the just acquired
1213 ElanInstanceBuilder elanInstanceBuilder = new ElanInstanceBuilder(elanInstanceAdded)
1214 .setElanInstanceName(elanInstanceName)
1215 .setDescription(elanInstanceAdded.getDescription())
1216 .setMacTimeout(elanInstanceAdded.getMacTimeout() == null
1217 ? Uint32.valueOf(ElanConstants.DEFAULT_MAC_TIME_OUT) : elanInstanceAdded.getMacTimeout())
1218 .withKey(elanInstanceAdded.key()).setElanTag(elanTag);
1219 if (isEtreeInstance(elanInstanceAdded)) {
1220 EtreeInstance etreeInstance = new EtreeInstanceBuilder().setEtreeLeafTagVal(new EtreeLeafTag(etreeLeafTag))
1222 elanInstanceBuilder.addAugmentation(EtreeInstance.class, etreeInstance);
1224 ElanInstance elanInstanceWithTag = elanInstanceBuilder.build();
1225 LOG.trace("Updated elan Operational DS for elan: {} with elanTag: {} and interfaces: {}", elanInstanceName,
1226 elanTag, elanInterfaces);
1227 confTx.merge(ElanHelper.getElanInstanceConfigurationDataPath(elanInstanceName), elanInstanceWithTag,
1228 CREATE_MISSING_PARENTS);
1229 return elanInstanceWithTag;
1232 private static void addTheLeafTagAsElanTag(String elanInstanceName,Uint32 etreeLeafTag,
1233 TypedWriteTransaction<Operational> tx) {
1234 ElanTagName etreeTagAsElanTag = new ElanTagNameBuilder().setElanTag(etreeLeafTag)
1235 .withKey(new ElanTagNameKey(etreeLeafTag)).setName(elanInstanceName).build();
1236 tx.put(getElanInfoEntriesOperationalDataPath(etreeLeafTag), etreeTagAsElanTag);
1239 private static boolean isEtreeInstance(ElanInstance elanInstanceAdded) {
1240 return elanInstanceAdded.augmentation(EtreeInstance.class) != null;
1243 public boolean isDpnPresent(Uint64 dpnId) {
1244 String dpn = String.format("%s:%s", "openflow", dpnId);
1245 NodeId nodeId = new NodeId(dpn);
1247 InstanceIdentifier<Node> node = InstanceIdentifier.builder(Nodes.class).child(Node.class, new NodeKey(nodeId))
1249 return read(broker, LogicalDatastoreType.CONFIGURATION, node).isPresent();
1252 public static String getElanServiceName(String elanName, String interfaceName) {
1253 return "elan." + elanName + interfaceName;
1256 public static BoundServices getBoundServices(String serviceName, short servicePriority, int flowPriority,
1257 Uint64 cookie, List<Instruction> instructions) {
1258 StypeOpenflowBuilder augBuilder = new StypeOpenflowBuilder().setFlowCookie(cookie).setFlowPriority(flowPriority)
1259 .setInstruction(instructions);
1260 return new BoundServicesBuilder().withKey(new BoundServicesKey(servicePriority)).setServiceName(serviceName)
1261 .setServicePriority(servicePriority).setServiceType(ServiceTypeFlowBased.class)
1262 .addAugmentation(StypeOpenflow.class, augBuilder.build()).build();
1265 public static InstanceIdentifier<BoundServices> buildServiceId(String interfaceName, short serviceIndex) {
1266 return InstanceIdentifier.builder(ServiceBindings.class)
1267 .child(ServicesInfo.class, new ServicesInfoKey(interfaceName, ServiceModeIngress.class))
1268 .child(BoundServices.class, new BoundServicesKey(serviceIndex)).build();
1271 public static List<MatchInfo> getTunnelMatchesForServiceId(Uint32 elanTag) {
1272 List<MatchInfo> mkMatches = new ArrayList<>();
1274 // Adding 270000 to avoid collision between LPort and elan tag for broadcast
1275 mkMatches.add(new MatchTunnelId(Uint64.valueOf(elanTag.longValue() + ElanConstants.ELAN_TAG_ADDEND)));
1280 public void removeTerminatingServiceAction(Uint64 destDpId, int serviceId) {
1281 RemoveTerminatingServiceActionsInput input = new RemoveTerminatingServiceActionsInputBuilder()
1282 .setDpnId(destDpId).setServiceId(serviceId).build();
1283 Future<RpcResult<RemoveTerminatingServiceActionsOutput>> futureObject =
1284 itmRpcService.removeTerminatingServiceActions(input);
1286 RpcResult<RemoveTerminatingServiceActionsOutput> result = futureObject.get();
1287 if (result.isSuccessful()) {
1288 LOG.debug("Successfully completed removeTerminatingServiceActions for ELAN with serviceId {} on "
1289 + "dpn {}", serviceId, destDpId);
1291 LOG.debug("Failure in removeTerminatingServiceAction RPC call for ELAN with serviceId {} on "
1292 + "dpn {}", serviceId, destDpId);
1294 } catch (InterruptedException | ExecutionException e) {
1295 LOG.error("Error in RPC call removeTerminatingServiceActions for ELAN with serviceId {} on "
1296 + "dpn {}", serviceId, destDpId, e);
1301 * Gets the external tunnel.
1303 * @param sourceDevice
1305 * @param destinationDevice
1306 * the destination device
1307 * @param datastoreType
1308 * the datastore type
1309 * @return the external tunnel
1312 public ExternalTunnel getExternalTunnel(String sourceDevice, String destinationDevice,
1313 LogicalDatastoreType datastoreType) {
1314 Class<? extends TunnelTypeBase> tunType = TunnelTypeVxlan.class;
1315 InstanceIdentifier<ExternalTunnel> iid = InstanceIdentifier.builder(ExternalTunnelList.class)
1316 .child(ExternalTunnel.class, new ExternalTunnelKey(destinationDevice, sourceDevice, tunType)).build();
1317 return read(broker, datastoreType, iid).orElse(null);
1321 * Gets the external tunnel.
1323 * @param interfaceName
1324 * the interface name
1325 * @param datastoreType
1326 * the datastore type
1327 * @return the external tunnel
1330 public ExternalTunnel getExternalTunnel(String interfaceName, LogicalDatastoreType datastoreType) {
1331 ExternalTunnel externalTunnel = null;
1332 List<ExternalTunnel> externalTunnels = getAllExternalTunnels(datastoreType);
1333 for (ExternalTunnel tunnel : externalTunnels) {
1334 if (StringUtils.equalsIgnoreCase(interfaceName, tunnel.getTunnelInterfaceName())) {
1335 externalTunnel = tunnel;
1339 return externalTunnel;
1343 * Gets the all external tunnels.
1345 * @param datastoreType
1346 * the data store type
1347 * @return the all external tunnels
1349 public List<ExternalTunnel> getAllExternalTunnels(LogicalDatastoreType datastoreType) {
1350 InstanceIdentifier<ExternalTunnelList> iid = InstanceIdentifier.builder(ExternalTunnelList.class).build();
1351 return read(broker, datastoreType, iid).map(ExternalTunnelList::getExternalTunnel).orElse(
1355 public static List<MatchInfo> buildMatchesForElanTagShFlagAndDstMac(long elanTag, boolean shFlag, String macAddr) {
1356 List<MatchInfo> mkMatches = new ArrayList<>();
1358 new MatchMetadata(getElanMetadataLabel(elanTag, shFlag), MetaDataUtil.METADATA_MASK_SERVICE_SH_FLAG));
1359 mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddr)));
1364 * Checks if is interface operational.
1366 * @param interfaceName
1367 * the interface name
1370 * @return true, if is interface operational
1372 public static boolean isInterfaceOperational(String interfaceName, DataBroker dataBroker) {
1373 if (StringUtils.isBlank(interfaceName)) {
1376 Interface ifState = getInterfaceStateFromOperDS(interfaceName, dataBroker);
1377 if (ifState == null) {
1380 return ifState.getOperStatus() == OperStatus.Up && ifState.getAdminStatus() == AdminStatus.Up;
1384 * Gets the interface state from operational ds.
1386 * @param interfaceName
1387 * the interface name
1390 * @return the interface state from oper ds
1392 public static org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state
1393 .@Nullable Interface getInterfaceStateFromOperDS(String interfaceName, DataBroker dataBroker) {
1395 return SingleTransactionDataBroker.syncReadOptional(dataBroker, LogicalDatastoreType.OPERATIONAL,
1396 createInterfaceStateInstanceIdentifier(interfaceName)).orElse(null);
1397 } catch (ExecutionException | InterruptedException e) {
1398 LOG.error("getInterfaceStateFromOperDS: Exception while reading interface DS for the interface {}",
1405 * Creates the interface state instance identifier.
1407 * @param interfaceName
1408 * the interface name
1409 * @return the instance identifier
1411 public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1412 .ietf.interfaces.rev140508.interfaces.state.Interface> createInterfaceStateInstanceIdentifier(
1413 String interfaceName) {
1414 InstanceIdentifierBuilder<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1415 .ietf.interfaces.rev140508.interfaces.state.Interface> idBuilder = InstanceIdentifier
1416 .builder(InterfacesState.class)
1417 .child(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1418 .ietf.interfaces.rev140508.interfaces.state.Interface.class,
1419 new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1420 .ietf.interfaces.rev140508.interfaces.state.InterfaceKey(
1422 return idBuilder.build();
1426 public static ListenableFuture<Void> waitForTransactionToComplete(ListenableFuture<Void> future) {
1429 } catch (InterruptedException | ExecutionException e) {
1430 // NETVIRT-1215: Do not log.error() here, only debug(); but callers *MUST* @CheckReturnValue
1431 LOG.debug("Error writing to datastore", e);
1436 public static boolean isVxlan(@Nullable ElanInstance elanInstance) {
1437 return elanInstance != null && elanInstance.getSegmentType() != null
1438 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1439 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId().toJava() != 0;
1442 private static boolean isVxlanSegment(@Nullable ElanInstance elanInstance) {
1443 if (elanInstance != null) {
1444 List<ElanSegments> elanSegments = elanInstance.getElanSegments();
1445 if (elanSegments != null) {
1446 for (ElanSegments segment : elanSegments) {
1447 if (segment != null && segment.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1448 && segment.getSegmentationId() != null
1449 && segment.getSegmentationId().longValue() != 0) {
1458 public static boolean isVxlanNetworkOrVxlanSegment(@Nullable ElanInstance elanInstance) {
1459 return isVxlan(elanInstance) || isVxlanSegment(elanInstance);
1462 public static Uint32 getVxlanSegmentationId(ElanInstance elanInstance) {
1463 Uint32 segmentationId = Uint32.ZERO;
1464 if (elanInstance == null) {
1465 return segmentationId;
1468 if (elanInstance.getSegmentType() != null
1469 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1470 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId().longValue() != 0) {
1471 segmentationId = elanInstance.getSegmentationId();
1473 for (ElanSegments segment: elanInstance.getElanSegments()) {
1474 if (segment != null && segment.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1475 && segment.getSegmentationId() != null
1476 && segment.getSegmentationId().longValue() != 0) {
1477 segmentationId = segment.getSegmentationId();
1481 return segmentationId;
1484 public static boolean isVlan(ElanInstance elanInstance) {
1485 return elanInstance != null && elanInstance.getSegmentType() != null
1486 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVlan.class)
1487 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId().toJava() != 0;
1490 public static boolean isFlat(ElanInstance elanInstance) {
1491 return elanInstance != null && elanInstance.getSegmentType() != null
1492 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeFlat.class);
1495 public void addDmacRedirectToDispatcherFlows(Uint32 elanTag, String displayName,
1496 String macAddress, List<Uint64> dpnIds) {
1497 for (Uint64 dpId : dpnIds) {
1498 LoggingFutures.addErrorLogging(txRunner.callWithNewWriteOnlyTransactionAndSubmit(CONFIGURATION,
1499 tx -> mdsalManager.addFlow(tx, buildDmacRedirectToDispatcherFlow(dpId, macAddress, displayName,
1501 "Error adding DMAC redirect to dispatcher flows");
1505 public void removeDmacRedirectToDispatcherFlows(Uint32 elanTag, String macAddress, List<Uint64> dpnIds) {
1506 LoggingFutures.addErrorLogging(
1507 txRunner.callWithNewReadWriteTransactionAndSubmit(Datastore.CONFIGURATION, tx -> {
1508 for (Uint64 dpId : dpnIds) {
1509 String flowId = getKnownDynamicmacFlowRef(elanTag, macAddress);
1510 mdsalManager.removeFlow(tx, dpId, MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, flowId));
1512 }), LOG, "Error removing DMAC redirect to dispatcher flows");
1515 public static FlowEntity buildDmacRedirectToDispatcherFlow(Uint64 dpId, String dstMacAddress,
1516 String displayName, Uint32 elanTag) {
1517 List<MatchInfo> matches = new ArrayList<>();
1518 matches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag.longValue()),
1519 MetaDataUtil.METADATA_MASK_SERVICE));
1520 matches.add(new MatchEthernetDestination(new MacAddress(dstMacAddress)));
1521 List<InstructionInfo> instructions = new ArrayList<>();
1522 List<ActionInfo> actions = new ArrayList<>();
1523 actions.add(new ActionNxResubmit(NwConstants.LPORT_DISPATCHER_TABLE));
1525 instructions.add(new InstructionApplyActions(actions));
1526 String flowId = getKnownDynamicmacFlowRef(elanTag, dstMacAddress);
1527 return MDSALUtil.buildFlowEntity(dpId, NwConstants.ELAN_DMAC_TABLE, flowId, 20, displayName, 0, 0,
1528 Uint64.valueOf(ElanConstants.COOKIE_ELAN_KNOWN_DMAC.longValue() + elanTag.longValue()),
1529 matches, instructions);
1533 public String getExternalElanInterface(String elanInstanceName, Uint64 dpnId) {
1534 DpnInterfaces dpnInterfaces = getElanInterfaceInfoByElanDpn(elanInstanceName, dpnId);
1535 if (dpnInterfaces == null || dpnInterfaces.getInterfaces() == null) {
1536 LOG.trace("Elan {} does not have interfaces in DPN {}", elanInstanceName, dpnId);
1540 for (String dpnInterface : dpnInterfaces.getInterfaces()) {
1541 if (interfaceManager.isExternalInterface(dpnInterface)) {
1542 return dpnInterface;
1546 LOG.trace("Elan {} does not have any external interace attached to DPN {}", elanInstanceName, dpnId);
1550 public static Acquired lockElanMacDPN(long elanTag, String macAddress, Uint64 dpnId) {
1551 return ELAN_LOCKS.acquire(new ElanLockName(elanTag, macAddress, dpnId));
1554 public static List<ListenableFuture<Void>>
1555 returnFailedListenableFutureIfTransactionCommitFailedExceptionCauseOrElseThrow(RuntimeException exception) {
1557 Throwable cause = exception.getCause();
1558 if (cause != null && cause instanceof TransactionCommitFailedException) {
1559 return Collections.singletonList(Futures.immediateFailedFuture(cause));
1565 public static List<PhysAddress> getPhysAddress(List<String> macAddress) {
1566 Preconditions.checkNotNull(macAddress, "macAddress cannot be null");
1567 List<PhysAddress> physAddresses = new ArrayList<>();
1568 for (String mac : macAddress) {
1569 physAddresses.add(new PhysAddress(mac));
1571 return physAddresses;
1574 public static List<StaticMacEntries> getStaticMacEntries(List<String> staticMacAddresses) {
1575 if (isEmpty(staticMacAddresses)) {
1576 return Collections.EMPTY_LIST;
1578 StaticMacEntriesBuilder staticMacEntriesBuilder = new StaticMacEntriesBuilder();
1579 List<StaticMacEntries> staticMacEntries = new ArrayList<>();
1580 List<PhysAddress> physAddressList = getPhysAddress(staticMacAddresses);
1581 for (PhysAddress physAddress : physAddressList) {
1582 staticMacEntries.add(staticMacEntriesBuilder.setMacAddress(physAddress).build());
1584 return staticMacEntries;
1587 public static InstanceIdentifier<StaticMacEntries> getStaticMacEntriesCfgDataPathIdentifier(String interfaceName,
1588 String macAddress) {
1589 return InstanceIdentifier.builder(ElanInterfaces.class)
1590 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).child(StaticMacEntries.class,
1591 new StaticMacEntriesKey(new PhysAddress(macAddress))).build();
1594 public static <T> List<T> diffOf(List<T> orig, List<T> updated) {
1595 if (isEmpty(orig)) {
1596 return Collections.EMPTY_LIST;
1598 List<T> diff = Lists.newArrayList(orig);
1599 if (isNotEmpty(updated)) {
1600 diff.removeAll(updated);
1605 public static boolean isEmpty(Collection collection) {
1606 return collection == null || collection.isEmpty();
1609 public static boolean isNotEmpty(Collection collection) {
1610 return !isEmpty(collection);
1613 public Optional<IpAddress> getSourceIpAddress(Ethernet ethernet) {
1614 Optional<IpAddress> srcIpAddress = Optional.empty();
1615 if (ethernet.getPayload() == null) {
1616 return srcIpAddress;
1618 byte[] ipAddrBytes = null;
1619 if (ethernet.getPayload() instanceof IPv4) {
1620 IPv4 ipv4 = (IPv4) ethernet.getPayload();
1621 ipAddrBytes = Ints.toByteArray(ipv4.getSourceAddress());
1622 } else if (ethernet.getPayload() instanceof ARP) {
1623 ipAddrBytes = ((ARP) ethernet.getPayload()).getSenderProtocolAddress();
1625 if (ipAddrBytes != null) {
1626 String ipAddr = NWUtil.toStringIpAddress(ipAddrBytes);
1627 return Optional.of(IpAddressBuilder.getDefaultInstance(ipAddr));
1629 return srcIpAddress;
1632 public List<MacEntry> getElanMacEntries(String elanName) {
1633 MacTable macTable = getElanMacTable(elanName);
1634 if (macTable == null) {
1637 return macTable.getMacEntry();
1640 public boolean isTunnelInLogicalGroup(String interfaceName) {
1641 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1642 .ietf.interfaces.rev140508.interfaces.Interface configIface =
1643 interfaceManager.getInterfaceInfoFromConfigDataStore(interfaceName);
1644 if (configIface == null) {
1645 configIface = iitmProvider.getInterface(interfaceName);
1647 if (configIface == null) {
1650 IfTunnel ifTunnel = configIface.augmentation(IfTunnel.class);
1651 if (ifTunnel != null && ifTunnel.getTunnelInterfaceType().isAssignableFrom(TunnelTypeVxlan.class)) {
1652 ParentRefs refs = configIface.augmentation(ParentRefs.class);
1653 return refs != null && !Strings.isNullOrEmpty(refs.getParentInterface());
1658 public static InstanceIdentifier<Flow> getFlowIid(Flow flow, Uint64 dpnId) {
1659 FlowKey flowKey = new FlowKey(new FlowId(flow.getId()));
1660 org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId nodeId =
1661 new org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId("openflow:" + dpnId);
1662 org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node nodeDpn =
1663 new NodeBuilder().setId(nodeId).withKey(new NodeKey(nodeId)).build();
1664 return InstanceIdentifier.builder(Nodes.class)
1665 .child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node.class,
1666 nodeDpn.key()).augmentation(FlowCapableNode.class)
1667 .child(Table.class, new TableKey(flow.getTableId())).child(Flow.class, flowKey).build();
1670 public static String getElanInterfaceJobKey(String interfaceName) {
1671 return "elaninterface-" + interfaceName;
1674 public void removeArpResponderFlow(Uint64 dpnId, String ingressInterfaceName, String ipAddress,
1676 LOG.info("Removing the ARP responder flow on DPN {} of Interface {} with IP {}", dpnId, ingressInterfaceName,
1678 LoggingFutures.addErrorLogging(txRunner.callWithNewReadWriteTransactionAndSubmit(Datastore.CONFIGURATION,
1679 tx -> mdsalManager.removeFlow(tx, dpnId, ArpResponderUtil.getFlowId(lportTag, ipAddress),
1680 NwConstants.ARP_RESPONDER_TABLE)), LOG, "Error removing ARP responder flow");
1684 public static String getRouterPordIdFromElanInstance(DataBroker dataBroker, String elanInstanceName) {
1685 Optional<Subnetmaps> subnetMapsData =
1686 read(dataBroker, LogicalDatastoreType.CONFIGURATION, buildSubnetMapsWildCardPath());
1687 if (subnetMapsData.isPresent()) {
1688 List<Subnetmap> subnetMapList = subnetMapsData.get().getSubnetmap();
1689 if (subnetMapList != null && !subnetMapList.isEmpty()) {
1690 for (Subnetmap subnet : subnetMapList) {
1691 if (subnet.getNetworkId().getValue().equals(elanInstanceName)) {
1692 if (subnet.getRouterInterfacePortId() != null) {
1693 return subnet.getRouterInterfacePortId().getValue();
1702 protected Node buildDpnNode(Uint64 dpnId) {
1703 org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId nodeId =
1704 new org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819
1705 .NodeId("openflow:" + dpnId);
1706 Node nodeDpn = new NodeBuilder().setId(nodeId).withKey(new NodeKey(nodeId)).build();
1710 public void syncUpdateGroup(Uint64 dpnId, Group newGroup, long delayTime,
1711 TypedWriteTransaction<Datastore.Configuration> confTx) {
1712 Node nodeDpn = buildDpnNode(dpnId);
1713 long groupIdInfo = newGroup.getGroupId().getValue().toJava();
1714 GroupKey groupKey = new GroupKey(new GroupId(groupIdInfo));
1715 InstanceIdentifier<Group> groupInstanceId = InstanceIdentifier.builder(Nodes.class)
1716 .child(Node.class, nodeDpn.key()).augmentation(FlowCapableNode.class)
1717 .child(Group.class, groupKey).build();
1718 LOG.trace("Performing merge operation for remote BC group for node {} with group {}", nodeDpn, newGroup);
1719 Optional<Group> existingGroupOpt = ElanUtils.read(broker, LogicalDatastoreType.CONFIGURATION, groupInstanceId);
1720 if (!existingGroupOpt.isPresent()) {
1721 LOG.debug("Group {} doesn't exist. Performing syncInstall", groupIdInfo);
1722 mdsalManager.addGroup(confTx, dpnId, newGroup);
1725 Buckets existingGroup = existingGroupOpt.get().getBuckets();
1726 if (existingGroup == null) {
1727 LOG.debug("Bucket doesn't exist for group {}. Performing syncInstall", groupIdInfo);
1728 mdsalManager.addGroup(confTx, dpnId, newGroup);
1731 if (newGroup.getBuckets() == null) {
1732 LOG.debug("Buckets are not sent for group {}. Skipping merge operation", groupIdInfo);
1735 List<Bucket> newBuckets = newGroup.getBuckets().getBucket();
1736 List<Bucket> existingBuckets = existingGroup.getBucket();
1737 Set<Bucket> toMergeBucketsWithoutId = new LinkedHashSet<>();
1739 existingBuckets.stream()
1740 .map(TO_BUCKET_WITHOUT_ID)
1741 .forEach(bucketWithoutId -> toMergeBucketsWithoutId.add(bucketWithoutId));
1744 .map(TO_BUCKET_WITHOUT_ID)
1745 .forEach(bucketWithoutId -> toMergeBucketsWithoutId.add(bucketWithoutId));
1747 if (toMergeBucketsWithoutId.size() == existingBuckets.size()) {
1748 //no new buckets got added
1749 //size matched and no extra buckets in existing buckets , rewrite the group
1750 LOG.debug("Buckets did not change group {}. Skipping merge operation", groupIdInfo);
1753 LOG.debug("Old group buckets size {} New group buckets size {} Dpn id {} Group id {} ",
1754 existingBuckets.size(), toMergeBucketsWithoutId.size(), dpnId, groupIdInfo);
1755 AtomicLong bucketIdValue = new AtomicLong(-1);
1756 //Change the bucket id of existing buckets
1757 List<Bucket> bucketsToBeAdded = toMergeBucketsWithoutId.stream()
1758 .map(bucketWithoutId -> TO_BUCKET_WITH_ID.apply(bucketWithoutId, bucketIdValue))
1759 .collect(Collectors.toList());
1761 Group group = MDSALUtil.buildGroup(newGroup.getGroupId().getValue().toJava(), newGroup.getGroupName(),
1762 GroupTypes.GroupAll, MDSALUtil.buildBucketLists(bucketsToBeAdded));
1763 mdsalManager.addGroup(confTx, dpnId, group);
1764 LOG.trace("Installed remote BC group for node {} with group {}", nodeDpn, group);
1767 static InstanceIdentifier<Subnetmaps> buildSubnetMapsWildCardPath() {
1768 return InstanceIdentifier.create(Subnetmaps.class);
1771 public static InstanceIdentifier<Group> getGroupInstanceid(Uint64 dpnId, long groupId) {
1772 return InstanceIdentifier.builder(Nodes.class).child(Node.class, new NodeKey(new NodeId("openflow:" + dpnId)))
1773 .augmentation(FlowCapableNode.class).child(Group.class, new GroupKey(new GroupId(groupId))).build();
1776 public static String getBcGroupUpdateKey(String elanName) {
1777 return "bc.group.update." + elanName;