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 edu.umd.cs.findbugs.annotations.CheckReturnValue;
25 import java.math.BigInteger;
26 import java.util.ArrayList;
27 import java.util.Collection;
28 import java.util.Collections;
29 import java.util.LinkedHashSet;
30 import java.util.List;
31 import java.util.Locale;
32 import java.util.Objects;
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.controller.md.sal.binding.api.DataBroker;
46 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
47 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
48 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
49 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
50 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
51 import org.opendaylight.genius.infra.Datastore;
52 import org.opendaylight.genius.infra.Datastore.Configuration;
53 import org.opendaylight.genius.infra.Datastore.Operational;
54 import org.opendaylight.genius.infra.ManagedNewTransactionRunner;
55 import org.opendaylight.genius.infra.ManagedNewTransactionRunnerImpl;
56 import org.opendaylight.genius.infra.TypedReadTransaction;
57 import org.opendaylight.genius.infra.TypedReadWriteTransaction;
58 import org.opendaylight.genius.infra.TypedWriteTransaction;
59 import org.opendaylight.genius.interfacemanager.globals.InterfaceInfo;
60 import org.opendaylight.genius.interfacemanager.interfaces.IInterfaceManager;
61 import org.opendaylight.genius.itm.api.IITMProvider;
62 import org.opendaylight.genius.itm.globals.ITMConstants;
63 import org.opendaylight.genius.mdsalutil.ActionInfo;
64 import org.opendaylight.genius.mdsalutil.FlowEntity;
65 import org.opendaylight.genius.mdsalutil.FlowEntityBuilder;
66 import org.opendaylight.genius.mdsalutil.InstructionInfo;
67 import org.opendaylight.genius.mdsalutil.MDSALUtil;
68 import org.opendaylight.genius.mdsalutil.MatchInfo;
69 import org.opendaylight.genius.mdsalutil.MetaDataUtil;
70 import org.opendaylight.genius.mdsalutil.NWUtil;
71 import org.opendaylight.genius.mdsalutil.NwConstants;
72 import org.opendaylight.genius.mdsalutil.actions.ActionNxResubmit;
73 import org.opendaylight.genius.mdsalutil.instructions.InstructionApplyActions;
74 import org.opendaylight.genius.mdsalutil.instructions.InstructionGotoTable;
75 import org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager;
76 import org.opendaylight.genius.mdsalutil.matches.MatchEthernetDestination;
77 import org.opendaylight.genius.mdsalutil.matches.MatchEthernetSource;
78 import org.opendaylight.genius.mdsalutil.matches.MatchMetadata;
79 import org.opendaylight.genius.mdsalutil.matches.MatchTunnelId;
80 import org.opendaylight.genius.mdsalutil.packet.ARP;
81 import org.opendaylight.genius.mdsalutil.packet.Ethernet;
82 import org.opendaylight.genius.mdsalutil.packet.IPv4;
83 import org.opendaylight.infrautils.utils.concurrent.LoggingFutures;
84 import org.opendaylight.infrautils.utils.concurrent.NamedLocks;
85 import org.opendaylight.infrautils.utils.concurrent.NamedSimpleReentrantLock.Acquired;
86 import org.opendaylight.netvirt.elan.arp.responder.ArpResponderUtil;
87 import org.opendaylight.netvirt.elan.cache.ElanInterfaceCache;
88 import org.opendaylight.netvirt.elan.internal.ElanGroupCache;
89 import org.opendaylight.netvirt.elanmanager.api.ElanHelper;
90 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
91 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddressBuilder;
92 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfacesState;
93 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface;
94 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.AdminStatus;
95 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.OperStatus;
96 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
97 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.PhysAddress;
98 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
99 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
100 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
101 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
102 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
103 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
104 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
105 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
106 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInput;
107 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInputBuilder;
108 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdOutput;
109 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdManagerService;
110 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInput;
111 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInputBuilder;
112 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406.IfIndexesInterfaceMap;
113 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._if.indexes._interface.map.IfIndexInterface;
114 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._if.indexes._interface.map.IfIndexInterfaceKey;
115 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfTunnel;
116 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.ParentRefs;
117 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeBase;
118 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeVxlan;
119 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceInput;
120 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceInputBuilder;
121 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceOutput;
122 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.OdlInterfaceRpcService;
123 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceBindings;
124 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceModeIngress;
125 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceTypeFlowBased;
126 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflow;
127 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflowBuilder;
128 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.ServicesInfo;
129 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.ServicesInfoKey;
130 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServices;
131 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesBuilder;
132 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesKey;
133 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.ExternalTunnelList;
134 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnel;
135 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnelKey;
136 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.ItmRpcService;
137 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsInput;
138 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsInputBuilder;
139 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsOutput;
140 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.BucketId;
141 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupId;
142 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupTypes;
143 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.Buckets;
144 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.buckets.Bucket;
145 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.buckets.BucketBuilder;
146 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group;
147 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupKey;
148 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
149 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
150 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
151 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
152 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
153 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.config.rev150710.ElanConfig;
154 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInstance;
155 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInstanceBuilder;
156 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInterface;
157 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInterface.EtreeInterfaceType;
158 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTag;
159 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTagName;
160 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTagNameBuilder;
161 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanDpnInterfaces;
162 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanForwardingTables;
163 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaceForwardingEntries;
164 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaces;
165 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanState;
166 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanTagNameMap;
167 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeFlat;
168 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeVlan;
169 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeVxlan;
170 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan._interface.forwarding.entries.ElanInterfaceMac;
171 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan._interface.forwarding.entries.ElanInterfaceMacKey;
172 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesList;
173 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesListKey;
174 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfaces;
175 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfacesKey;
176 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTable;
177 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTableBuilder;
178 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTableKey;
179 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstance;
180 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstanceBuilder;
181 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.elan.instance.ElanSegments;
182 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterface;
183 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterfaceKey;
184 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntries;
185 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntriesBuilder;
186 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntriesKey;
187 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.Elan;
188 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.ElanBuilder;
189 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.ElanKey;
190 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagName;
191 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagNameBuilder;
192 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagNameKey;
193 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntry;
194 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntryKey;
195 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.Subnetmaps;
196 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.subnetmaps.Subnetmap;
197 import org.opendaylight.yangtools.yang.binding.DataObject;
198 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
199 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.InstanceIdentifierBuilder;
200 import org.opendaylight.yangtools.yang.common.RpcResult;
201 import org.opendaylight.yangtools.yang.common.Uint32;
202 import org.opendaylight.yangtools.yang.common.Uint64;
203 import org.slf4j.Logger;
204 import org.slf4j.LoggerFactory;
207 public class ElanUtils {
208 private static final class ElanLockName {
209 private final String macAddress;
210 private final Uint64 dpnId;
211 private final long elanTag;
213 ElanLockName(long elanTag, String macAddress, Uint64 dpnId) {
214 this.elanTag = elanTag;
215 this.macAddress = macAddress;
220 public int hashCode() {
221 return 31 * Long.hashCode(elanTag) + Objects.hash(macAddress, dpnId);
225 public boolean equals(Object obj) {
229 if (!(obj instanceof ElanLockName)) {
232 final ElanLockName other = (ElanLockName) obj;
233 return elanTag == other.elanTag && Objects.equals(macAddress, other.macAddress)
234 && Objects.equals(dpnId, other.dpnId);
238 private static final Logger LOG = LoggerFactory.getLogger(ElanUtils.class);
239 private static final NamedLocks<ElanLockName> ELAN_LOCKS = new NamedLocks<>();
241 private final DataBroker broker;
242 private final ManagedNewTransactionRunner txRunner;
243 private final IMdsalApiManager mdsalManager;
244 private final OdlInterfaceRpcService interfaceManagerRpcService;
245 private final ItmRpcService itmRpcService;
246 private final IInterfaceManager interfaceManager;
247 private final ElanConfig elanConfig;
248 private final ElanItmUtils elanItmUtils;
249 private final ElanEtreeUtils elanEtreeUtils;
250 private final ElanInterfaceCache elanInterfaceCache;
251 private final IITMProvider iitmProvider;
252 private final ElanGroupCache elanGroupCache;
254 private static final Function<Bucket, Bucket> TO_BUCKET_WITHOUT_ID = (bucket) -> new BucketBuilder(bucket)
255 .setBucketId(new BucketId(0L))
258 private static final BiFunction<Bucket, AtomicLong, Bucket> TO_BUCKET_WITH_ID = (bucket, id)
259 -> new BucketBuilder(bucket)
260 .setBucketId(new BucketId(id.incrementAndGet()))
263 public static final FutureCallback<Void> DEFAULT_CALLBACK = new FutureCallback<Void>() {
265 public void onSuccess(Void result) {
266 LOG.debug("Success in Datastore operation");
270 public void onFailure(Throwable error) {
271 LOG.error("Error in Datastore operation", error);
276 public ElanUtils(DataBroker dataBroker, IMdsalApiManager mdsalManager,
277 OdlInterfaceRpcService interfaceManagerRpcService, ItmRpcService itmRpcService, ElanConfig elanConfig,
278 IInterfaceManager interfaceManager, ElanEtreeUtils elanEtreeUtils, ElanItmUtils elanItmUtils,
279 ElanInterfaceCache elanInterfaceCache, IITMProvider iitmProvider, ElanGroupCache elanGroupCache) {
280 this.broker = dataBroker;
281 this.txRunner = new ManagedNewTransactionRunnerImpl(dataBroker);
282 this.mdsalManager = mdsalManager;
283 this.interfaceManagerRpcService = interfaceManagerRpcService;
284 this.itmRpcService = itmRpcService;
285 this.interfaceManager = interfaceManager;
286 this.elanConfig = elanConfig;
287 this.elanEtreeUtils = elanEtreeUtils;
288 this.elanItmUtils = elanItmUtils;
289 this.elanInterfaceCache = elanInterfaceCache;
290 this.iitmProvider = iitmProvider;
291 this.elanGroupCache = elanGroupCache;
294 public final Boolean isOpenstackVniSemanticsEnforced() {
295 return elanConfig.isOpenstackVniSemanticsEnforced() != null
296 ? elanConfig.isOpenstackVniSemanticsEnforced() : false;
300 * Uses the IdManager to retrieve a brand new ElanTag.
306 * @return the integer
308 public static Uint32 retrieveNewElanTag(IdManagerService idManager, String idKey) {
310 AllocateIdInput getIdInput = new AllocateIdInputBuilder().setPoolName(ElanConstants.ELAN_ID_POOL_NAME)
311 .setIdKey(idKey).build();
314 Future<RpcResult<AllocateIdOutput>> result = idManager.allocateId(getIdInput);
315 RpcResult<AllocateIdOutput> rpcResult = result.get();
316 if (rpcResult.isSuccessful()) {
317 return rpcResult.getResult().getIdValue();
319 LOG.warn("RPC Call to Allocate Id returned with Errors {}", rpcResult.getErrors());
321 } catch (InterruptedException | ExecutionException e) {
322 LOG.warn("Exception when Allocating Id", e);
324 return Uint32.valueOf(0L);
327 public static void releaseId(IdManagerService idManager, String poolName, String idKey) {
328 ReleaseIdInput releaseIdInput = new ReleaseIdInputBuilder().setPoolName(poolName).setIdKey(idKey).build();
329 LoggingFutures.addErrorLogging(idManager.releaseId(releaseIdInput), LOG, "Release Id");
335 * @deprecated Consider using {@link #read2(LogicalDatastoreType, InstanceIdentifier)} with proper exception
337 * @param broker dataBroker
338 * @param datastoreType Logical DataStore type
339 * @param path IID to read
340 * @param <T> T extends DataObject
341 * @return the read value T
344 @SuppressWarnings("checkstyle:IllegalCatch")
345 public static <T extends DataObject> Optional<T> read(@NonNull DataBroker broker,
346 LogicalDatastoreType datastoreType, InstanceIdentifier<T> path) {
347 try (ReadOnlyTransaction tx = broker.newReadOnlyTransaction()) {
348 return tx.read(datastoreType, path).get();
349 } catch (Exception e) {
350 throw new RuntimeException(e);
354 public <T extends DataObject> Optional<T> read2(LogicalDatastoreType datastoreType, InstanceIdentifier<T> path)
355 throws ReadFailedException {
356 try (ReadOnlyTransaction tx = broker.newReadOnlyTransaction()) {
357 CheckedFuture<Optional<T>, ReadFailedException> checkedFuture = tx.read(datastoreType, path);
358 return checkedFuture.checkedGet();
362 @SuppressWarnings("checkstyle:ForbidCertainMethod")
363 public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
364 InstanceIdentifier<T> path) {
365 WriteTransaction tx = broker.newWriteOnlyTransaction();
366 tx.delete(datastoreType, path);
367 Futures.addCallback(tx.submit(), DEFAULT_CALLBACK, MoreExecutors.directExecutor());
370 public static InstanceIdentifier<ElanInterface> getElanInterfaceConfigurationDataPathId(String interfaceName) {
371 return InstanceIdentifier.builder(ElanInterfaces.class)
372 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).build();
375 // elan-state Operational container
377 public static Elan getElanByName(DataBroker broker, String elanInstanceName) {
378 InstanceIdentifier<Elan> elanIdentifier = getElanInstanceOperationalDataPath(elanInstanceName);
379 return MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL, elanIdentifier).orNull();
383 public static Elan getElanByName(TypedReadTransaction<Operational> tx, String elanInstanceName)
384 throws ExecutionException, InterruptedException {
385 return tx.read(getElanInstanceOperationalDataPath(elanInstanceName)).get().orNull();
388 public static InstanceIdentifier<Elan> getElanInstanceOperationalDataPath(String elanInstanceName) {
389 return InstanceIdentifier.builder(ElanState.class).child(Elan.class, new ElanKey(elanInstanceName)).build();
392 // grouping of forwarding-entries
394 public MacEntry getInterfaceMacEntriesOperationalDataPath(String interfaceName, PhysAddress physAddress) {
395 InstanceIdentifier<MacEntry> existingMacEntryId = getInterfaceMacEntriesIdentifierOperationalDataPath(
396 interfaceName, physAddress);
397 return read(broker, LogicalDatastoreType.OPERATIONAL, existingMacEntryId).orNull();
401 public MacEntry getInterfaceMacEntriesOperationalDataPathFromId(TypedReadTransaction<Operational> tx,
402 InstanceIdentifier<MacEntry> identifier) throws ExecutionException, InterruptedException {
403 return tx.read(identifier).get().orNull();
406 public static InstanceIdentifier<MacEntry> getInterfaceMacEntriesIdentifierOperationalDataPath(String interfaceName,
407 PhysAddress physAddress) {
408 return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class)
409 .child(ElanInterfaceMac.class, new ElanInterfaceMacKey(interfaceName))
410 .child(MacEntry.class, new MacEntryKey(physAddress)).build();
414 // elan-forwarding-tables Operational container
415 public Optional<MacEntry> getMacEntryForElanInstance(String elanName, PhysAddress physAddress) {
416 InstanceIdentifier<MacEntry> macId = getMacEntryOperationalDataPath(elanName, physAddress);
417 return read(broker, LogicalDatastoreType.OPERATIONAL, macId);
420 public Optional<MacEntry> getMacEntryForElanInstance(TypedReadTransaction<Operational> tx, String elanName,
421 PhysAddress physAddress) throws ExecutionException, InterruptedException {
422 InstanceIdentifier<MacEntry> macId = getMacEntryOperationalDataPath(elanName, physAddress);
423 return tx.read(macId).get();
427 public MacEntry getMacEntryFromElanMacId(TypedReadTransaction<Operational> tx,
428 InstanceIdentifier<MacEntry> identifier) throws ExecutionException, InterruptedException {
429 return tx.read(identifier).get().orNull();
432 public static InstanceIdentifier<MacEntry> getMacEntryOperationalDataPath(String elanName,
433 PhysAddress physAddress) {
434 return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class, new MacTableKey(elanName))
435 .child(MacEntry.class, new MacEntryKey(physAddress)).build();
438 public static InstanceIdentifier<MacTable> getElanMacTableOperationalDataPath(String elanName) {
439 return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class, new MacTableKey(elanName))
443 // elan-interface-forwarding-entries Operational container
444 public ElanInterfaceMac getElanInterfaceMacByInterfaceName(String interfaceName) {
445 return getElanInterfaceMacByInterfaceName(broker, interfaceName);
449 public static ElanInterfaceMac getElanInterfaceMacByInterfaceName(DataBroker dataBroker, String interfaceName) {
450 InstanceIdentifier<ElanInterfaceMac> elanInterfaceId = getElanInterfaceMacEntriesOperationalDataPath(
452 return read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanInterfaceId).orNull();
455 public static InstanceIdentifier<ElanInterfaceMac> getElanInterfaceMacEntriesOperationalDataPath(
456 String interfaceName) {
457 return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class)
458 .child(ElanInterfaceMac.class, new ElanInterfaceMacKey(interfaceName)).build();
462 * Returns the list of Interfaces that belong to an Elan on an specific DPN.
463 * Data retrieved from Elan's operational DS: elan-dpn-interfaces container.
465 * @param elanInstanceName
466 * name of the Elan to which the interfaces must belong to
468 * Id of the DPN where the interfaces are located
469 * @return the elan interface Info
472 public DpnInterfaces getElanInterfaceInfoByElanDpn(String elanInstanceName, Uint64 dpId) {
473 InstanceIdentifier<DpnInterfaces> elanDpnInterfacesId = getElanDpnInterfaceOperationalDataPath(elanInstanceName,
475 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfacesId).orNull();
479 * Returns the InstanceIdentifier that points to the Interfaces of an Elan
480 * in a given DPN in the Operational DS. Data retrieved from Elans's
481 * operational DS: dpn-interfaces list
483 * @param elanInstanceName
484 * name of the Elan to which the interfaces must belong to
486 * Id of the DPN where the interfaces are located
487 * @return the elan dpn interface
489 public static InstanceIdentifier<DpnInterfaces> getElanDpnInterfaceOperationalDataPath(String elanInstanceName,
491 return InstanceIdentifier.builder(ElanDpnInterfaces.class)
492 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName))
493 .child(DpnInterfaces.class, new DpnInterfacesKey(dpId)).build();
496 // elan-tag-name-map Operational Container
498 public ElanTagName getElanInfoByElanTag(Uint32 elanTag) {
499 InstanceIdentifier<ElanTagName> elanId = getElanInfoEntriesOperationalDataPath(elanTag);
500 Optional<ElanTagName> existingElanInfo = read(broker,
501 LogicalDatastoreType.OPERATIONAL, elanId);
502 return existingElanInfo.orNull();
505 public static InstanceIdentifier<ElanTagName> getElanInfoEntriesOperationalDataPath(Uint32 elanTag) {
506 return InstanceIdentifier.builder(ElanTagNameMap.class).child(ElanTagName.class, new ElanTagNameKey(elanTag))
510 // interface-index-tag operational container
511 public Optional<IfIndexInterface> getInterfaceInfoByInterfaceTag(Uint32 interfaceTag) {
512 InstanceIdentifier<IfIndexInterface> interfaceId = getInterfaceInfoEntriesOperationalDataPath(interfaceTag);
513 return read(broker, LogicalDatastoreType.OPERATIONAL, interfaceId);
516 public static InstanceIdentifier<IfIndexInterface> getInterfaceInfoEntriesOperationalDataPath(Uint32 interfaceTag) {
517 return InstanceIdentifier.builder(IfIndexesInterfaceMap.class)
518 .child(IfIndexInterface.class,
519 new IfIndexInterfaceKey(Integer.valueOf(interfaceTag.intValue()))).build();
522 public static InstanceIdentifier<ElanDpnInterfacesList> getElanDpnOperationDataPath(String elanInstanceName) {
523 return InstanceIdentifier.builder(ElanDpnInterfaces.class)
524 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName)).build();
528 public ElanDpnInterfacesList getElanDpnInterfacesList(String elanName) {
529 InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanName);
530 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orNull();
534 public ElanDpnInterfaces getElanDpnInterfacesList() {
535 InstanceIdentifier<ElanDpnInterfaces> elanDpnInterfaceId = InstanceIdentifier.builder(ElanDpnInterfaces.class)
537 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orNull();
541 * This method is useful get all ELAN participating CSS dpIds to install
542 * program remote dmac entries and updating remote bc groups for tor
545 * @param elanInstanceName
546 * the elan instance name
547 * @return list of dpIds
550 public List<Uint64> getParticipatingDpnsInElanInstance(String elanInstanceName) {
551 List<Uint64> dpIds = new ArrayList<>();
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 dpIds.add(dpnInterface.getDpId());
565 public static long getElanRemoteBroadCastGroupID(long elanTag) {
566 return ElanConstants.ELAN_GID_MIN + elanTag % ElanConstants.ELAN_GID_MIN * 2;
570 * Gets the elan mac table.
574 * @return the elan mac table
577 public MacTable getElanMacTable(String elanName) {
578 return getElanMacTable(broker, elanName);
582 public static MacTable getElanMacTable(DataBroker dataBroker, String elanName) {
583 InstanceIdentifier<MacTable> elanMacTableId = getElanMacTableOperationalDataPath(elanName);
584 return read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanMacTableId).orNull();
587 public static long getElanLocalBCGId(long elanTag) {
588 return ElanConstants.ELAN_GID_MIN + (elanTag % ElanConstants.ELAN_GID_MIN * 2 - 1);
591 public static long getElanRemoteBCGId(long elanTag) {
592 return ElanConstants.ELAN_GID_MIN + elanTag % ElanConstants.ELAN_GID_MIN * 2;
595 public static long getEtreeLeafLocalBCGId(long etreeLeafTag) {
596 return ElanConstants.ELAN_GID_MIN + (etreeLeafTag % ElanConstants.ELAN_GID_MIN * 2 - 1);
599 public static long getEtreeLeafRemoteBCGId(long etreeLeafTag) {
600 return ElanConstants.ELAN_GID_MIN + etreeLeafTag % ElanConstants.ELAN_GID_MIN * 2;
603 public static Uint64 getElanMetadataLabel(long elanTag, boolean isSHFlagSet) {
604 int shBit = isSHFlagSet ? 1 : 0;
605 return Uint64.valueOf(BigInteger.valueOf(elanTag).shiftLeft(24).or(BigInteger.valueOf(shBit)));
609 * Setting SMAC, DMAC, UDMAC in this DPN and optionally in other DPNs.
613 * @param interfaceInfo
619 * @param configureRemoteFlows
620 * true if remote dmac flows should be configured as well
621 * @param writeFlowGroupTx
624 public void setupMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo,
625 long macTimeout, String macAddress, boolean configureRemoteFlows,
626 TypedWriteTransaction<Configuration> writeFlowGroupTx) {
627 try (Acquired lock = lockElanMacDPN(elanInfo.getElanTag().toJava(), macAddress, interfaceInfo.getDpId())) {
628 setupKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress, mdsalManager,
630 setupOrigDmacFlows(elanInfo, interfaceInfo, macAddress, configureRemoteFlows, mdsalManager,
635 public void setupDMacFlowOnRemoteDpn(ElanInstance elanInfo, InterfaceInfo interfaceInfo, Uint64 dstDpId,
636 String macAddress, TypedWriteTransaction<Configuration> writeFlowTx) {
637 String elanInstanceName = elanInfo.getElanInstanceName();
638 setupRemoteDmacFlow(dstDpId, interfaceInfo.getDpId(), interfaceInfo.getInterfaceTag(),
639 elanInfo.getElanTag(), macAddress, elanInstanceName, writeFlowTx,
640 interfaceInfo.getInterfaceName(), elanInfo);
641 LOG.info("Remote Dmac flow entry created for elan Name:{}, logical port Name:{} and"
642 + " mac address {} on dpn:{}", elanInstanceName, interfaceInfo.getPortName(),
643 macAddress, dstDpId);
647 * Inserts a Flow in SMAC table to state that the MAC has already been
650 private void setupKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
651 String macAddress, IMdsalApiManager mdsalApiManager,
652 TypedWriteTransaction<Configuration> writeFlowGroupTx) {
653 FlowEntity flowEntity = buildKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress);
654 mdsalApiManager.addFlow(writeFlowGroupTx, flowEntity);
655 LOG.debug("Known Smac flow entry created for elan Name:{}, logical Interface port:{} and mac address:{}",
656 elanInfo.getElanInstanceName(), elanInfo.getDescription(), macAddress);
659 public FlowEntity buildKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
661 int lportTag = interfaceInfo.getInterfaceTag();
662 // Matching metadata and eth_src fields
663 List<MatchInfo> mkMatches = new ArrayList<>();
664 mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanInfo.getElanTag().toJava(), lportTag),
665 ElanHelper.getElanMetadataMask()));
666 mkMatches.add(new MatchEthernetSource(new MacAddress(macAddress)));
667 List<InstructionInfo> mkInstructions = new ArrayList<>();
668 mkInstructions.add(new InstructionGotoTable(NwConstants.ELAN_DMAC_TABLE));
669 Uint64 dpId = interfaceInfo.getDpId();
670 Uint32 elanTag = getElanTag(elanInfo, interfaceInfo);
671 return new FlowEntityBuilder()
673 .setTableId(NwConstants.ELAN_SMAC_TABLE)
674 .setFlowId(getKnownDynamicmacFlowRef(elanTag, macAddress))
676 .setFlowName(elanInfo.getDescription())
677 .setIdleTimeOut((int) macTimeout)
679 .setCookie(Uint64.valueOf(ElanConstants.COOKIE_ELAN_KNOWN_SMAC.longValue() + elanTag.longValue()))
680 .setMatchInfoList(mkMatches)
681 .setInstructionInfoList(mkInstructions)
683 // If Mac timeout is 0, the flow won't be deleted automatically, so no need to get notified
684 .setSendFlowRemFlag(macTimeout != 0)
688 private Uint32 getElanTag(ElanInstance elanInfo, InterfaceInfo interfaceInfo) {
689 EtreeInterface etreeInterface = elanInterfaceCache.getEtreeInterface(interfaceInfo.getInterfaceName()).orNull();
690 if (etreeInterface == null || etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
691 return elanInfo.getElanTag();
693 EtreeInstance etreeInstance = elanInfo.augmentation(EtreeInstance.class);
694 if (etreeInstance == null) {
695 LOG.warn("EtreeInterface {} is connected to a non-Etree network: {}",
696 interfaceInfo.getInterfaceName(), elanInfo.getElanInstanceName());
697 return elanInfo.getElanTag();
699 return etreeInstance.getEtreeLeafTagVal().getValue();
705 * Installs a Flow in INTERNAL_TUNNEL_TABLE of the affected DPN that sends
706 * the packet through the specified interface if the tunnel_id matches the
707 * interface's lportTag.
709 * @param interfaceInfo
711 * @param mdsalApiManager
712 * the mdsal API manager
713 * @param writeFlowGroupTx
714 * the writeFLowGroup tx
716 public void setupTermDmacFlows(InterfaceInfo interfaceInfo, IMdsalApiManager mdsalApiManager,
717 TypedWriteTransaction<Configuration> writeFlowGroupTx) {
718 Uint64 dpId = interfaceInfo.getDpId();
719 int lportTag = interfaceInfo.getInterfaceTag();
720 Flow flow = MDSALUtil.buildFlowNew(NwConstants.INTERNAL_TUNNEL_TABLE,
721 getIntTunnelTableFlowRef(NwConstants.INTERNAL_TUNNEL_TABLE, lportTag), 5,
722 String.format("%s:%d", "ITM Flow Entry ", lportTag), 0, 0,
723 Uint64.valueOf(ITMConstants.COOKIE_ITM.longValue() + lportTag),
724 getTunnelIdMatchForFilterEqualsLPortTag(lportTag),
725 getInstructionsInPortForOutGroup(interfaceInfo.getInterfaceName()));
726 mdsalApiManager.addFlow(writeFlowGroupTx, dpId, flow);
727 LOG.debug("Terminating service table flow entry created on dpn:{} for logical Interface port:{}", dpId,
728 interfaceInfo.getPortName());
732 * Constructs the FlowName for flows installed in the Internal Tunnel Table,
733 * consisting in tableId + elanTag.
739 * @return the Internal tunnel
741 public static String getIntTunnelTableFlowRef(short tableId, int elanTag) {
742 return new StringBuilder().append(tableId).append(elanTag).toString();
746 * Constructs the Matches that checks that the tunnel_id field contains a
750 * lportTag that must be checked against the tunnel_id field
751 * @return the list of match Info
753 public static List<MatchInfo> getTunnelIdMatchForFilterEqualsLPortTag(int lportTag) {
754 List<MatchInfo> mkMatches = new ArrayList<>();
756 mkMatches.add(new MatchTunnelId(Uint64.valueOf(lportTag)));
761 * Constructs the Instructions that take the packet over a given interface.
764 * Name of the interface where the packet must be sent over. It
765 * can be a local interface or a tunnel interface (internal or
767 * @return the Instruction
769 public List<Instruction> getInstructionsInPortForOutGroup(String ifName) {
770 List<Instruction> mkInstructions = new ArrayList<>();
771 List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
773 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
774 return mkInstructions;
778 * Returns the list of Actions to be taken when sending the packet through
779 * an Elan interface. Note that this interface can refer to an ElanInterface
780 * where the Elan VM is attached to a DPN or an ITM tunnel interface where
781 * Elan traffic can be sent through. In this latter case, the tunnelKey is
782 * mandatory and it can hold serviceId for internal tunnels or the VNI for
789 * @return the egress actions for interface
791 @SuppressWarnings("checkstyle:IllegalCatch")
793 public List<Action> getEgressActionsForInterface(String ifName, @Nullable Long tunnelKey) {
794 List<Action> listAction = new ArrayList<>();
796 GetEgressActionsForInterfaceInput getEgressActionInput = new GetEgressActionsForInterfaceInputBuilder()
797 .setIntfName(ifName).setTunnelKey(tunnelKey).build();
798 Future<RpcResult<GetEgressActionsForInterfaceOutput>> result = interfaceManagerRpcService
799 .getEgressActionsForInterface(getEgressActionInput);
800 RpcResult<GetEgressActionsForInterfaceOutput> rpcResult = result.get();
801 if (!rpcResult.isSuccessful()) {
802 LOG.debug("RPC Call to Get egress actions for interface {} returned with Errors {}", ifName,
803 rpcResult.getErrors());
805 listAction = rpcResult.getResult().nonnullAction();
807 } catch (Exception e) {
808 LOG.warn("Exception when egress actions for interface {}", ifName, e);
813 private void setupOrigDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
814 boolean configureRemoteFlows, IMdsalApiManager mdsalApiManager,
815 TypedWriteTransaction<Configuration> writeFlowGroupTx) {
816 Uint64 dpId = interfaceInfo.getDpId();
817 String ifName = interfaceInfo.getInterfaceName();
818 long ifTag = interfaceInfo.getInterfaceTag();
819 String elanInstanceName = elanInfo.getElanInstanceName();
821 Uint32 elanTag = elanInfo.getElanTag();
823 setupLocalDmacFlow(elanTag, dpId, ifName, macAddress, elanInfo, mdsalApiManager, ifTag,
825 LOG.debug("Dmac flow entry created for elan Name:{}, logical port Name:{} mand mac address:{} "
826 + "on dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, dpId);
828 if (!configureRemoteFlows) {
832 List<DpnInterfaces> elanDpns = getInvolvedDpnsInElan(elanInstanceName);
833 for (DpnInterfaces elanDpn : elanDpns) {
835 if (Objects.equals(elanDpn.getDpId(), dpId)) {
839 // Check for the Remote DPN present in Inventory Manager
840 if (!isDpnPresent(elanDpn.getDpId())) {
844 // For remote DPNs a flow is needed to indicate that packets of this ELAN going to this MAC need to be
845 // forwarded through the appropriate ITM tunnel
846 setupRemoteDmacFlow(elanDpn.getDpId(), // srcDpn (the remote DPN in this case)
847 dpId, // dstDpn (the local DPN)
848 interfaceInfo.getInterfaceTag(), // lportTag of the local interface
849 elanTag, // identifier of the Elan
850 macAddress, // MAC to be programmed in remote DPN
851 elanInstanceName, writeFlowGroupTx, ifName, elanInfo
853 LOG.debug("Remote Dmac flow entry created for elan Name:{}, logical port Name:{} and mac address:{} on"
854 + " dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, elanDpn.getDpId());
857 // TODO: Make sure that the same is performed against the ElanDevices.
861 public List<DpnInterfaces> getInvolvedDpnsInElan(String elanName) {
862 return getElanDPNByName(elanName);
866 public List<DpnInterfaces> getElanDPNByName(String elanInstanceName) {
867 InstanceIdentifier<ElanDpnInterfacesList> elanIdentifier = getElanDpnOperationDataPath(elanInstanceName);
868 return MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL, elanIdentifier).toJavaUtil().map(
869 ElanDpnInterfacesList::getDpnInterfaces).orElse(emptyList());
872 private void setupLocalDmacFlow(Uint32 elanTag, Uint64 dpId, String ifName, String macAddress,
873 ElanInstance elanInfo, IMdsalApiManager mdsalApiManager, long ifTag,
874 TypedWriteTransaction<Configuration> writeFlowGroupTx) {
875 Flow flowEntity = buildLocalDmacFlowEntry(elanTag, dpId, ifName, macAddress, elanInfo, ifTag);
876 mdsalApiManager.addFlow(writeFlowGroupTx, dpId, flowEntity);
877 installEtreeLocalDmacFlow(elanTag, dpId, ifName, macAddress, elanInfo, ifTag, writeFlowGroupTx);
880 private void installEtreeLocalDmacFlow(Uint32 elanTag, Uint64 dpId, String ifName, String macAddress,
881 ElanInstance elanInfo, long ifTag, TypedWriteTransaction<Configuration> writeFlowGroupTx) {
882 EtreeInterface etreeInterface = elanInterfaceCache.getEtreeInterface(ifName).orNull();
883 if (etreeInterface != null && etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
884 EtreeLeafTagName etreeTagName = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag.longValue());
885 if (etreeTagName == null) {
886 LOG.warn("Interface {} seems like it belongs to Etree but etreeTagName from elanTag {} is null",
889 Flow flowEntity = buildLocalDmacFlowEntry(etreeTagName.getEtreeLeafTag().getValue(), dpId,
890 ifName, macAddress, elanInfo, ifTag);
891 mdsalManager.addFlow(writeFlowGroupTx, dpId, flowEntity);
896 public static String getKnownDynamicmacFlowRef(Uint32 elanTag, String macAddress) {
897 return new StringBuffer().append(elanTag).append(macAddress.toLowerCase(Locale.getDefault())).toString();
900 public static String getKnownDynamicmacFlowRef(short elanDmacTable, Uint64 dpId, String extDeviceNodeId,
901 String dstMacAddress, long elanTag, boolean shFlag) {
902 return String.valueOf(elanDmacTable) + elanTag + dpId + extDeviceNodeId + dstMacAddress + shFlag;
906 * Builds the flow to be programmed in the DMAC table of the local DPN (that
907 * is, where the MAC is attached to). This flow consists in:
909 * <p>Match: + elanTag in metadata + packet goes to a MAC locally attached
910 * Actions: + optionally, pop-vlan + set-vlan-id + output to ifName's
927 public Flow buildLocalDmacFlowEntry(Uint32 elanTag, Uint64 dpId, String ifName, String macAddress,
928 ElanInstance elanInfo, long ifTag) {
930 List<MatchInfo> mkMatches = new ArrayList<>();
931 mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag.longValue()),
932 MetaDataUtil.METADATA_MASK_SERVICE));
933 mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddress)));
935 List<Instruction> mkInstructions = new ArrayList<>();
936 List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
937 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
938 Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
939 getKnownDynamicmacFlowRef(elanTag, macAddress), 20,
940 elanInfo.getElanInstanceName(), 0, 0,
941 Uint64.valueOf(ElanConstants.COOKIE_ELAN_KNOWN_DMAC.longValue() + elanTag.longValue()),
942 mkMatches, mkInstructions);
947 public void setupRemoteDmacFlow(Uint64 srcDpId, Uint64 destDpId, int lportTag, Uint32 elanTag,
948 String macAddress, String displayName, TypedWriteTransaction<Configuration> writeFlowGroupTx,
949 String interfaceName, ElanInstance elanInstance) {
950 if (interfaceManager.isExternalInterface(interfaceName)) {
951 LOG.debug("Ignoring install remote DMAC {} flow on provider interface {} elan {}",
952 macAddress, interfaceName, elanInstance.getElanInstanceName());
955 // if openstack-vni-semantics are enforced, segmentation ID is passed as network VNI for VxLAN based provider
956 // networks, 0 otherwise
957 long lportTagOrVni = !isOpenstackVniSemanticsEnforced() ? lportTag : isVxlanNetworkOrVxlanSegment(elanInstance)
958 ? getVxlanSegmentationId(elanInstance).longValue() : 0;
959 Flow flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTagOrVni, elanTag, macAddress, displayName,
961 mdsalManager.addFlow(writeFlowGroupTx, srcDpId, flowEntity);
962 setupEtreeRemoteDmacFlow(srcDpId, destDpId, lportTagOrVni, elanTag, macAddress, displayName, interfaceName,
963 writeFlowGroupTx, elanInstance);
966 private void setupEtreeRemoteDmacFlow(Uint64 srcDpId, Uint64 destDpId, long lportTagOrVni, Uint32 elanTag,
967 String macAddress, String displayName, String interfaceName,
968 TypedWriteTransaction<Configuration> writeFlowGroupTx,
969 ElanInstance elanInstance) {
971 EtreeInterface etreeInterface = elanInterfaceCache.getEtreeInterface(interfaceName).orNull();
972 if (etreeInterface != null && etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
973 EtreeLeafTagName etreeTagName = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag.longValue());
974 if (etreeTagName == null) {
975 LOG.warn("Interface {} seems like it belongs to Etree but etreeTagName from elanTag {} is null.",
976 interfaceName, elanTag);
978 flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTagOrVni,
979 etreeTagName.getEtreeLeafTag().getValue(), macAddress, displayName, elanInstance);
980 mdsalManager.addFlow(writeFlowGroupTx, srcDpId, flowEntity);
986 * Builds a Flow to be programmed in a remote DPN's DMAC table. This flow
987 * consists in: Match: + elanTag in packet's metadata + packet going to a
988 * MAC known to be located in another DPN Actions: + set_tunnel_id
989 * + output ITM internal tunnel interface with the other DPN
995 * @param lportTagOrVni
996 * lportTag or network VNI
1001 * @param displayName
1003 * @param elanInstance
1005 * @return the flow remote Dmac
1007 @SuppressWarnings("checkstyle:IllegalCatch")
1008 public Flow buildRemoteDmacFlowEntry(Uint64 srcDpId, Uint64 destDpId, long lportTagOrVni, Uint32 elanTag,
1009 String macAddress, String displayName, ElanInstance elanInstance) {
1010 List<MatchInfo> mkMatches = new ArrayList<>();
1011 mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag.longValue()),
1012 MetaDataUtil.METADATA_MASK_SERVICE));
1013 mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddress)));
1015 List<Instruction> mkInstructions = new ArrayList<>();
1017 // List of Action for the provided Source and Destination DPIDs
1019 List<Action> actions = null;
1020 if (isVxlanNetworkOrVxlanSegment(elanInstance)) {
1021 actions = elanItmUtils.getInternalTunnelItmEgressAction(srcDpId, destDpId, lportTagOrVni);
1022 } else if (isVlan(elanInstance) || isFlat(elanInstance)) {
1023 String interfaceName = getExternalElanInterface(elanInstance.getElanInstanceName(), srcDpId);
1024 if (null == interfaceName) {
1025 LOG.info("buildRemoteDmacFlowEntry: Could not find interfaceName for {} {}", srcDpId,
1028 actions = getEgressActionsForInterface(interfaceName, null);
1030 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
1031 } catch (Exception e) {
1032 LOG.error("Could not get egress actions to add to flow for srcDpId {}, destDpId {}, lportTag/VNI {}",
1033 srcDpId, destDpId, lportTagOrVni, e);
1036 Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
1037 getKnownDynamicmacFlowRef(elanTag, macAddress),
1039 displayName, 0, /* idleTimeout */
1040 0, /* hardTimeout */
1041 Uint64.valueOf(ElanConstants.COOKIE_ELAN_KNOWN_DMAC.longValue() + elanTag.longValue()),
1042 mkMatches, mkInstructions);
1048 public void deleteMacFlows(@Nullable ElanInstance elanInfo, @Nullable InterfaceInfo interfaceInfo,
1049 MacEntry macEntry, TypedReadWriteTransaction<Configuration> flowTx)
1050 throws ExecutionException, InterruptedException {
1051 if (elanInfo == null || interfaceInfo == null) {
1054 String macAddress = macEntry.getMacAddress().getValue();
1055 try (Acquired lock = lockElanMacDPN(elanInfo.getElanTag().toJava(),
1056 macAddress, interfaceInfo.getDpId())) {
1057 deleteMacFlows(elanInfo, interfaceInfo, macAddress, /* alsoDeleteSMAC */ true, flowTx);
1061 public void deleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1062 boolean deleteSmac, TypedReadWriteTransaction<Configuration> flowTx)
1063 throws ExecutionException, InterruptedException {
1064 String elanInstanceName = elanInfo.getElanInstanceName();
1065 List<DpnInterfaces> remoteFEs = getInvolvedDpnsInElan(elanInstanceName);
1066 Uint64 srcdpId = interfaceInfo.getDpId();
1067 boolean isFlowsRemovedInSrcDpn = false;
1068 for (DpnInterfaces dpnInterface : remoteFEs) {
1069 Uint32 elanTag = elanInfo.getElanTag();
1070 Uint64 dstDpId = dpnInterface.getDpId();
1071 if (executeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1072 elanTag, dstDpId, flowTx)) {
1073 isFlowsRemovedInSrcDpn = true;
1075 executeEtreeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1076 elanTag, dstDpId, flowTx);
1078 if (!isFlowsRemovedInSrcDpn) {
1079 deleteSmacAndDmacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, flowTx);
1083 private void executeEtreeDeleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1084 boolean deleteSmac, String elanInstanceName, Uint64 srcdpId, Uint32 elanTag, Uint64 dstDpId,
1085 TypedReadWriteTransaction<Configuration> flowTx) throws ExecutionException, InterruptedException {
1086 EtreeLeafTagName etreeLeafTag = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag.longValue());
1087 if (etreeLeafTag != null) {
1088 executeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1089 etreeLeafTag.getEtreeLeafTag().getValue(), dstDpId, flowTx);
1093 private boolean executeDeleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1094 boolean deleteSmac, String elanInstanceName, Uint64 srcdpId, Uint32 elanTag, Uint64 dstDpId,
1095 TypedReadWriteTransaction<Configuration> flowTx) throws ExecutionException, InterruptedException {
1096 boolean isFlowsRemovedInSrcDpn = false;
1097 if (dstDpId.equals(srcdpId)) {
1098 isFlowsRemovedInSrcDpn = true;
1099 deleteSmacAndDmacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, flowTx);
1100 } else if (isDpnPresent(dstDpId)) {
1102 .removeFlow(flowTx, dstDpId,
1103 MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, getKnownDynamicmacFlowRef(elanTag, macAddress)));
1104 LOG.debug("Dmac flow entry deleted for elan:{}, logical interface port:{} and mac address:{} on dpn:{}",
1105 elanInstanceName, interfaceInfo.getPortName(), macAddress, dstDpId);
1107 return isFlowsRemovedInSrcDpn;
1110 public void deleteSmacFlowOnly(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1111 TypedReadWriteTransaction<Configuration> flowTx) throws ExecutionException,
1112 InterruptedException {
1113 Uint64 srcdpId = interfaceInfo.getDpId();
1114 Uint32 elanTag = elanInfo.getElanTag();
1115 LOG.debug("Deleting SMAC flow with id {}", getKnownDynamicmacFlowRef(elanTag, macAddress));
1116 mdsalManager.removeFlow(flowTx, srcdpId,
1117 MDSALUtil.buildFlow(NwConstants.ELAN_SMAC_TABLE, getKnownDynamicmacFlowRef(elanTag, macAddress)));
1120 private void deleteSmacAndDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1121 boolean deleteSmac, TypedReadWriteTransaction<Configuration> flowTx)
1122 throws ExecutionException, InterruptedException {
1123 String elanInstanceName = elanInfo.getElanInstanceName();
1124 Uint64 srcdpId = interfaceInfo.getDpId();
1125 Uint32 elanTag = elanInfo.getElanTag();
1127 LOG.debug("Deleting SMAC flow with id {}", getKnownDynamicmacFlowRef(elanTag, macAddress));
1129 .removeFlow(flowTx, srcdpId,
1130 MDSALUtil.buildFlow(NwConstants.ELAN_SMAC_TABLE,
1131 getKnownDynamicmacFlowRef(elanTag, macAddress)));
1133 mdsalManager.removeFlow(flowTx, srcdpId,
1134 MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE,
1135 getKnownDynamicmacFlowRef(elanTag, macAddress)));
1136 LOG.debug("All the required flows deleted for elan:{}, logical Interface port:{} and MAC address:{} on dpn:{}",
1137 elanInstanceName, interfaceInfo.getPortName(), macAddress, srcdpId);
1141 * Updates the Elan information in the Operational DS. It also updates the
1142 * ElanInstance in the Config DS by setting the adquired elanTag.
1146 * @param elanInstanceAdded
1147 * the elan instance added
1148 * @param elanInterfaces
1149 * the elan interfaces
1153 * @return the updated ELAN instance.
1155 public static ElanInstance updateOperationalDataStore(IdManagerService idManager,
1156 ElanInstance elanInstanceAdded, List<String> elanInterfaces, TypedWriteTransaction<Configuration> confTx,
1157 TypedWriteTransaction<Operational> operTx) {
1158 String elanInstanceName = elanInstanceAdded.getElanInstanceName();
1159 Uint32 elanTag = elanInstanceAdded.getElanTag();
1160 if (elanTag == null || elanTag.longValue() == 0L) {
1161 elanTag = retrieveNewElanTag(idManager, elanInstanceName);
1163 Elan elanInfo = new ElanBuilder().setName(elanInstanceName).setElanInterfaces(elanInterfaces)
1164 .withKey(new ElanKey(elanInstanceName)).build();
1166 // Add the ElanState in the elan-state operational data-store
1167 operTx.put(getElanInstanceOperationalDataPath(elanInstanceName), elanInfo, CREATE_MISSING_PARENTS);
1169 // Add the ElanMacTable in the elan-mac-table operational data-store
1170 MacTable elanMacTable = new MacTableBuilder().withKey(new MacTableKey(elanInstanceName)).build();
1171 operTx.put(getElanMacTableOperationalDataPath(elanInstanceName), elanMacTable, CREATE_MISSING_PARENTS);
1173 ElanTagNameBuilder elanTagNameBuilder = new ElanTagNameBuilder().setElanTag(elanTag)
1174 .withKey(new ElanTagNameKey(elanTag)).setName(elanInstanceName);
1175 Uint32 etreeLeafTag = Uint32.valueOf(0L);
1176 if (isEtreeInstance(elanInstanceAdded)) {
1177 etreeLeafTag = retrieveNewElanTag(idManager,elanInstanceName + ElanConstants
1179 EtreeLeafTagName etreeLeafTagName = new EtreeLeafTagNameBuilder()
1180 .setEtreeLeafTag(new EtreeLeafTag(etreeLeafTag)).build();
1181 elanTagNameBuilder.addAugmentation(EtreeLeafTagName.class, etreeLeafTagName);
1182 addTheLeafTagAsElanTag(elanInstanceName, etreeLeafTag, operTx);
1184 ElanTagName elanTagName = elanTagNameBuilder.build();
1186 // Add the ElanTag to ElanName in the elan-tag-name Operational
1188 operTx.put(getElanInfoEntriesOperationalDataPath(elanTag), elanTagName);
1190 // Updates the ElanInstance Config DS by setting the just acquired
1192 ElanInstanceBuilder elanInstanceBuilder = new ElanInstanceBuilder(elanInstanceAdded)
1193 .setElanInstanceName(elanInstanceName)
1194 .setDescription(elanInstanceAdded.getDescription())
1195 .setMacTimeout(elanInstanceAdded.getMacTimeout() == null
1196 ? Uint32.valueOf(ElanConstants.DEFAULT_MAC_TIME_OUT) : elanInstanceAdded.getMacTimeout())
1197 .withKey(elanInstanceAdded.key()).setElanTag(elanTag);
1198 if (isEtreeInstance(elanInstanceAdded)) {
1199 EtreeInstance etreeInstance = new EtreeInstanceBuilder().setEtreeLeafTagVal(new EtreeLeafTag(etreeLeafTag))
1201 elanInstanceBuilder.addAugmentation(EtreeInstance.class, etreeInstance);
1203 ElanInstance elanInstanceWithTag = elanInstanceBuilder.build();
1204 LOG.trace("Updated elan Operational DS for elan: {} with elanTag: {} and interfaces: {}", elanInstanceName,
1205 elanTag, elanInterfaces);
1206 confTx.merge(ElanHelper.getElanInstanceConfigurationDataPath(elanInstanceName), elanInstanceWithTag,
1207 CREATE_MISSING_PARENTS);
1208 return elanInstanceWithTag;
1211 private static void addTheLeafTagAsElanTag(String elanInstanceName,Uint32 etreeLeafTag,
1212 TypedWriteTransaction<Operational> tx) {
1213 ElanTagName etreeTagAsElanTag = new ElanTagNameBuilder().setElanTag(etreeLeafTag)
1214 .withKey(new ElanTagNameKey(etreeLeafTag)).setName(elanInstanceName).build();
1215 tx.put(getElanInfoEntriesOperationalDataPath(etreeLeafTag), etreeTagAsElanTag);
1218 private static boolean isEtreeInstance(ElanInstance elanInstanceAdded) {
1219 return elanInstanceAdded.augmentation(EtreeInstance.class) != null;
1222 public boolean isDpnPresent(Uint64 dpnId) {
1223 String dpn = String.format("%s:%s", "openflow", dpnId);
1224 NodeId nodeId = new NodeId(dpn);
1226 InstanceIdentifier<Node> node = InstanceIdentifier.builder(Nodes.class).child(Node.class, new NodeKey(nodeId))
1228 return read(broker, LogicalDatastoreType.CONFIGURATION, node).isPresent();
1231 public static String getElanServiceName(String elanName, String interfaceName) {
1232 return "elan." + elanName + interfaceName;
1235 public static BoundServices getBoundServices(String serviceName, short servicePriority, int flowPriority,
1236 Uint64 cookie, List<Instruction> instructions) {
1237 StypeOpenflowBuilder augBuilder = new StypeOpenflowBuilder().setFlowCookie(cookie).setFlowPriority(flowPriority)
1238 .setInstruction(instructions);
1239 return new BoundServicesBuilder().withKey(new BoundServicesKey(servicePriority)).setServiceName(serviceName)
1240 .setServicePriority(servicePriority).setServiceType(ServiceTypeFlowBased.class)
1241 .addAugmentation(StypeOpenflow.class, augBuilder.build()).build();
1244 public static InstanceIdentifier<BoundServices> buildServiceId(String interfaceName, short serviceIndex) {
1245 return InstanceIdentifier.builder(ServiceBindings.class)
1246 .child(ServicesInfo.class, new ServicesInfoKey(interfaceName, ServiceModeIngress.class))
1247 .child(BoundServices.class, new BoundServicesKey(serviceIndex)).build();
1250 public static List<MatchInfo> getTunnelMatchesForServiceId(Uint32 elanTag) {
1251 List<MatchInfo> mkMatches = new ArrayList<>();
1253 // Adding 270000 to avoid collision between LPort and elan tag for broadcast
1254 mkMatches.add(new MatchTunnelId(Uint64.valueOf(elanTag.longValue() + ElanConstants.ELAN_TAG_ADDEND)));
1259 public void removeTerminatingServiceAction(Uint64 destDpId, int serviceId) {
1260 RemoveTerminatingServiceActionsInput input = new RemoveTerminatingServiceActionsInputBuilder()
1261 .setDpnId(destDpId).setServiceId(serviceId).build();
1262 Future<RpcResult<RemoveTerminatingServiceActionsOutput>> futureObject =
1263 itmRpcService.removeTerminatingServiceActions(input);
1265 RpcResult<RemoveTerminatingServiceActionsOutput> result = futureObject.get();
1266 if (result.isSuccessful()) {
1267 LOG.debug("Successfully completed removeTerminatingServiceActions for ELAN with serviceId {} on "
1268 + "dpn {}", serviceId, destDpId);
1270 LOG.debug("Failure in removeTerminatingServiceAction RPC call for ELAN with serviceId {} on "
1271 + "dpn {}", serviceId, destDpId);
1273 } catch (InterruptedException | ExecutionException e) {
1274 LOG.error("Error in RPC call removeTerminatingServiceActions for ELAN with serviceId {} on "
1275 + "dpn {}", serviceId, destDpId, e);
1280 * Gets the external tunnel.
1282 * @param sourceDevice
1284 * @param destinationDevice
1285 * the destination device
1286 * @param datastoreType
1287 * the datastore type
1288 * @return the external tunnel
1291 public ExternalTunnel getExternalTunnel(String sourceDevice, String destinationDevice,
1292 LogicalDatastoreType datastoreType) {
1293 Class<? extends TunnelTypeBase> tunType = TunnelTypeVxlan.class;
1294 InstanceIdentifier<ExternalTunnel> iid = InstanceIdentifier.builder(ExternalTunnelList.class)
1295 .child(ExternalTunnel.class, new ExternalTunnelKey(destinationDevice, sourceDevice, tunType)).build();
1296 return read(broker, datastoreType, iid).orNull();
1300 * Gets the external tunnel.
1302 * @param interfaceName
1303 * the interface name
1304 * @param datastoreType
1305 * the datastore type
1306 * @return the external tunnel
1309 public ExternalTunnel getExternalTunnel(String interfaceName, LogicalDatastoreType datastoreType) {
1310 ExternalTunnel externalTunnel = null;
1311 List<ExternalTunnel> externalTunnels = getAllExternalTunnels(datastoreType);
1312 for (ExternalTunnel tunnel : externalTunnels) {
1313 if (StringUtils.equalsIgnoreCase(interfaceName, tunnel.getTunnelInterfaceName())) {
1314 externalTunnel = tunnel;
1318 return externalTunnel;
1322 * Gets the all external tunnels.
1324 * @param datastoreType
1325 * the data store type
1326 * @return the all external tunnels
1328 public List<ExternalTunnel> getAllExternalTunnels(LogicalDatastoreType datastoreType) {
1329 InstanceIdentifier<ExternalTunnelList> iid = InstanceIdentifier.builder(ExternalTunnelList.class).build();
1330 return read(broker, datastoreType, iid).toJavaUtil().map(ExternalTunnelList::getExternalTunnel).orElse(
1334 public static List<MatchInfo> buildMatchesForElanTagShFlagAndDstMac(long elanTag, boolean shFlag, String macAddr) {
1335 List<MatchInfo> mkMatches = new ArrayList<>();
1337 new MatchMetadata(getElanMetadataLabel(elanTag, shFlag), MetaDataUtil.METADATA_MASK_SERVICE_SH_FLAG));
1338 mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddr)));
1343 * Checks if is interface operational.
1345 * @param interfaceName
1346 * the interface name
1349 * @return true, if is interface operational
1351 public static boolean isInterfaceOperational(String interfaceName, DataBroker dataBroker) {
1352 if (StringUtils.isBlank(interfaceName)) {
1355 Interface ifState = getInterfaceStateFromOperDS(interfaceName, dataBroker);
1356 if (ifState == null) {
1359 return ifState.getOperStatus() == OperStatus.Up && ifState.getAdminStatus() == AdminStatus.Up;
1363 * Gets the interface state from operational ds.
1365 * @param interfaceName
1366 * the interface name
1369 * @return the interface state from oper ds
1371 public static org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state
1372 .@Nullable Interface getInterfaceStateFromOperDS(String interfaceName, DataBroker dataBroker) {
1373 return MDSALUtil.read(dataBroker, LogicalDatastoreType.OPERATIONAL,
1374 createInterfaceStateInstanceIdentifier(interfaceName)).orNull();
1378 * Creates the interface state instance identifier.
1380 * @param interfaceName
1381 * the interface name
1382 * @return the instance identifier
1384 public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1385 .ietf.interfaces.rev140508.interfaces.state.Interface> createInterfaceStateInstanceIdentifier(
1386 String interfaceName) {
1387 InstanceIdentifierBuilder<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1388 .ietf.interfaces.rev140508.interfaces.state.Interface> idBuilder = InstanceIdentifier
1389 .builder(InterfacesState.class)
1390 .child(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1391 .ietf.interfaces.rev140508.interfaces.state.Interface.class,
1392 new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1393 .ietf.interfaces.rev140508.interfaces.state.InterfaceKey(
1395 return idBuilder.build();
1399 public static ListenableFuture<Void> waitForTransactionToComplete(ListenableFuture<Void> future) {
1402 } catch (InterruptedException | ExecutionException e) {
1403 // NETVIRT-1215: Do not log.error() here, only debug(); but callers *MUST* @CheckReturnValue
1404 LOG.debug("Error writing to datastore", e);
1409 public static boolean isVxlan(@Nullable ElanInstance elanInstance) {
1410 return elanInstance != null && elanInstance.getSegmentType() != null
1411 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1412 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId().toJava() != 0;
1415 private static boolean isVxlanSegment(@Nullable ElanInstance elanInstance) {
1416 if (elanInstance != null) {
1417 List<ElanSegments> elanSegments = elanInstance.getElanSegments();
1418 if (elanSegments != null) {
1419 for (ElanSegments segment : elanSegments) {
1420 if (segment != null && segment.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1421 && segment.getSegmentationId() != null
1422 && segment.getSegmentationId().longValue() != 0) {
1431 public static boolean isVxlanNetworkOrVxlanSegment(@Nullable ElanInstance elanInstance) {
1432 return isVxlan(elanInstance) || isVxlanSegment(elanInstance);
1435 public static Uint32 getVxlanSegmentationId(ElanInstance elanInstance) {
1436 Uint32 segmentationId = Uint32.ZERO;
1437 if (elanInstance == null) {
1438 return segmentationId;
1441 if (elanInstance.getSegmentType() != null
1442 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1443 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId().longValue() != 0) {
1444 segmentationId = elanInstance.getSegmentationId();
1446 for (ElanSegments segment: elanInstance.getElanSegments()) {
1447 if (segment != null && segment.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1448 && segment.getSegmentationId() != null
1449 && segment.getSegmentationId().longValue() != 0) {
1450 segmentationId = segment.getSegmentationId();
1454 return segmentationId;
1457 public static boolean isVlan(ElanInstance elanInstance) {
1458 return elanInstance != null && elanInstance.getSegmentType() != null
1459 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVlan.class)
1460 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId().toJava() != 0;
1463 public static boolean isFlat(ElanInstance elanInstance) {
1464 return elanInstance != null && elanInstance.getSegmentType() != null
1465 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeFlat.class);
1468 public void addDmacRedirectToDispatcherFlows(Uint32 elanTag, String displayName,
1469 String macAddress, List<Uint64> dpnIds) {
1470 for (Uint64 dpId : dpnIds) {
1471 LoggingFutures.addErrorLogging(txRunner.callWithNewWriteOnlyTransactionAndSubmit(CONFIGURATION,
1472 tx -> mdsalManager.addFlow(tx, buildDmacRedirectToDispatcherFlow(dpId, macAddress, displayName,
1474 "Error adding DMAC redirect to dispatcher flows");
1478 public void removeDmacRedirectToDispatcherFlows(Uint32 elanTag, String macAddress, List<Uint64> dpnIds) {
1479 LoggingFutures.addErrorLogging(
1480 txRunner.callWithNewReadWriteTransactionAndSubmit(Datastore.CONFIGURATION, tx -> {
1481 for (Uint64 dpId : dpnIds) {
1482 String flowId = getKnownDynamicmacFlowRef(elanTag, macAddress);
1483 mdsalManager.removeFlow(tx, dpId, MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, flowId));
1485 }), LOG, "Error removing DMAC redirect to dispatcher flows");
1488 public static FlowEntity buildDmacRedirectToDispatcherFlow(Uint64 dpId, String dstMacAddress,
1489 String displayName, Uint32 elanTag) {
1490 List<MatchInfo> matches = new ArrayList<>();
1491 matches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag.longValue()),
1492 MetaDataUtil.METADATA_MASK_SERVICE));
1493 matches.add(new MatchEthernetDestination(new MacAddress(dstMacAddress)));
1494 List<InstructionInfo> instructions = new ArrayList<>();
1495 List<ActionInfo> actions = new ArrayList<>();
1496 actions.add(new ActionNxResubmit(NwConstants.LPORT_DISPATCHER_TABLE));
1498 instructions.add(new InstructionApplyActions(actions));
1499 String flowId = getKnownDynamicmacFlowRef(elanTag, dstMacAddress);
1500 return MDSALUtil.buildFlowEntity(dpId, NwConstants.ELAN_DMAC_TABLE, flowId, 20, displayName, 0, 0,
1501 Uint64.valueOf(ElanConstants.COOKIE_ELAN_KNOWN_DMAC.longValue() + elanTag.longValue()),
1502 matches, instructions);
1506 public String getExternalElanInterface(String elanInstanceName, Uint64 dpnId) {
1507 DpnInterfaces dpnInterfaces = getElanInterfaceInfoByElanDpn(elanInstanceName, dpnId);
1508 if (dpnInterfaces == null || dpnInterfaces.getInterfaces() == null) {
1509 LOG.trace("Elan {} does not have interfaces in DPN {}", elanInstanceName, dpnId);
1513 for (String dpnInterface : dpnInterfaces.getInterfaces()) {
1514 if (interfaceManager.isExternalInterface(dpnInterface)) {
1515 return dpnInterface;
1519 LOG.trace("Elan {} does not have any external interace attached to DPN {}", elanInstanceName, dpnId);
1523 public static Acquired lockElanMacDPN(long elanTag, String macAddress, Uint64 dpnId) {
1524 return ELAN_LOCKS.acquire(new ElanLockName(elanTag, macAddress, dpnId));
1527 public static List<ListenableFuture<Void>>
1528 returnFailedListenableFutureIfTransactionCommitFailedExceptionCauseOrElseThrow(RuntimeException exception) {
1530 Throwable cause = exception.getCause();
1531 if (cause != null && cause instanceof TransactionCommitFailedException) {
1532 return Collections.singletonList(Futures.immediateFailedFuture(cause));
1538 public static List<PhysAddress> getPhysAddress(List<String> macAddress) {
1539 Preconditions.checkNotNull(macAddress, "macAddress cannot be null");
1540 List<PhysAddress> physAddresses = new ArrayList<>();
1541 for (String mac : macAddress) {
1542 physAddresses.add(new PhysAddress(mac));
1544 return physAddresses;
1547 public static List<StaticMacEntries> getStaticMacEntries(List<String> staticMacAddresses) {
1548 if (isEmpty(staticMacAddresses)) {
1549 return Collections.EMPTY_LIST;
1551 StaticMacEntriesBuilder staticMacEntriesBuilder = new StaticMacEntriesBuilder();
1552 List<StaticMacEntries> staticMacEntries = new ArrayList<>();
1553 List<PhysAddress> physAddressList = getPhysAddress(staticMacAddresses);
1554 for (PhysAddress physAddress : physAddressList) {
1555 staticMacEntries.add(staticMacEntriesBuilder.setMacAddress(physAddress).build());
1557 return staticMacEntries;
1560 public static InstanceIdentifier<StaticMacEntries> getStaticMacEntriesCfgDataPathIdentifier(String interfaceName,
1561 String macAddress) {
1562 return InstanceIdentifier.builder(ElanInterfaces.class)
1563 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).child(StaticMacEntries.class,
1564 new StaticMacEntriesKey(new PhysAddress(macAddress))).build();
1567 public static <T> List<T> diffOf(List<T> orig, List<T> updated) {
1568 if (isEmpty(orig)) {
1569 return Collections.EMPTY_LIST;
1571 List<T> diff = Lists.newArrayList(orig);
1572 if (isNotEmpty(updated)) {
1573 diff.removeAll(updated);
1578 public static boolean isEmpty(Collection collection) {
1579 return collection == null || collection.isEmpty();
1582 public static boolean isNotEmpty(Collection collection) {
1583 return !isEmpty(collection);
1586 public Optional<IpAddress> getSourceIpAddress(Ethernet ethernet) {
1587 Optional<IpAddress> srcIpAddress = Optional.absent();
1588 if (ethernet.getPayload() == null) {
1589 return srcIpAddress;
1591 byte[] ipAddrBytes = null;
1592 if (ethernet.getPayload() instanceof IPv4) {
1593 IPv4 ipv4 = (IPv4) ethernet.getPayload();
1594 ipAddrBytes = Ints.toByteArray(ipv4.getSourceAddress());
1595 } else if (ethernet.getPayload() instanceof ARP) {
1596 ipAddrBytes = ((ARP) ethernet.getPayload()).getSenderProtocolAddress();
1598 if (ipAddrBytes != null) {
1599 String ipAddr = NWUtil.toStringIpAddress(ipAddrBytes);
1600 return Optional.of(IpAddressBuilder.getDefaultInstance(ipAddr));
1602 return srcIpAddress;
1605 public List<MacEntry> getElanMacEntries(String elanName) {
1606 MacTable macTable = getElanMacTable(elanName);
1607 if (macTable == null) {
1610 return macTable.getMacEntry();
1613 public boolean isTunnelInLogicalGroup(String interfaceName) {
1614 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1615 .ietf.interfaces.rev140508.interfaces.Interface configIface =
1616 interfaceManager.getInterfaceInfoFromConfigDataStore(interfaceName);
1617 if (configIface == null) {
1618 configIface = iitmProvider.getInterface(interfaceName);
1620 if (configIface == null) {
1623 IfTunnel ifTunnel = configIface.augmentation(IfTunnel.class);
1624 if (ifTunnel != null && ifTunnel.getTunnelInterfaceType().isAssignableFrom(TunnelTypeVxlan.class)) {
1625 ParentRefs refs = configIface.augmentation(ParentRefs.class);
1626 return refs != null && !Strings.isNullOrEmpty(refs.getParentInterface());
1631 public static InstanceIdentifier<Flow> getFlowIid(Flow flow, Uint64 dpnId) {
1632 FlowKey flowKey = new FlowKey(new FlowId(flow.getId()));
1633 org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId nodeId =
1634 new org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId("openflow:" + dpnId);
1635 org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node nodeDpn =
1636 new NodeBuilder().setId(nodeId).withKey(new NodeKey(nodeId)).build();
1637 return InstanceIdentifier.builder(Nodes.class)
1638 .child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node.class,
1639 nodeDpn.key()).augmentation(FlowCapableNode.class)
1640 .child(Table.class, new TableKey(flow.getTableId())).child(Flow.class, flowKey).build();
1643 public static String getElanInterfaceJobKey(String interfaceName) {
1644 return "elaninterface-" + interfaceName;
1647 public void removeArpResponderFlow(Uint64 dpnId, String ingressInterfaceName, String ipAddress,
1649 LOG.info("Removing the ARP responder flow on DPN {} of Interface {} with IP {}", dpnId, ingressInterfaceName,
1651 LoggingFutures.addErrorLogging(txRunner.callWithNewReadWriteTransactionAndSubmit(Datastore.CONFIGURATION,
1652 tx -> mdsalManager.removeFlow(tx, dpnId, ArpResponderUtil.getFlowId(lportTag, ipAddress),
1653 NwConstants.ARP_RESPONDER_TABLE)), LOG, "Error removing ARP responder flow");
1657 public static String getRouterPordIdFromElanInstance(DataBroker dataBroker, String elanInstanceName) {
1658 Optional<Subnetmaps> subnetMapsData =
1659 read(dataBroker, LogicalDatastoreType.CONFIGURATION, buildSubnetMapsWildCardPath());
1660 if (subnetMapsData.isPresent()) {
1661 List<Subnetmap> subnetMapList = subnetMapsData.get().getSubnetmap();
1662 if (subnetMapList != null && !subnetMapList.isEmpty()) {
1663 for (Subnetmap subnet : subnetMapList) {
1664 if (subnet.getNetworkId().getValue().equals(elanInstanceName)) {
1665 if (subnet.getRouterInterfacePortId() != null) {
1666 return subnet.getRouterInterfacePortId().getValue();
1675 protected Node buildDpnNode(Uint64 dpnId) {
1676 org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId nodeId =
1677 new org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819
1678 .NodeId("openflow:" + dpnId);
1679 Node nodeDpn = new NodeBuilder().setId(nodeId).withKey(new NodeKey(nodeId)).build();
1683 public void syncUpdateGroup(Uint64 dpnId, Group newGroup, long delayTime,
1684 TypedWriteTransaction<Datastore.Configuration> confTx) {
1685 Node nodeDpn = buildDpnNode(dpnId);
1686 long groupIdInfo = newGroup.getGroupId().getValue().toJava();
1687 GroupKey groupKey = new GroupKey(new GroupId(groupIdInfo));
1688 InstanceIdentifier<Group> groupInstanceId = InstanceIdentifier.builder(Nodes.class)
1689 .child(Node.class, nodeDpn.key()).augmentation(FlowCapableNode.class)
1690 .child(Group.class, groupKey).build();
1691 LOG.trace("Performing merge operation for remote BC group for node {} with group {}", nodeDpn, newGroup);
1692 Optional<Group> existingGroupOpt = ElanUtils.read(broker, LogicalDatastoreType.CONFIGURATION, groupInstanceId);
1693 if (!existingGroupOpt.isPresent()) {
1694 LOG.debug("Group {} doesn't exist. Performing syncInstall", groupIdInfo);
1695 mdsalManager.addGroup(confTx, dpnId, newGroup);
1698 Buckets existingGroup = existingGroupOpt.get().getBuckets();
1699 if (existingGroup == null) {
1700 LOG.debug("Bucket doesn't exist for group {}. Performing syncInstall", groupIdInfo);
1701 mdsalManager.addGroup(confTx, dpnId, newGroup);
1704 if (newGroup.getBuckets() == null) {
1705 LOG.debug("Buckets are not sent for group {}. Skipping merge operation", groupIdInfo);
1708 List<Bucket> newBuckets = newGroup.getBuckets().getBucket();
1709 List<Bucket> existingBuckets = existingGroup.getBucket();
1710 Set<Bucket> toMergeBucketsWithoutId = new LinkedHashSet<>();
1712 existingBuckets.stream()
1713 .map(TO_BUCKET_WITHOUT_ID)
1714 .forEach(bucketWithoutId -> toMergeBucketsWithoutId.add(bucketWithoutId));
1717 .map(TO_BUCKET_WITHOUT_ID)
1718 .forEach(bucketWithoutId -> toMergeBucketsWithoutId.add(bucketWithoutId));
1720 if (toMergeBucketsWithoutId.size() == existingBuckets.size()) {
1721 //no new buckets got added
1722 //size matched and no extra buckets in existing buckets , rewrite the group
1723 LOG.debug("Buckets did not change group {}. Skipping merge operation", groupIdInfo);
1726 LOG.debug("Old group buckets size {} New group buckets size {} Dpn id {} Group id {} ",
1727 existingBuckets.size(), toMergeBucketsWithoutId.size(), dpnId, groupIdInfo);
1728 AtomicLong bucketIdValue = new AtomicLong(-1);
1729 //Change the bucket id of existing buckets
1730 List<Bucket> bucketsToBeAdded = toMergeBucketsWithoutId.stream()
1731 .map(bucketWithoutId -> TO_BUCKET_WITH_ID.apply(bucketWithoutId, bucketIdValue))
1732 .collect(Collectors.toList());
1734 Group group = MDSALUtil.buildGroup(newGroup.getGroupId().getValue().toJava(), newGroup.getGroupName(),
1735 GroupTypes.GroupAll, MDSALUtil.buildBucketLists(bucketsToBeAdded));
1736 mdsalManager.addGroup(confTx, dpnId, group);
1737 LOG.trace("Installed remote BC group for node {} with group {}", nodeDpn, group);
1740 static InstanceIdentifier<Subnetmaps> buildSubnetMapsWildCardPath() {
1741 return InstanceIdentifier.create(Subnetmaps.class);
1744 public static InstanceIdentifier<Group> getGroupInstanceid(Uint64 dpnId, long groupId) {
1745 return InstanceIdentifier.builder(Nodes.class).child(Node.class, new NodeKey(new NodeId("openflow:" + dpnId)))
1746 .augmentation(FlowCapableNode.class).child(Group.class, new GroupKey(new GroupId(groupId))).build();
1749 public static String getBcGroupUpdateKey(String elanName) {
1750 return "bc.group.update." + elanName;