avoid race in elan bc group update
[netvirt.git] / elanmanager / impl / src / main / java / org / opendaylight / netvirt / elan / utils / ElanUtils.java
1 /*
2  * Copyright © 2016, 2017 Ericsson India Global Services Pvt Ltd. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.netvirt.elan.utils;
9
10 import com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Strings;
13 import com.google.common.collect.Lists;
14 import com.google.common.primitives.Ints;
15 import com.google.common.util.concurrent.CheckedFuture;
16 import com.google.common.util.concurrent.FutureCallback;
17 import com.google.common.util.concurrent.Futures;
18 import com.google.common.util.concurrent.ListenableFuture;
19 import com.google.common.util.concurrent.MoreExecutors;
20 import java.math.BigInteger;
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.Collections;
24 import java.util.List;
25 import java.util.concurrent.ExecutionException;
26 import java.util.concurrent.Future;
27 import javax.annotation.Nonnull;
28 import javax.annotation.Nullable;
29 import javax.inject.Inject;
30 import javax.inject.Singleton;
31 import org.apache.commons.lang3.StringUtils;
32 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
33 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
34 import org.opendaylight.controller.md.sal.binding.api.ReadTransaction;
35 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
36 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
37 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
38 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
39 import org.opendaylight.genius.infra.ManagedNewTransactionRunner;
40 import org.opendaylight.genius.infra.ManagedNewTransactionRunnerImpl;
41 import org.opendaylight.genius.interfacemanager.globals.InterfaceInfo;
42 import org.opendaylight.genius.interfacemanager.globals.InterfaceServiceUtil;
43 import org.opendaylight.genius.interfacemanager.interfaces.IInterfaceManager;
44 import org.opendaylight.genius.itm.globals.ITMConstants;
45 import org.opendaylight.genius.mdsalutil.ActionInfo;
46 import org.opendaylight.genius.mdsalutil.FlowEntity;
47 import org.opendaylight.genius.mdsalutil.FlowEntityBuilder;
48 import org.opendaylight.genius.mdsalutil.InstructionInfo;
49 import org.opendaylight.genius.mdsalutil.MDSALUtil;
50 import org.opendaylight.genius.mdsalutil.MatchInfo;
51 import org.opendaylight.genius.mdsalutil.MetaDataUtil;
52 import org.opendaylight.genius.mdsalutil.NWUtil;
53 import org.opendaylight.genius.mdsalutil.NwConstants;
54 import org.opendaylight.genius.mdsalutil.actions.ActionNxResubmit;
55 import org.opendaylight.genius.mdsalutil.instructions.InstructionApplyActions;
56 import org.opendaylight.genius.mdsalutil.instructions.InstructionGotoTable;
57 import org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager;
58 import org.opendaylight.genius.mdsalutil.matches.MatchEthernetDestination;
59 import org.opendaylight.genius.mdsalutil.matches.MatchEthernetSource;
60 import org.opendaylight.genius.mdsalutil.matches.MatchMetadata;
61 import org.opendaylight.genius.mdsalutil.matches.MatchTunnelId;
62 import org.opendaylight.genius.mdsalutil.packet.ARP;
63 import org.opendaylight.genius.mdsalutil.packet.Ethernet;
64 import org.opendaylight.genius.mdsalutil.packet.IPv4;
65 import org.opendaylight.infrautils.utils.concurrent.JdkFutures;
66 import org.opendaylight.infrautils.utils.concurrent.ListenableFutures;
67 import org.opendaylight.netvirt.elan.ElanException;
68 import org.opendaylight.netvirt.elan.arp.responder.ArpResponderUtil;
69 import org.opendaylight.netvirt.elan.cache.ElanInterfaceCache;
70 import org.opendaylight.netvirt.elanmanager.api.ElanHelper;
71 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
72 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddressBuilder;
73 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfacesState;
74 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface;
75 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.AdminStatus;
76 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.OperStatus;
77 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
78 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.PhysAddress;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInput;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInputBuilder;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdOutput;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdManagerService;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInput;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInputBuilder;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406.IfIndexesInterfaceMap;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._if.indexes._interface.map.IfIndexInterface;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._if.indexes._interface.map.IfIndexInterfaceKey;
96 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfTunnel;
97 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.ParentRefs;
98 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeBase;
99 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeVxlan;
100 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceInput;
101 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceInputBuilder;
102 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceOutput;
103 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.OdlInterfaceRpcService;
104 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceBindings;
105 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceModeIngress;
106 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceTypeFlowBased;
107 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflow;
108 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflowBuilder;
109 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.ServicesInfo;
110 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.ServicesInfoKey;
111 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServices;
112 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesBuilder;
113 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesKey;
114 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.ExternalTunnelList;
115 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnel;
116 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnelKey;
117 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.ItmRpcService;
118 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsInput;
119 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsInputBuilder;
120 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
121 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
122 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
123 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
124 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
125 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.config.rev150710.ElanConfig;
126 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInstance;
127 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInstanceBuilder;
128 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInterface;
129 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInterface.EtreeInterfaceType;
130 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTag;
131 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTagName;
132 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTagNameBuilder;
133 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanDpnInterfaces;
134 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanForwardingTables;
135 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInstances;
136 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaceForwardingEntries;
137 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaces;
138 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanState;
139 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanTagNameMap;
140 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeFlat;
141 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeVlan;
142 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeVxlan;
143 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan._interface.forwarding.entries.ElanInterfaceMac;
144 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan._interface.forwarding.entries.ElanInterfaceMacKey;
145 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesList;
146 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesListKey;
147 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfaces;
148 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfacesKey;
149 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTable;
150 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTableBuilder;
151 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTableKey;
152 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstance;
153 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstanceBuilder;
154 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.elan.instance.ElanSegments;
155 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterface;
156 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterfaceKey;
157 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntries;
158 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntriesBuilder;
159 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntriesKey;
160 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.Elan;
161 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.ElanBuilder;
162 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.ElanKey;
163 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagName;
164 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagNameBuilder;
165 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagNameKey;
166 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntry;
167 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntryKey;
168 import org.opendaylight.yangtools.yang.binding.DataObject;
169 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
170 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.InstanceIdentifierBuilder;
171 import org.opendaylight.yangtools.yang.common.RpcResult;
172 import org.slf4j.Logger;
173 import org.slf4j.LoggerFactory;
174
175 @Singleton
176 public class ElanUtils {
177
178     private static final Logger LOG = LoggerFactory.getLogger(ElanUtils.class);
179
180     private final DataBroker broker;
181     private final ManagedNewTransactionRunner txRunner;
182     private final IMdsalApiManager mdsalManager;
183     private final OdlInterfaceRpcService interfaceManagerRpcService;
184     private final ItmRpcService itmRpcService;
185     private final IInterfaceManager interfaceManager;
186     private final ElanConfig elanConfig;
187     private final ElanItmUtils elanItmUtils;
188     private final ElanEtreeUtils elanEtreeUtils;
189     private final ElanInterfaceCache elanInterfaceCache;
190
191     public static final FutureCallback<Void> DEFAULT_CALLBACK = new FutureCallback<Void>() {
192         @Override
193         public void onSuccess(Void result) {
194             LOG.debug("Success in Datastore operation");
195         }
196
197         @Override
198         public void onFailure(Throwable error) {
199             LOG.error("Error in Datastore operation", error);
200         }
201     };
202
203     @Inject
204     public ElanUtils(DataBroker dataBroker, IMdsalApiManager mdsalManager,
205             OdlInterfaceRpcService interfaceManagerRpcService, ItmRpcService itmRpcService, ElanConfig elanConfig,
206             IInterfaceManager interfaceManager, ElanEtreeUtils elanEtreeUtils, ElanItmUtils elanItmUtils,
207             ElanInterfaceCache elanInterfaceCache) {
208         this.broker = dataBroker;
209         this.txRunner = new ManagedNewTransactionRunnerImpl(dataBroker);
210         this.mdsalManager = mdsalManager;
211         this.interfaceManagerRpcService = interfaceManagerRpcService;
212         this.itmRpcService = itmRpcService;
213         this.interfaceManager = interfaceManager;
214         this.elanConfig = elanConfig;
215         this.elanEtreeUtils = elanEtreeUtils;
216         this.elanItmUtils = elanItmUtils;
217         this.elanInterfaceCache = elanInterfaceCache;
218     }
219
220     public final Boolean isOpenstackVniSemanticsEnforced() {
221         return elanConfig.isOpenstackVniSemanticsEnforced() != null
222                 ? elanConfig.isOpenstackVniSemanticsEnforced() : false;
223     }
224
225     /**
226      * Uses the IdManager to retrieve a brand new ElanTag.
227      *
228      * @param idManager
229      *            the id manager
230      * @param idKey
231      *            the id key
232      * @return the integer
233      */
234     public static Long retrieveNewElanTag(IdManagerService idManager, String idKey) {
235
236         AllocateIdInput getIdInput = new AllocateIdInputBuilder().setPoolName(ElanConstants.ELAN_ID_POOL_NAME)
237                 .setIdKey(idKey).build();
238
239         try {
240             Future<RpcResult<AllocateIdOutput>> result = idManager.allocateId(getIdInput);
241             RpcResult<AllocateIdOutput> rpcResult = result.get();
242             if (rpcResult.isSuccessful()) {
243                 return rpcResult.getResult().getIdValue();
244             } else {
245                 LOG.warn("RPC Call to Allocate Id returned with Errors {}", rpcResult.getErrors());
246             }
247         } catch (InterruptedException | ExecutionException e) {
248             LOG.warn("Exception when Allocating Id", e);
249         }
250         return 0L;
251     }
252
253     public static void releaseId(IdManagerService idManager, String poolName, String idKey) {
254         ReleaseIdInput releaseIdInput = new ReleaseIdInputBuilder().setPoolName(poolName).setIdKey(idKey).build();
255         JdkFutures.addErrorLogging(idManager.releaseId(releaseIdInput), LOG, "Release Id");
256     }
257
258     /**
259      * Read utility.
260      *
261      * @deprecated Consider using {@link #read2(LogicalDatastoreType, InstanceIdentifier)} with proper exception
262      *             handling instead
263      * @param broker dataBroker
264      * @param datastoreType Logical DataStore type
265      * @param path IID to read
266      * @param <T> T extends DataObject
267      * @return the read value T
268      */
269     @Deprecated
270     @SuppressWarnings("checkstyle:IllegalCatch")
271     public static <T extends DataObject> Optional<T> read(@Nonnull DataBroker broker,
272             LogicalDatastoreType datastoreType, InstanceIdentifier<T> path) {
273         try (ReadOnlyTransaction tx = broker.newReadOnlyTransaction()) {
274             return tx.read(datastoreType, path).get();
275         } catch (Exception e) {
276             throw new RuntimeException(e);
277         }
278     }
279
280     public <T extends DataObject> Optional<T> read2(LogicalDatastoreType datastoreType, InstanceIdentifier<T> path)
281             throws ReadFailedException {
282         try (ReadOnlyTransaction tx = broker.newReadOnlyTransaction()) {
283             CheckedFuture<Optional<T>, ReadFailedException> checkedFuture = tx.read(datastoreType, path);
284             return checkedFuture.checkedGet();
285         }
286     }
287
288     public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
289             InstanceIdentifier<T> path) {
290         WriteTransaction tx = broker.newWriteOnlyTransaction();
291         tx.delete(datastoreType, path);
292         Futures.addCallback(tx.submit(), DEFAULT_CALLBACK, MoreExecutors.directExecutor());
293     }
294
295     public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
296             InstanceIdentifier<T> path, FutureCallback<Void> callback) {
297         WriteTransaction tx = broker.newWriteOnlyTransaction();
298         tx.delete(datastoreType, path);
299         Futures.addCallback(tx.submit(), callback, MoreExecutors.directExecutor());
300     }
301
302     public static InstanceIdentifier<ElanInstance> getElanInstanceIdentifier() {
303         return InstanceIdentifier.builder(ElanInstances.class).child(ElanInstance.class).build();
304     }
305
306     public static InstanceIdentifier<ElanInterface> getElanInterfaceConfigurationDataPathId(String interfaceName) {
307         return InstanceIdentifier.builder(ElanInterfaces.class)
308                 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).build();
309     }
310
311     // elan-state Operational container
312     public static Elan getElanByName(DataBroker broker, String elanInstanceName) {
313         InstanceIdentifier<Elan> elanIdentifier = getElanInstanceOperationalDataPath(elanInstanceName);
314         return MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL, elanIdentifier).orNull();
315     }
316
317     @Nullable
318     public static Elan getElanByName(ReadTransaction tx, String elanInstanceName) throws ReadFailedException {
319         return tx.read(LogicalDatastoreType.OPERATIONAL,
320                 getElanInstanceOperationalDataPath(elanInstanceName)).checkedGet().orNull();
321     }
322
323     public static InstanceIdentifier<Elan> getElanInstanceOperationalDataPath(String elanInstanceName) {
324         return InstanceIdentifier.builder(ElanState.class).child(Elan.class, new ElanKey(elanInstanceName)).build();
325     }
326
327     // grouping of forwarding-entries
328     public MacEntry getInterfaceMacEntriesOperationalDataPath(String interfaceName, PhysAddress physAddress) {
329         InstanceIdentifier<MacEntry> existingMacEntryId = getInterfaceMacEntriesIdentifierOperationalDataPath(
330                 interfaceName, physAddress);
331         return read(broker, LogicalDatastoreType.OPERATIONAL, existingMacEntryId).orNull();
332     }
333
334     public MacEntry getInterfaceMacEntriesOperationalDataPathFromId(InstanceIdentifier identifier) {
335         Optional<MacEntry> existingInterfaceMacEntry = read(broker,
336                 LogicalDatastoreType.OPERATIONAL, identifier);
337         return existingInterfaceMacEntry.orNull();
338     }
339
340     public static InstanceIdentifier<MacEntry> getInterfaceMacEntriesIdentifierOperationalDataPath(String interfaceName,
341             PhysAddress physAddress) {
342         return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class)
343                 .child(ElanInterfaceMac.class, new ElanInterfaceMacKey(interfaceName))
344                 .child(MacEntry.class, new MacEntryKey(physAddress)).build();
345
346     }
347
348     // elan-forwarding-tables Operational container
349     public Optional<MacEntry> getMacEntryForElanInstance(String elanName, PhysAddress physAddress) {
350         InstanceIdentifier<MacEntry> macId = getMacEntryOperationalDataPath(elanName, physAddress);
351         return read(broker, LogicalDatastoreType.OPERATIONAL, macId);
352     }
353
354     public Optional<MacEntry> getMacEntryForElanInstance(ReadTransaction tx, String elanName, PhysAddress physAddress)
355             throws ReadFailedException {
356         InstanceIdentifier<MacEntry> macId = getMacEntryOperationalDataPath(elanName, physAddress);
357         return tx.read(LogicalDatastoreType.OPERATIONAL, macId).checkedGet();
358     }
359
360     public MacEntry getMacEntryFromElanMacId(InstanceIdentifier identifier) {
361         Optional<MacEntry> existingInterfaceMacEntry = read(broker,
362                 LogicalDatastoreType.OPERATIONAL, identifier);
363         return existingInterfaceMacEntry.orNull();
364     }
365
366     public static InstanceIdentifier<MacEntry> getMacEntryOperationalDataPath(String elanName,
367             PhysAddress physAddress) {
368         return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class, new MacTableKey(elanName))
369                 .child(MacEntry.class, new MacEntryKey(physAddress)).build();
370     }
371
372     public static InstanceIdentifier<MacTable> getElanMacTableOperationalDataPath(String elanName) {
373         return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class, new MacTableKey(elanName))
374                 .build();
375     }
376
377     // elan-interface-forwarding-entries Operational container
378     public ElanInterfaceMac getElanInterfaceMacByInterfaceName(String interfaceName) {
379         return getElanInterfaceMacByInterfaceName(broker, interfaceName);
380     }
381
382     @Nullable
383     public static ElanInterfaceMac getElanInterfaceMacByInterfaceName(DataBroker dataBroker, String interfaceName) {
384         InstanceIdentifier<ElanInterfaceMac> elanInterfaceId = getElanInterfaceMacEntriesOperationalDataPath(
385                 interfaceName);
386         return read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanInterfaceId).orNull();
387     }
388
389     /**
390      * Gets the elan interface mac addresses.
391      *
392      * @param interfaceName
393      *            the interface name
394      * @return the elan interface mac addresses
395      */
396     public List<PhysAddress> getElanInterfaceMacAddresses(String interfaceName) {
397         List<PhysAddress> macAddresses = new ArrayList<>();
398         ElanInterfaceMac elanInterfaceMac = getElanInterfaceMacByInterfaceName(interfaceName);
399         if (elanInterfaceMac != null && elanInterfaceMac.getMacEntry() != null) {
400             List<MacEntry> macEntries = elanInterfaceMac.getMacEntry();
401             for (MacEntry macEntry : macEntries) {
402                 macAddresses.add(macEntry.getMacAddress());
403             }
404         }
405         return macAddresses;
406     }
407
408     public static InstanceIdentifier<ElanInterfaceMac> getElanInterfaceMacEntriesOperationalDataPath(
409             String interfaceName) {
410         return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class)
411                 .child(ElanInterfaceMac.class, new ElanInterfaceMacKey(interfaceName)).build();
412     }
413
414     /**
415      * Returns the list of Interfaces that belong to an Elan on an specific DPN.
416      * Data retrieved from Elan's operational DS: elan-dpn-interfaces container
417      *
418      * @param elanInstanceName
419      *            name of the Elan to which the interfaces must belong to
420      * @param dpId
421      *            Id of the DPN where the interfaces are located
422      * @return the elan interface Info
423      */
424     public DpnInterfaces getElanInterfaceInfoByElanDpn(String elanInstanceName, BigInteger dpId) {
425         InstanceIdentifier<DpnInterfaces> elanDpnInterfacesId = getElanDpnInterfaceOperationalDataPath(elanInstanceName,
426                 dpId);
427         return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfacesId).orNull();
428     }
429
430     /**
431      * Returns the InstanceIdentifier that points to the Interfaces of an Elan
432      * in a given DPN in the Operational DS. Data retrieved from Elans's
433      * operational DS: dpn-interfaces list
434      *
435      * @param elanInstanceName
436      *            name of the Elan to which the interfaces must belong to
437      * @param dpId
438      *            Id of the DPN where the interfaces are located
439      * @return the elan dpn interface
440      */
441     public static InstanceIdentifier<DpnInterfaces> getElanDpnInterfaceOperationalDataPath(String elanInstanceName,
442             BigInteger dpId) {
443         return InstanceIdentifier.builder(ElanDpnInterfaces.class)
444                 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName))
445                 .child(DpnInterfaces.class, new DpnInterfacesKey(dpId)).build();
446     }
447
448     // elan-tag-name-map Operational Container
449     public ElanTagName getElanInfoByElanTag(long elanTag) {
450         InstanceIdentifier<ElanTagName> elanId = getElanInfoEntriesOperationalDataPath(elanTag);
451         Optional<ElanTagName> existingElanInfo = read(broker,
452                 LogicalDatastoreType.OPERATIONAL, elanId);
453         return existingElanInfo.orNull();
454     }
455
456     public static InstanceIdentifier<ElanTagName> getElanInfoEntriesOperationalDataPath(long elanTag) {
457         return InstanceIdentifier.builder(ElanTagNameMap.class).child(ElanTagName.class, new ElanTagNameKey(elanTag))
458                 .build();
459     }
460
461     // interface-index-tag operational container
462     public Optional<IfIndexInterface> getInterfaceInfoByInterfaceTag(long interfaceTag) {
463         InstanceIdentifier<IfIndexInterface> interfaceId = getInterfaceInfoEntriesOperationalDataPath(interfaceTag);
464         return read(broker, LogicalDatastoreType.OPERATIONAL, interfaceId);
465     }
466
467     public static InstanceIdentifier<IfIndexInterface> getInterfaceInfoEntriesOperationalDataPath(long interfaceTag) {
468         return InstanceIdentifier.builder(IfIndexesInterfaceMap.class)
469                 .child(IfIndexInterface.class, new IfIndexInterfaceKey((int) interfaceTag)).build();
470     }
471
472     public static InstanceIdentifier<ElanDpnInterfacesList> getElanDpnOperationDataPath(String elanInstanceName) {
473         return InstanceIdentifier.builder(ElanDpnInterfaces.class)
474                 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName)).build();
475     }
476
477     public ElanDpnInterfacesList getElanDpnInterfacesList(String elanName) {
478         InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanName);
479         return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orNull();
480     }
481
482     public ElanDpnInterfaces getElanDpnInterfacesList() {
483         InstanceIdentifier<ElanDpnInterfaces> elanDpnInterfaceId = InstanceIdentifier.builder(ElanDpnInterfaces.class)
484                 .build();
485         return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orNull();
486     }
487
488     /**
489      * This method is useful get all ELAN participating CSS dpIds to install
490      * program remote dmac entries and updating remote bc groups for tor
491      * integration.
492      *
493      * @param elanInstanceName
494      *            the elan instance name
495      * @return list of dpIds
496      */
497     @Nonnull
498     public List<BigInteger> getParticipatingDpnsInElanInstance(String elanInstanceName) {
499         List<BigInteger> dpIds = new ArrayList<>();
500         InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
501         Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = read(broker,
502                 LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
503         if (!existingElanDpnInterfaces.isPresent()) {
504             return dpIds;
505         }
506         List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().getDpnInterfaces();
507         for (DpnInterfaces dpnInterface : dpnInterfaces) {
508             dpIds.add(dpnInterface.getDpId());
509         }
510         return dpIds;
511     }
512
513     /**
514      * To check given dpId is already present in Elan instance. This can be used
515      * to program flow entry in external tunnel table when a new access port
516      * added for first time into the ELAN instance
517      *
518      * @param dpId
519      *            the dp id
520      * @param elanInstanceName
521      *            the elan instance name
522      * @return true if dpId is already present, otherwise return false
523      */
524     public boolean isDpnAlreadyPresentInElanInstance(BigInteger dpId, String elanInstanceName) {
525         InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
526         Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = read(broker,
527                 LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
528         if (!existingElanDpnInterfaces.isPresent()) {
529             return false;
530         }
531         List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().getDpnInterfaces();
532         for (DpnInterfaces dpnInterface : dpnInterfaces) {
533             if (dpnInterface.getDpId().equals(dpId)) {
534                 return true;
535             }
536         }
537         return false;
538     }
539
540     public ElanForwardingTables getElanForwardingList() {
541         InstanceIdentifier<ElanForwardingTables> elanForwardingTableId = InstanceIdentifier
542                 .builder(ElanForwardingTables.class).build();
543         return read(broker, LogicalDatastoreType.OPERATIONAL, elanForwardingTableId).orNull();
544     }
545
546     public static long getElanRemoteBroadCastGroupID(long elanTag) {
547         return ElanConstants.ELAN_GID_MIN + elanTag % ElanConstants.ELAN_GID_MIN * 2;
548     }
549
550     /**
551      * Gets the elan mac table.
552      *
553      * @param elanName
554      *            the elan name
555      * @return the elan mac table
556      */
557     public MacTable getElanMacTable(String elanName) {
558         return getElanMacTable(broker, elanName);
559     }
560
561     @Nullable
562     public static MacTable getElanMacTable(DataBroker dataBroker, String elanName) {
563         InstanceIdentifier<MacTable> elanMacTableId = getElanMacTableOperationalDataPath(elanName);
564         return read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanMacTableId).orNull();
565     }
566
567     public static long getElanLocalBCGId(long elanTag) {
568         return ElanConstants.ELAN_GID_MIN + (elanTag % ElanConstants.ELAN_GID_MIN * 2 - 1);
569     }
570
571     public static long getElanRemoteBCGId(long elanTag) {
572         return ElanConstants.ELAN_GID_MIN + elanTag % ElanConstants.ELAN_GID_MIN * 2;
573     }
574
575     public static long getEtreeLeafLocalBCGId(long etreeLeafTag) {
576         return ElanConstants.ELAN_GID_MIN + (etreeLeafTag % ElanConstants.ELAN_GID_MIN * 2 - 1);
577     }
578
579     public static long getEtreeLeafRemoteBCGId(long etreeLeafTag) {
580         return ElanConstants.ELAN_GID_MIN + etreeLeafTag % ElanConstants.ELAN_GID_MIN * 2;
581     }
582
583     public static BigInteger getElanMetadataLabel(long elanTag, boolean isSHFlagSet) {
584         int shBit = isSHFlagSet ? 1 : 0;
585         return BigInteger.valueOf(elanTag).shiftLeft(24).or(BigInteger.valueOf(shBit));
586     }
587
588     /**
589      * Setting SMAC, DMAC, UDMAC in this DPN and optionally in other DPNs.
590      *
591      * @param elanInfo
592      *            the elan info
593      * @param interfaceInfo
594      *            the interface info
595      * @param macTimeout
596      *            the mac timeout
597      * @param macAddress
598      *            the mac address
599      * @param configureRemoteFlows
600      *            true if remote dmac flows should be configured as well
601      * @param writeFlowGroupTx
602      *            the flow group tx
603      * @throws ElanException in case of issues creating the flow objects
604      */
605     public void setupMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo,
606                               long macTimeout, String macAddress, boolean configureRemoteFlows,
607                               WriteTransaction writeFlowGroupTx) throws ElanException {
608         synchronized (getElanMacDPNKey(elanInfo.getElanTag(), macAddress, interfaceInfo.getDpId())) {
609             setupKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress, mdsalManager,
610                 writeFlowGroupTx);
611             setupOrigDmacFlows(elanInfo, interfaceInfo, macAddress, configureRemoteFlows, mdsalManager,
612                     writeFlowGroupTx);
613         }
614     }
615
616     public void setupDMacFlowOnRemoteDpn(ElanInstance elanInfo, InterfaceInfo interfaceInfo, BigInteger dstDpId,
617                                          String macAddress, WriteTransaction writeFlowTx) throws ElanException {
618         String elanInstanceName = elanInfo.getElanInstanceName();
619         setupRemoteDmacFlow(dstDpId, interfaceInfo.getDpId(), interfaceInfo.getInterfaceTag(), elanInfo.getElanTag(),
620                 macAddress, elanInstanceName, writeFlowTx, interfaceInfo.getInterfaceName(), elanInfo);
621         LOG.info("Remote Dmac flow entry created for elan Name:{}, logical port Name:{} and"
622                 + " mac address {} on dpn:{}", elanInstanceName, interfaceInfo.getPortName(),
623                 macAddress, dstDpId);
624     }
625
626     /**
627      * Inserts a Flow in SMAC table to state that the MAC has already been
628      * learnt.
629      */
630     private void setupKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
631             String macAddress, IMdsalApiManager mdsalApiManager, WriteTransaction writeFlowGroupTx) {
632         FlowEntity flowEntity = buildKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress);
633         mdsalApiManager.addFlowToTx(flowEntity, writeFlowGroupTx);
634         LOG.debug("Known Smac flow entry created for elan Name:{}, logical Interface port:{} and mac address:{}",
635                 elanInfo.getElanInstanceName(), elanInfo.getDescription(), macAddress);
636     }
637
638     public FlowEntity buildKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
639             String macAddress) {
640         int lportTag = interfaceInfo.getInterfaceTag();
641         // Matching metadata and eth_src fields
642         List<MatchInfo> mkMatches = new ArrayList<>();
643         mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanInfo.getElanTag(), lportTag),
644                 ElanHelper.getElanMetadataMask()));
645         mkMatches.add(new MatchEthernetSource(new MacAddress(macAddress)));
646         List<InstructionInfo> mkInstructions = new ArrayList<>();
647         mkInstructions.add(new InstructionGotoTable(NwConstants.ELAN_DMAC_TABLE));
648         BigInteger dpId = interfaceInfo.getDpId();
649         long elanTag = getElanTag(elanInfo, interfaceInfo);
650         return new FlowEntityBuilder()
651             .setDpnId(dpId)
652             .setTableId(NwConstants.ELAN_SMAC_TABLE)
653             .setFlowId(getKnownDynamicmacFlowRef(NwConstants.ELAN_SMAC_TABLE, dpId, lportTag, macAddress, elanTag))
654             .setPriority(20)
655             .setFlowName(elanInfo.getDescription())
656             .setIdleTimeOut((int) macTimeout)
657             .setHardTimeOut(0)
658             .setCookie(ElanConstants.COOKIE_ELAN_KNOWN_SMAC.add(BigInteger.valueOf(elanTag)))
659             .setMatchInfoList(mkMatches)
660             .setInstructionInfoList(mkInstructions)
661             .setStrictFlag(true)
662             // If Mac timeout is 0, the flow won't be deleted automatically, so no need to get notified
663             .setSendFlowRemFlag(macTimeout != 0)
664             .build();
665     }
666
667     private Long getElanTag(ElanInstance elanInfo, InterfaceInfo interfaceInfo) {
668         EtreeInterface etreeInterface = elanInterfaceCache.getEtreeInterface(interfaceInfo.getInterfaceName()).orNull();
669         if (etreeInterface == null || etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
670             return elanInfo.getElanTag();
671         } else { // Leaf
672             EtreeInstance etreeInstance = elanInfo.getAugmentation(EtreeInstance.class);
673             if (etreeInstance == null) {
674                 LOG.warn("EtreeInterface {} is connected to a non-Etree network: {}",
675                          interfaceInfo.getInterfaceName(), elanInfo.getElanInstanceName());
676                 return elanInfo.getElanTag();
677             } else {
678                 return etreeInstance.getEtreeLeafTagVal().getValue();
679             }
680         }
681     }
682
683     /**
684      * Installs a Flow in INTERNAL_TUNNEL_TABLE of the affected DPN that sends
685      * the packet through the specified interface if the tunnel_id matches the
686      * interface's lportTag.
687      *
688      * @param interfaceInfo
689      *            the interface info
690      * @param mdsalApiManager
691      *            the mdsal API manager
692      * @param writeFlowGroupTx
693      *            the writeFLowGroup tx
694      */
695     public void setupTermDmacFlows(InterfaceInfo interfaceInfo, IMdsalApiManager mdsalApiManager,
696                                    WriteTransaction writeFlowGroupTx) {
697         BigInteger dpId = interfaceInfo.getDpId();
698         int lportTag = interfaceInfo.getInterfaceTag();
699         Flow flow = MDSALUtil.buildFlowNew(NwConstants.INTERNAL_TUNNEL_TABLE,
700                 getIntTunnelTableFlowRef(NwConstants.INTERNAL_TUNNEL_TABLE, lportTag), 5,
701                 String.format("%s:%d", "ITM Flow Entry ", lportTag), 0, 0,
702                 ITMConstants.COOKIE_ITM.add(BigInteger.valueOf(lportTag)),
703                 getTunnelIdMatchForFilterEqualsLPortTag(lportTag),
704                 getInstructionsInPortForOutGroup(interfaceInfo.getInterfaceName()));
705         mdsalApiManager.addFlowToTx(dpId, flow, writeFlowGroupTx);
706         LOG.debug("Terminating service table flow entry created on dpn:{} for logical Interface port:{}", dpId,
707                 interfaceInfo.getPortName());
708     }
709
710     /**
711      * Constructs the FlowName for flows installed in the Internal Tunnel Table,
712      * consisting in tableId + elanTag.
713      *
714      * @param tableId
715      *            table Id
716      * @param elanTag
717      *            elan Tag
718      * @return the Internal tunnel
719      */
720     public static String getIntTunnelTableFlowRef(short tableId, int elanTag) {
721         return new StringBuffer().append(tableId).append(elanTag).toString();
722     }
723
724     /**
725      * Constructs the Matches that checks that the tunnel_id field contains a
726      * specific lportTag.
727      *
728      * @param lportTag
729      *            lportTag that must be checked against the tunnel_id field
730      * @return the list of match Info
731      */
732     public static List<MatchInfo> getTunnelIdMatchForFilterEqualsLPortTag(int lportTag) {
733         List<MatchInfo> mkMatches = new ArrayList<>();
734         // Matching metadata
735         mkMatches.add(new MatchTunnelId(BigInteger.valueOf(lportTag)));
736         return mkMatches;
737     }
738
739     /**
740      * Constructs the Instructions that take the packet over a given interface.
741      *
742      * @param ifName
743      *            Name of the interface where the packet must be sent over. It
744      *            can be a local interface or a tunnel interface (internal or
745      *            external)
746      * @return the Instruction
747      */
748     public List<Instruction> getInstructionsInPortForOutGroup(String ifName) {
749         List<Instruction> mkInstructions = new ArrayList<>();
750         List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
751
752         mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
753         return mkInstructions;
754     }
755
756     /**
757      * Returns the list of Actions to be taken when sending the packet through
758      * an Elan interface. Note that this interface can refer to an ElanInterface
759      * where the Elan VM is attached to a DPN or an ITM tunnel interface where
760      * Elan traffic can be sent through. In this latter case, the tunnelKey is
761      * mandatory and it can hold serviceId for internal tunnels or the VNI for
762      * external tunnels.
763      *
764      * @param ifName
765      *            the if name
766      * @param tunnelKey
767      *            the tunnel key
768      * @return the egress actions for interface
769      */
770     @SuppressWarnings("checkstyle:IllegalCatch")
771     public List<Action> getEgressActionsForInterface(String ifName, Long tunnelKey) {
772         List<Action> listAction = new ArrayList<>();
773         try {
774             GetEgressActionsForInterfaceInput getEgressActionInput = new GetEgressActionsForInterfaceInputBuilder()
775                     .setIntfName(ifName).setTunnelKey(tunnelKey).build();
776             Future<RpcResult<GetEgressActionsForInterfaceOutput>> result = interfaceManagerRpcService
777                     .getEgressActionsForInterface(getEgressActionInput);
778             RpcResult<GetEgressActionsForInterfaceOutput> rpcResult = result.get();
779             if (!rpcResult.isSuccessful()) {
780                 LOG.debug("RPC Call to Get egress actions for interface {} returned with Errors {}", ifName,
781                         rpcResult.getErrors());
782             } else {
783                 List<Action> actions = rpcResult.getResult().getAction();
784                 listAction = actions;
785             }
786         } catch (Exception e) {
787             LOG.warn("Exception when egress actions for interface {}", ifName, e);
788         }
789         return listAction;
790     }
791
792     private void setupOrigDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
793                                     boolean configureRemoteFlows, IMdsalApiManager mdsalApiManager,
794                                     WriteTransaction writeFlowGroupTx)
795                                     throws ElanException {
796         BigInteger dpId = interfaceInfo.getDpId();
797         String ifName = interfaceInfo.getInterfaceName();
798         long ifTag = interfaceInfo.getInterfaceTag();
799         String elanInstanceName = elanInfo.getElanInstanceName();
800
801         Long elanTag = elanInfo.getElanTag();
802
803         setupLocalDmacFlow(elanTag, dpId, ifName, macAddress, elanInfo, mdsalApiManager, ifTag,
804                 writeFlowGroupTx);
805         LOG.debug("Dmac flow entry created for elan Name:{}, logical port Name:{} mand mac address:{} "
806                                     + "on dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, dpId);
807
808         if (!configureRemoteFlows) {
809             return;
810         }
811
812         List<DpnInterfaces> elanDpns = getInvolvedDpnsInElan(elanInstanceName);
813         for (DpnInterfaces elanDpn : elanDpns) {
814
815             if (elanDpn.getDpId().equals(dpId)) {
816                 continue;
817             }
818
819             // Check for the Remote DPN present in Inventory Manager
820             if (!isDpnPresent(elanDpn.getDpId())) {
821                 continue;
822             }
823
824             // For remote DPNs a flow is needed to indicate that packets of this ELAN going to this MAC need to be
825             // forwarded through the appropriate ITM tunnel
826             setupRemoteDmacFlow(elanDpn.getDpId(), // srcDpn (the remote DPN in this case)
827                     dpId, // dstDpn (the local DPN)
828                     interfaceInfo.getInterfaceTag(), // lportTag of the local interface
829                     elanTag,  // identifier of the Elan
830                     macAddress, // MAC to be programmed in remote DPN
831                     elanInstanceName, writeFlowGroupTx, ifName, elanInfo
832             );
833             LOG.debug("Remote Dmac flow entry created for elan Name:{}, logical port Name:{} and mac address:{} on"
834                         + " dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, elanDpn.getDpId());
835         }
836
837         // TODO: Make sure that the same is performed against the ElanDevices.
838     }
839
840     @Nonnull
841     public List<DpnInterfaces> getInvolvedDpnsInElan(String elanName) {
842         return getElanDPNByName(elanName);
843     }
844
845     @Nonnull
846     public List<DpnInterfaces> getElanDPNByName(String elanInstanceName) {
847         InstanceIdentifier<ElanDpnInterfacesList> elanIdentifier = getElanDpnOperationDataPath(elanInstanceName);
848         return MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL, elanIdentifier).toJavaUtil().map(
849                 ElanDpnInterfacesList::getDpnInterfaces).orElse(Collections.emptyList());
850     }
851
852     private void setupLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
853             ElanInstance elanInfo, IMdsalApiManager mdsalApiManager, long ifTag, WriteTransaction writeFlowGroupTx) {
854         Flow flowEntity = buildLocalDmacFlowEntry(elanTag, dpId, ifName, macAddress, elanInfo, ifTag);
855         mdsalApiManager.addFlowToTx(dpId, flowEntity, writeFlowGroupTx);
856         installEtreeLocalDmacFlow(elanTag, dpId, ifName, macAddress, elanInfo,
857                 ifTag, writeFlowGroupTx);
858     }
859
860     private void installEtreeLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
861             ElanInstance elanInfo, long ifTag, WriteTransaction writeFlowGroupTx) {
862         EtreeInterface etreeInterface = elanInterfaceCache.getEtreeInterface(ifName).orNull();
863         if (etreeInterface != null && etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
864             EtreeLeafTagName etreeTagName = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
865             if (etreeTagName == null) {
866                 LOG.warn("Interface {} seems like it belongs to Etree but etreeTagName from elanTag {} is null",
867                         ifName, elanTag);
868             } else {
869                 Flow flowEntity = buildLocalDmacFlowEntry(etreeTagName.getEtreeLeafTag().getValue(), dpId, ifName,
870                         macAddress, elanInfo, ifTag);
871                 mdsalManager.addFlowToTx(dpId, flowEntity, writeFlowGroupTx);
872             }
873         }
874     }
875
876     public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, long lporTag, String macAddress,
877             long elanTag) {
878         return String.valueOf(tableId) + elanTag + dpId + lporTag + macAddress;
879     }
880
881     public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, BigInteger remoteDpId,
882             String macAddress, long elanTag) {
883         return String.valueOf(tableId) + elanTag + dpId + remoteDpId + macAddress;
884     }
885
886     public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, String macAddress, long elanTag) {
887         return String.valueOf(tableId) + elanTag + dpId + macAddress;
888     }
889
890     public static String getKnownDynamicmacFlowRef(short elanDmacTable, BigInteger dpId, String extDeviceNodeId,
891             String dstMacAddress, long elanTag, boolean shFlag) {
892         return String.valueOf(elanDmacTable) + elanTag + dpId + extDeviceNodeId + dstMacAddress + shFlag;
893     }
894
895     /**
896      * Builds the flow to be programmed in the DMAC table of the local DPN (that
897      * is, where the MAC is attached to). This flow consists in:
898      *
899      * <p>Match: + elanTag in metadata + packet goes to a MAC locally attached
900      * Actions: + optionally, pop-vlan + set-vlan-id + output to ifName's
901      * portNumber
902      *
903      * @param elanTag
904      *            the elan tag
905      * @param dpId
906      *            the dp id
907      * @param ifName
908      *            the if name
909      * @param macAddress
910      *            the mac address
911      * @param elanInfo
912      *            the elan info
913      * @param ifTag
914      *            the if tag
915      * @return the flow
916      */
917     public Flow buildLocalDmacFlowEntry(long elanTag, BigInteger dpId, String ifName, String macAddress,
918             ElanInstance elanInfo, long ifTag) {
919
920         List<MatchInfo> mkMatches = new ArrayList<>();
921         mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
922         mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddress)));
923
924         List<Instruction> mkInstructions = new ArrayList<>();
925         List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
926         mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
927         Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
928                 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, ifTag, macAddress, elanTag), 20,
929                 elanInfo.getElanInstanceName(), 0, 0, ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(
930                         BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
931
932         return flow;
933     }
934
935     public void setupRemoteDmacFlow(BigInteger srcDpId, BigInteger destDpId, int lportTag, long elanTag, String
936             macAddress, String displayName, WriteTransaction writeFlowGroupTx, String interfaceName, ElanInstance
937             elanInstance) throws ElanException {
938         if (interfaceManager.isExternalInterface(interfaceName)) {
939             LOG.debug("Ignoring install remote DMAC {} flow on provider interface {} elan {}",
940                     macAddress, interfaceName, elanInstance.getElanInstanceName());
941             return;
942         }
943         Flow flowEntity;
944         // if openstack-vni-semantics are enforced, segmentation ID is passed as network VNI for VxLAN based provider
945         // networks, 0 otherwise
946         long lportTagOrVni = !isOpenstackVniSemanticsEnforced() ? lportTag : isVxlanNetworkOrVxlanSegment(elanInstance)
947                 ? getVxlanSegmentationId(elanInstance) : 0;
948         flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTagOrVni, elanTag, macAddress, displayName,
949                 elanInstance);
950         mdsalManager.addFlowToTx(srcDpId, flowEntity, writeFlowGroupTx);
951         setupEtreeRemoteDmacFlow(srcDpId, destDpId, lportTagOrVni, elanTag, macAddress, displayName, interfaceName,
952                 writeFlowGroupTx, elanInstance);
953     }
954
955     private void setupEtreeRemoteDmacFlow(BigInteger srcDpId, BigInteger destDpId, long lportTagOrVni, long elanTag,
956                                           String macAddress, String displayName, String interfaceName,
957                                           WriteTransaction writeFlowGroupTx, ElanInstance elanInstance) {
958         Flow flowEntity;
959         EtreeInterface etreeInterface = elanInterfaceCache.getEtreeInterface(interfaceName).orNull();
960         if (etreeInterface != null && etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
961             EtreeLeafTagName etreeTagName = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
962             if (etreeTagName == null) {
963                 LOG.warn("Interface " + interfaceName
964                         + " seems like it belongs to Etree but etreeTagName from elanTag " + elanTag + " is null.");
965             } else {
966                 flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTagOrVni,
967                         etreeTagName.getEtreeLeafTag().getValue(), macAddress, displayName, elanInstance);
968                 mdsalManager.addFlowToTx(srcDpId, flowEntity, writeFlowGroupTx);
969             }
970         }
971     }
972
973     /**
974      * Builds a Flow to be programmed in a remote DPN's DMAC table. This flow
975      * consists in: Match: + elanTag in packet's metadata + packet going to a
976      * MAC known to be located in another DPN Actions: + set_tunnel_id
977      * + output ITM internal tunnel interface with the other DPN
978      *
979      * @param srcDpId
980      *            the src Dpn Id
981      * @param destDpId
982      *            dest Dp Id
983      * @param lportTagOrVni
984      *            lportTag or network VNI
985      * @param elanTag
986      *            elan Tag
987      * @param macAddress
988      *            macAddress
989      * @param displayName
990      *            display Name
991      * @param elanInstance
992      *            elanInstance
993      * @return the flow remote Dmac
994      */
995     @SuppressWarnings("checkstyle:IllegalCatch")
996     public Flow buildRemoteDmacFlowEntry(BigInteger srcDpId, BigInteger destDpId, long lportTagOrVni, long elanTag,
997             String macAddress, String displayName, ElanInstance elanInstance) {
998         List<MatchInfo> mkMatches = new ArrayList<>();
999         mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
1000         mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddress)));
1001
1002         List<Instruction> mkInstructions = new ArrayList<>();
1003
1004         // List of Action for the provided Source and Destination DPIDs
1005         try {
1006             List<Action> actions = null;
1007             if (isVlan(elanInstance) || isFlat(elanInstance)) {
1008                 String interfaceName = getExternalElanInterface(elanInstance.getElanInstanceName(), srcDpId);
1009                 if (null == interfaceName) {
1010                     LOG.info("buildRemoteDmacFlowEntry: Could not find interfaceName for {} {}", srcDpId,
1011                         elanInstance);
1012                 }
1013                 actions = getEgressActionsForInterface(interfaceName, null);
1014             } else if (isVxlanNetworkOrVxlanSegment(elanInstance)) {
1015                 actions = elanItmUtils.getInternalTunnelItmEgressAction(srcDpId, destDpId, lportTagOrVni);
1016             }
1017             mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
1018         } catch (Exception e) {
1019             LOG.error("Could not get egress actions to add to flow for srcDpId=" + srcDpId + ", destDpId=" + destDpId
1020                     + ", lportTag/VNI=" + lportTagOrVni, e);
1021         }
1022
1023         Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
1024                 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, srcDpId, destDpId, macAddress, elanTag),
1025                 20, /* prio */
1026                 displayName, 0, /* idleTimeout */
1027                 0, /* hardTimeout */
1028                 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
1029
1030         return flow;
1031
1032     }
1033
1034     public void deleteMacFlows(@Nullable ElanInstance elanInfo, @Nullable InterfaceInfo interfaceInfo,
1035             MacEntry macEntry, WriteTransaction deleteFlowGroupTx) {
1036         if (elanInfo == null || interfaceInfo == null) {
1037             return;
1038         }
1039         String macAddress = macEntry.getMacAddress().getValue();
1040         synchronized (getElanMacDPNKey(elanInfo.getElanTag(), macAddress, interfaceInfo.getDpId())) {
1041             deleteMacFlows(elanInfo, interfaceInfo, macAddress, /* alsoDeleteSMAC */ true, deleteFlowGroupTx);
1042         }
1043     }
1044
1045     public void deleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1046             boolean deleteSmac, WriteTransaction deleteFlowGroupTx) {
1047         String elanInstanceName = elanInfo.getElanInstanceName();
1048         List<DpnInterfaces> remoteFEs = getInvolvedDpnsInElan(elanInstanceName);
1049         BigInteger srcdpId = interfaceInfo.getDpId();
1050         boolean isFlowsRemovedInSrcDpn = false;
1051         for (DpnInterfaces dpnInterface : remoteFEs) {
1052             Long elanTag = elanInfo.getElanTag();
1053             BigInteger dstDpId = dpnInterface.getDpId();
1054             if (executeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1055                     elanTag, dstDpId, deleteFlowGroupTx)) {
1056                 isFlowsRemovedInSrcDpn = true;
1057             }
1058             executeEtreeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1059                     elanTag, dstDpId, deleteFlowGroupTx);
1060         }
1061         if (!isFlowsRemovedInSrcDpn) {
1062             deleteSmacAndDmacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, deleteFlowGroupTx);
1063         }
1064     }
1065
1066     private void executeEtreeDeleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1067             boolean deleteSmac, String elanInstanceName, BigInteger srcdpId, Long elanTag, BigInteger dstDpId,
1068             WriteTransaction deleteFlowGroupTx) {
1069         EtreeLeafTagName etreeLeafTag = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
1070         if (etreeLeafTag != null) {
1071             executeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1072                     etreeLeafTag.getEtreeLeafTag().getValue(), dstDpId, deleteFlowGroupTx);
1073         }
1074     }
1075
1076     private boolean executeDeleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1077             boolean deleteSmac, String elanInstanceName, BigInteger srcdpId, Long elanTag, BigInteger dstDpId,
1078             WriteTransaction deleteFlowGroupTx) {
1079         boolean isFlowsRemovedInSrcDpn = false;
1080         if (dstDpId.equals(srcdpId)) {
1081             isFlowsRemovedInSrcDpn = true;
1082             deleteSmacAndDmacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, deleteFlowGroupTx);
1083         } else if (isDpnPresent(dstDpId)) {
1084             mdsalManager
1085                     .removeFlowToTx(dstDpId,
1086                             MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, getKnownDynamicmacFlowRef(
1087                                     NwConstants.ELAN_DMAC_TABLE, dstDpId, srcdpId, macAddress, elanTag)),
1088                             deleteFlowGroupTx);
1089             LOG.debug("Dmac flow entry deleted for elan:{}, logical interface port:{} and mac address:{} on dpn:{}",
1090                     elanInstanceName, interfaceInfo.getPortName(), macAddress, dstDpId);
1091         }
1092         return isFlowsRemovedInSrcDpn;
1093     }
1094
1095     private void deleteSmacAndDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1096             boolean deleteSmac, WriteTransaction deleteFlowGroupTx) {
1097         String elanInstanceName = elanInfo.getElanInstanceName();
1098         long ifTag = interfaceInfo.getInterfaceTag();
1099         BigInteger srcdpId = interfaceInfo.getDpId();
1100         Long elanTag = elanInfo.getElanTag();
1101         if (deleteSmac) {
1102             mdsalManager
1103                     .removeFlowToTx(srcdpId,
1104                             MDSALUtil.buildFlow(NwConstants.ELAN_SMAC_TABLE, getKnownDynamicmacFlowRef(
1105                                     NwConstants.ELAN_SMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)),
1106                             deleteFlowGroupTx);
1107         }
1108         mdsalManager.removeFlowToTx(srcdpId,
1109                 MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE,
1110                         getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)),
1111                 deleteFlowGroupTx);
1112         LOG.debug("All the required flows deleted for elan:{}, logical Interface port:{} and MAC address:{} on dpn:{}",
1113                 elanInstanceName, interfaceInfo.getPortName(), macAddress, srcdpId);
1114     }
1115
1116     /**
1117      * Updates the Elan information in the Operational DS. It also updates the
1118      * ElanInstance in the Config DS by setting the adquired elanTag.
1119      *
1120      * @param idManager
1121      *            the id manager
1122      * @param elanInstanceAdded
1123      *            the elan instance added
1124      * @param elanInterfaces
1125      *            the elan interfaces
1126      * @param tx
1127      *            transaction
1128      *
1129      * @return the updated ELAN instance.
1130      */
1131     public static ElanInstance updateOperationalDataStore(IdManagerService idManager,
1132             ElanInstance elanInstanceAdded, List<String> elanInterfaces, WriteTransaction tx) {
1133         String elanInstanceName = elanInstanceAdded.getElanInstanceName();
1134         Long elanTag = elanInstanceAdded.getElanTag();
1135         if (elanTag == null || elanTag == 0L) {
1136             elanTag = retrieveNewElanTag(idManager, elanInstanceName);
1137         }
1138         Elan elanInfo = new ElanBuilder().setName(elanInstanceName).setElanInterfaces(elanInterfaces)
1139                 .setKey(new ElanKey(elanInstanceName)).build();
1140
1141         // Add the ElanState in the elan-state operational data-store
1142         tx.put(LogicalDatastoreType.OPERATIONAL, getElanInstanceOperationalDataPath(elanInstanceName),
1143                 elanInfo, WriteTransaction.CREATE_MISSING_PARENTS);
1144
1145         // Add the ElanMacTable in the elan-mac-table operational data-store
1146         MacTable elanMacTable = new MacTableBuilder().setKey(new MacTableKey(elanInstanceName)).build();
1147         tx.put(LogicalDatastoreType.OPERATIONAL, getElanMacTableOperationalDataPath(elanInstanceName),
1148                 elanMacTable, WriteTransaction.CREATE_MISSING_PARENTS);
1149
1150         ElanTagNameBuilder elanTagNameBuilder = new ElanTagNameBuilder().setElanTag(elanTag)
1151                 .setKey(new ElanTagNameKey(elanTag)).setName(elanInstanceName);
1152         long etreeLeafTag = -1;
1153         if (isEtreeInstance(elanInstanceAdded)) {
1154             etreeLeafTag = retrieveNewElanTag(idManager,elanInstanceName + ElanConstants
1155                     .LEAVES_POSTFIX);
1156             EtreeLeafTagName etreeLeafTagName = new EtreeLeafTagNameBuilder()
1157                     .setEtreeLeafTag(new EtreeLeafTag(etreeLeafTag)).build();
1158             elanTagNameBuilder.addAugmentation(EtreeLeafTagName.class, etreeLeafTagName);
1159             addTheLeafTagAsElanTag(elanInstanceName, etreeLeafTag, tx);
1160         }
1161         ElanTagName elanTagName = elanTagNameBuilder.build();
1162
1163         // Add the ElanTag to ElanName in the elan-tag-name Operational
1164         // data-store
1165         tx.put(LogicalDatastoreType.OPERATIONAL,
1166                 getElanInfoEntriesOperationalDataPath(elanTag), elanTagName);
1167
1168         // Updates the ElanInstance Config DS by setting the just acquired
1169         // elanTag
1170         ElanInstanceBuilder elanInstanceBuilder = new ElanInstanceBuilder().setElanInstanceName(elanInstanceName)
1171                 .setDescription(elanInstanceAdded.getDescription())
1172                 .setMacTimeout(elanInstanceAdded.getMacTimeout() == null
1173                         ? Long.valueOf(ElanConstants.DEFAULT_MAC_TIME_OUT) : elanInstanceAdded.getMacTimeout())
1174                 .setKey(elanInstanceAdded.getKey()).setElanTag(elanTag);
1175         if (isEtreeInstance(elanInstanceAdded)) {
1176             EtreeInstance etreeInstance = new EtreeInstanceBuilder().setEtreeLeafTagVal(new EtreeLeafTag(etreeLeafTag))
1177                     .build();
1178             elanInstanceBuilder.addAugmentation(EtreeInstance.class, etreeInstance);
1179         }
1180         ElanInstance elanInstanceWithTag = elanInstanceBuilder.build();
1181         tx.merge(LogicalDatastoreType.CONFIGURATION, ElanHelper.getElanInstanceConfigurationDataPath(elanInstanceName),
1182                 elanInstanceWithTag, WriteTransaction.CREATE_MISSING_PARENTS);
1183         return elanInstanceWithTag;
1184     }
1185
1186     private static void addTheLeafTagAsElanTag(String elanInstanceName, long etreeLeafTag, WriteTransaction tx) {
1187         ElanTagName etreeTagAsElanTag = new ElanTagNameBuilder().setElanTag(etreeLeafTag)
1188                 .setKey(new ElanTagNameKey(etreeLeafTag)).setName(elanInstanceName).build();
1189         tx.put(LogicalDatastoreType.OPERATIONAL,
1190                 getElanInfoEntriesOperationalDataPath(etreeLeafTag), etreeTagAsElanTag);
1191     }
1192
1193     private static boolean isEtreeInstance(ElanInstance elanInstanceAdded) {
1194         return elanInstanceAdded.getAugmentation(EtreeInstance.class) != null;
1195     }
1196
1197     public boolean isDpnPresent(BigInteger dpnId) {
1198         String dpn = String.format("%s:%s", "openflow", dpnId);
1199         NodeId nodeId = new NodeId(dpn);
1200
1201         InstanceIdentifier<Node> node = InstanceIdentifier.builder(Nodes.class).child(Node.class, new NodeKey(nodeId))
1202                 .build();
1203         return read(broker, LogicalDatastoreType.CONFIGURATION, node).isPresent();
1204     }
1205
1206     public static ServicesInfo getServiceInfo(String elanInstanceName, String interfaceName) {
1207         return InterfaceServiceUtil.buildServiceInfo(elanInstanceName + "." + interfaceName,
1208                 ElanConstants.ELAN_SERVICE_PRIORITY);
1209     }
1210
1211     public static String getElanServiceName(String elanName, String interfaceName) {
1212         return "elan." + elanName + interfaceName;
1213     }
1214
1215     public static BoundServices getBoundServices(String serviceName, short servicePriority, int flowPriority,
1216             BigInteger cookie, List<Instruction> instructions) {
1217         StypeOpenflowBuilder augBuilder = new StypeOpenflowBuilder().setFlowCookie(cookie).setFlowPriority(flowPriority)
1218                 .setInstruction(instructions);
1219         return new BoundServicesBuilder().setKey(new BoundServicesKey(servicePriority)).setServiceName(serviceName)
1220                 .setServicePriority(servicePriority).setServiceType(ServiceTypeFlowBased.class)
1221                 .addAugmentation(StypeOpenflow.class, augBuilder.build()).build();
1222     }
1223
1224     public static InstanceIdentifier<BoundServices> buildServiceId(String interfaceName, short serviceIndex) {
1225         return InstanceIdentifier.builder(ServiceBindings.class)
1226                 .child(ServicesInfo.class, new ServicesInfoKey(interfaceName, ServiceModeIngress.class))
1227                 .child(BoundServices.class, new BoundServicesKey(serviceIndex)).build();
1228     }
1229
1230     public static List<MatchInfo> getTunnelMatchesForServiceId(int elanTag) {
1231         List<MatchInfo> mkMatches = new ArrayList<>();
1232         // Matching metadata
1233         mkMatches.add(new MatchTunnelId(BigInteger.valueOf(elanTag)));
1234
1235         return mkMatches;
1236     }
1237
1238     public void removeTerminatingServiceAction(BigInteger destDpId, int serviceId) {
1239         RemoveTerminatingServiceActionsInput input = new RemoveTerminatingServiceActionsInputBuilder()
1240                 .setDpnId(destDpId).setServiceId(serviceId).build();
1241         Future<RpcResult<Void>> futureObject = itmRpcService.removeTerminatingServiceActions(input);
1242         try {
1243             RpcResult<Void> result = futureObject.get();
1244             if (result.isSuccessful()) {
1245                 LOG.debug("Successfully completed removeTerminatingServiceActions for ELAN with serviceId {} on "
1246                                 + "dpn {}", serviceId, destDpId);
1247             } else {
1248                 LOG.debug("Failure in removeTerminatingServiceAction RPC call for ELAN with serviceId {} on "
1249                         + "dpn {}", serviceId, destDpId);
1250             }
1251         } catch (InterruptedException | ExecutionException e) {
1252             LOG.error("Error in RPC call removeTerminatingServiceActions for ELAN with serviceId {} on "
1253                     + "dpn {}: {}", serviceId, destDpId, e);
1254         }
1255     }
1256
1257     /**
1258      * Gets the external tunnel.
1259      *
1260      * @param sourceDevice
1261      *            the source device
1262      * @param destinationDevice
1263      *            the destination device
1264      * @param datastoreType
1265      *            the datastore type
1266      * @return the external tunnel
1267      */
1268     public ExternalTunnel getExternalTunnel(String sourceDevice, String destinationDevice,
1269             LogicalDatastoreType datastoreType) {
1270         Class<? extends TunnelTypeBase> tunType = TunnelTypeVxlan.class;
1271         InstanceIdentifier<ExternalTunnel> iid = InstanceIdentifier.builder(ExternalTunnelList.class)
1272                 .child(ExternalTunnel.class, new ExternalTunnelKey(destinationDevice, sourceDevice, tunType)).build();
1273         return read(broker, datastoreType, iid).orNull();
1274     }
1275
1276     /**
1277      * Gets the external tunnel.
1278      *
1279      * @param interfaceName
1280      *            the interface name
1281      * @param datastoreType
1282      *            the datastore type
1283      * @return the external tunnel
1284      */
1285     public ExternalTunnel getExternalTunnel(String interfaceName, LogicalDatastoreType datastoreType) {
1286         ExternalTunnel externalTunnel = null;
1287         List<ExternalTunnel> externalTunnels = getAllExternalTunnels(datastoreType);
1288         for (ExternalTunnel tunnel : externalTunnels) {
1289             if (StringUtils.equalsIgnoreCase(interfaceName, tunnel.getTunnelInterfaceName())) {
1290                 externalTunnel = tunnel;
1291                 break;
1292             }
1293         }
1294         return externalTunnel;
1295     }
1296
1297     /**
1298      * Gets the all external tunnels.
1299      *
1300      * @param datastoreType
1301      *            the data store type
1302      * @return the all external tunnels
1303      */
1304     public List<ExternalTunnel> getAllExternalTunnels(LogicalDatastoreType datastoreType) {
1305         InstanceIdentifier<ExternalTunnelList> iid = InstanceIdentifier.builder(ExternalTunnelList.class).build();
1306         return read(broker, datastoreType, iid).toJavaUtil().map(ExternalTunnelList::getExternalTunnel).orElse(
1307                 Collections.emptyList());
1308     }
1309
1310     public static List<MatchInfo> buildMatchesForElanTagShFlagAndDstMac(long elanTag, boolean shFlag, String macAddr) {
1311         List<MatchInfo> mkMatches = new ArrayList<>();
1312         mkMatches.add(
1313                 new MatchMetadata(getElanMetadataLabel(elanTag, shFlag), MetaDataUtil.METADATA_MASK_SERVICE_SH_FLAG));
1314         mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddr)));
1315         return mkMatches;
1316     }
1317
1318     /**
1319      * Checks if is interface operational.
1320      *
1321      * @param interfaceName
1322      *            the interface name
1323      * @param dataBroker
1324      *            the data broker
1325      * @return true, if is interface operational
1326      */
1327     public static boolean isInterfaceOperational(String interfaceName, DataBroker dataBroker) {
1328         if (StringUtils.isBlank(interfaceName)) {
1329             return false;
1330         }
1331         Interface ifState = getInterfaceStateFromOperDS(interfaceName, dataBroker);
1332         if (ifState == null) {
1333             return false;
1334         }
1335         return ifState.getOperStatus() == OperStatus.Up && ifState.getAdminStatus() == AdminStatus.Up;
1336     }
1337
1338     /**
1339      * Gets the interface state from operational ds.
1340      *
1341      * @param interfaceName
1342      *            the interface name
1343      * @param dataBroker
1344      *            the data broker
1345      * @return the interface state from oper ds
1346      */
1347     public static org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1348         .ietf.interfaces.rev140508.interfaces.state.Interface getInterfaceStateFromOperDS(
1349             String interfaceName, DataBroker dataBroker) {
1350         InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1351             .ietf.interfaces.rev140508.interfaces.state.Interface> ifStateId = createInterfaceStateInstanceIdentifier(
1352                 interfaceName);
1353         return MDSALUtil.read(dataBroker, LogicalDatastoreType.OPERATIONAL, ifStateId).orNull();
1354     }
1355
1356     /**
1357      * Creates the interface state instance identifier.
1358      *
1359      * @param interfaceName
1360      *            the interface name
1361      * @return the instance identifier
1362      */
1363     public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1364         .ietf.interfaces.rev140508.interfaces.state.Interface> createInterfaceStateInstanceIdentifier(
1365             String interfaceName) {
1366         InstanceIdentifierBuilder<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1367             .ietf.interfaces.rev140508.interfaces.state.Interface> idBuilder = InstanceIdentifier
1368                 .builder(InterfacesState.class)
1369                 .child(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1370                         .ietf.interfaces.rev140508.interfaces.state.Interface.class,
1371                         new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1372                             .ietf.interfaces.rev140508.interfaces.state.InterfaceKey(
1373                                 interfaceName));
1374         return idBuilder.build();
1375     }
1376
1377     public static CheckedFuture<Void, TransactionCommitFailedException> waitForTransactionToComplete(
1378             WriteTransaction tx) {
1379         CheckedFuture<Void, TransactionCommitFailedException> futures = tx.submit();
1380         try {
1381             futures.get();
1382         } catch (InterruptedException | ExecutionException e) {
1383             LOG.error("Error writing to datastore {}", e);
1384         }
1385         return futures;
1386     }
1387
1388     public static boolean isVxlan(@Nullable ElanInstance elanInstance) {
1389         return elanInstance != null && elanInstance.getSegmentType() != null
1390                 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1391                 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId() != 0;
1392     }
1393
1394     private static boolean isVxlanSegment(ElanInstance elanInstance) {
1395         if (elanInstance != null) {
1396             List<ElanSegments> elanSegments = elanInstance.getElanSegments();
1397             if (elanSegments != null) {
1398                 for (ElanSegments segment : elanSegments) {
1399                     if (segment != null && segment.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1400                             && segment.getSegmentationId() != null
1401                             && segment.getSegmentationId().longValue() != 0) {
1402                         return true;
1403                     }
1404                 }
1405             }
1406         }
1407         return false;
1408     }
1409
1410     public static boolean isVxlanNetworkOrVxlanSegment(ElanInstance elanInstance) {
1411         return isVxlan(elanInstance) || isVxlanSegment(elanInstance);
1412     }
1413
1414     public static Long getVxlanSegmentationId(ElanInstance elanInstance) {
1415         Long segmentationId = 0L;
1416         if (elanInstance == null) {
1417             return segmentationId;
1418         }
1419
1420         if (elanInstance.getSegmentType() != null
1421                 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1422                 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId().longValue() != 0) {
1423             segmentationId = elanInstance.getSegmentationId();
1424         } else {
1425             for (ElanSegments segment: elanInstance.getElanSegments()) {
1426                 if (segment != null && segment.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1427                     && segment.getSegmentationId() != null
1428                     && segment.getSegmentationId().longValue() != 0) {
1429                     segmentationId = segment.getSegmentationId();
1430                 }
1431             }
1432         }
1433         return segmentationId;
1434     }
1435
1436     public static boolean isVlan(ElanInstance elanInstance) {
1437         return elanInstance != null && elanInstance.getSegmentType() != null
1438                 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVlan.class)
1439                 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId() != 0;
1440     }
1441
1442     public static boolean isFlat(ElanInstance elanInstance) {
1443         return elanInstance != null && elanInstance.getSegmentType() != null
1444                 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeFlat.class);
1445     }
1446
1447     public void addDmacRedirectToDispatcherFlows(Long elanTag, String displayName,
1448             String macAddress, List<BigInteger> dpnIds) {
1449         for (BigInteger dpId : dpnIds) {
1450             ListenableFutures.addErrorLogging(txRunner.callWithNewWriteOnlyTransactionAndSubmit(
1451                 tx -> mdsalManager.addFlowToTx(
1452                         buildDmacRedirectToDispatcherFlow(dpId, macAddress, displayName, elanTag), tx)), LOG,
1453                 "Error adding DMAC redirect to dispatcher flows");
1454         }
1455     }
1456
1457     public void removeDmacRedirectToDispatcherFlows(Long elanTag, String macAddress, List<BigInteger> dpnIds) {
1458         for (BigInteger dpId : dpnIds) {
1459             String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, macAddress, elanTag);
1460             mdsalManager.removeFlow(dpId, MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, flowId));
1461         }
1462     }
1463
1464     public static FlowEntity buildDmacRedirectToDispatcherFlow(BigInteger dpId, String dstMacAddress,
1465             String displayName, long elanTag) {
1466         List<MatchInfo> matches = new ArrayList<>();
1467         matches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
1468         matches.add(new MatchEthernetDestination(new MacAddress(dstMacAddress)));
1469         List<InstructionInfo> instructions = new ArrayList<>();
1470         List<ActionInfo> actions = new ArrayList<>();
1471         actions.add(new ActionNxResubmit(NwConstants.LPORT_DISPATCHER_TABLE));
1472
1473         instructions.add(new InstructionApplyActions(actions));
1474         String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, dstMacAddress, elanTag);
1475         return MDSALUtil.buildFlowEntity(dpId, NwConstants.ELAN_DMAC_TABLE, flowId, 20, displayName, 0, 0,
1476                 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)),
1477                 matches, instructions);
1478     }
1479
1480     public String getExternalElanInterface(String elanInstanceName, BigInteger dpnId) {
1481         DpnInterfaces dpnInterfaces = getElanInterfaceInfoByElanDpn(elanInstanceName, dpnId);
1482         if (dpnInterfaces == null || dpnInterfaces.getInterfaces() == null) {
1483             LOG.trace("Elan {} does not have interfaces in DPN {}", elanInstanceName, dpnId);
1484             return null;
1485         }
1486
1487         for (String dpnInterface : dpnInterfaces.getInterfaces()) {
1488             if (interfaceManager.isExternalInterface(dpnInterface)) {
1489                 return dpnInterface;
1490             }
1491         }
1492
1493         LOG.trace("Elan {} does not have any external interace attached to DPN {}", elanInstanceName, dpnId);
1494         return null;
1495     }
1496
1497     public static String getElanMacDPNKey(long elanTag, String macAddress, BigInteger dpnId) {
1498         String elanMacDmacDpnKey = "MAC-" + macAddress + " ELAN_TAG-" + elanTag + "DPN_ID-" + dpnId;
1499         return elanMacDmacDpnKey.intern();
1500     }
1501
1502     public static String getElanMacKey(long elanTag, String macAddress) {
1503         String elanMacKey = "MAC-" + macAddress + " ELAN_TAG-" + elanTag;
1504         return elanMacKey.intern();
1505     }
1506
1507     // TODO This should return a collection of futures
1508     public static void addToListenableFutureIfTxException(RuntimeException exception,
1509             List<ListenableFuture<Void>> futures) {
1510         Throwable cause = exception.getCause();
1511         if (cause != null && cause instanceof TransactionCommitFailedException) {
1512             futures.add(Futures.immediateFailedCheckedFuture((TransactionCommitFailedException) cause));
1513         }
1514     }
1515
1516     public static List<PhysAddress> getPhysAddress(List<String> macAddress) {
1517         Preconditions.checkNotNull(macAddress, "macAddress cannot be null");
1518         List<PhysAddress> physAddresses = new ArrayList<>();
1519         for (String mac : macAddress) {
1520             physAddresses.add(new PhysAddress(mac));
1521         }
1522         return physAddresses;
1523     }
1524
1525     public static List<StaticMacEntries> getStaticMacEntries(List<String> staticMacAddresses) {
1526         if (isEmpty(staticMacAddresses)) {
1527             return Collections.EMPTY_LIST;
1528         }
1529         StaticMacEntriesBuilder staticMacEntriesBuilder = new StaticMacEntriesBuilder();
1530         List<StaticMacEntries> staticMacEntries = new ArrayList<>();
1531         List<PhysAddress> physAddressList = getPhysAddress(staticMacAddresses);
1532         for (PhysAddress physAddress : physAddressList) {
1533             staticMacEntries.add(staticMacEntriesBuilder.setMacAddress(physAddress).build());
1534         }
1535         return staticMacEntries;
1536     }
1537
1538     public static InstanceIdentifier<StaticMacEntries> getStaticMacEntriesCfgDataPathIdentifier(String interfaceName,
1539                                                                                                 String macAddress) {
1540         return InstanceIdentifier.builder(ElanInterfaces.class)
1541                 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).child(StaticMacEntries.class,
1542                         new StaticMacEntriesKey(new PhysAddress(macAddress))).build();
1543     }
1544
1545     public static List<StaticMacEntries> getDeletedEntries(List<StaticMacEntries> originalStaticMacEntries,
1546                                                            List<StaticMacEntries> updatedStaticMacEntries) {
1547         if (isEmpty(originalStaticMacEntries)) {
1548             return Collections.EMPTY_LIST;
1549         }
1550         List<StaticMacEntries> deleted = Lists.newArrayList(originalStaticMacEntries);
1551         if (isNotEmpty(updatedStaticMacEntries)) {
1552             deleted.removeAll(updatedStaticMacEntries);
1553         }
1554         return deleted;
1555     }
1556
1557     public static <T> List<T> diffOf(List<T> orig, List<T> updated) {
1558         if (isEmpty(orig)) {
1559             return Collections.EMPTY_LIST;
1560         }
1561         List<T> diff = Lists.newArrayList(orig);
1562         if (isNotEmpty(updated)) {
1563             diff.removeAll(updated);
1564         }
1565         return diff;
1566     }
1567
1568     public static void segregateToBeDeletedAndAddEntries(List<StaticMacEntries> originalStaticMacEntries,
1569                                                              List<StaticMacEntries> updatedStaticMacEntries) {
1570         if (isNotEmpty(updatedStaticMacEntries)) {
1571             List<StaticMacEntries> existingClonedStaticMacEntries = new ArrayList<>();
1572             if (isNotEmpty(originalStaticMacEntries)) {
1573                 existingClonedStaticMacEntries.addAll(0, originalStaticMacEntries);
1574                 originalStaticMacEntries.removeAll(updatedStaticMacEntries);
1575                 updatedStaticMacEntries.removeAll(existingClonedStaticMacEntries);
1576             }
1577         }
1578     }
1579
1580     public static boolean isEmpty(Collection collection) {
1581         return collection == null || collection.isEmpty();
1582     }
1583
1584     public static boolean isNotEmpty(Collection collection) {
1585         return !isEmpty(collection);
1586     }
1587
1588     public Optional<IpAddress> getSourceIpAddress(Ethernet ethernet) {
1589         Optional<IpAddress> srcIpAddress = Optional.absent();
1590         if (ethernet.getPayload() == null) {
1591             return srcIpAddress;
1592         }
1593         byte[] ipAddrBytes = null;
1594         if (ethernet.getPayload() instanceof IPv4) {
1595             IPv4 ipv4 = (IPv4) ethernet.getPayload();
1596             ipAddrBytes = Ints.toByteArray(ipv4.getSourceAddress());
1597         } else if (ethernet.getPayload() instanceof ARP) {
1598             ipAddrBytes = ((ARP) ethernet.getPayload()).getSenderProtocolAddress();
1599         }
1600         if (ipAddrBytes != null) {
1601             String ipAddr = NWUtil.toStringIpAddress(ipAddrBytes);
1602             return Optional.of(IpAddressBuilder.getDefaultInstance(ipAddr));
1603         }
1604         return srcIpAddress;
1605     }
1606
1607     public List<MacEntry> getElanMacEntries(String elanName) {
1608         MacTable macTable = getElanMacTable(elanName);
1609         if (macTable == null) {
1610             return Collections.emptyList();
1611         }
1612         return macTable.getMacEntry();
1613     }
1614
1615     public boolean isTunnelInLogicalGroup(String interfaceName) {
1616         org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1617             .ietf.interfaces.rev140508.interfaces.Interface configIface =
1618             interfaceManager.getInterfaceInfoFromConfigDataStore(interfaceName);
1619         IfTunnel ifTunnel = configIface.getAugmentation(IfTunnel.class);
1620         if (ifTunnel != null && ifTunnel.getTunnelInterfaceType().isAssignableFrom(TunnelTypeVxlan.class)) {
1621             ParentRefs refs = configIface.getAugmentation(ParentRefs.class);
1622             if (refs != null && !Strings.isNullOrEmpty(refs.getParentInterface())) {
1623                 return true; //multiple VxLAN tunnels enabled, i.e. only logical tunnel should be treated
1624             }
1625         }
1626         return false;
1627     }
1628
1629     public static InstanceIdentifier<Flow> getFlowIid(Flow flow, BigInteger dpnId) {
1630         FlowKey flowKey = new FlowKey(new FlowId(flow.getId()));
1631         org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId nodeId =
1632                 new org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId("openflow:" + dpnId);
1633         org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node nodeDpn =
1634                 new NodeBuilder().setId(nodeId).setKey(new NodeKey(nodeId)).build();
1635         return InstanceIdentifier.builder(Nodes.class)
1636                 .child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node.class,
1637                         nodeDpn.getKey()).augmentation(FlowCapableNode.class)
1638                 .child(Table.class, new TableKey(flow.getTableId())).child(Flow.class, flowKey).build();
1639     }
1640
1641     public static String getElanInterfaceJobKey(String interfaceName) {
1642         return "elaninterface-" + interfaceName;
1643     }
1644
1645     public void removeArpResponderFlow(BigInteger dpnId, String ingressInterfaceName, String ipAddress,
1646             int lportTag) {
1647         LOG.info("Removing the ARP responder flow on DPN {} of Interface {} with IP {}", dpnId, ingressInterfaceName,
1648                 ipAddress);
1649         ArpResponderUtil.removeFlow(mdsalManager, dpnId, ArpResponderUtil.getFlowId(lportTag, ipAddress));
1650     }
1651 }
1652
1653