Merge "HwVTEP JUNITs, and fixing show:vxlan CLI"
[vpnservice.git] / elanmanager / elanmanager-impl / src / main / java / org / opendaylight / vpnservice / elan / utils / ElanUtils.java
1 /*
2  * Copyright (c) 2016 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.vpnservice.elan.utils;
9
10 import java.math.BigInteger;
11 import java.util.ArrayList;
12 import java.util.List;
13 import java.util.concurrent.ExecutionException;
14 import java.util.concurrent.Future;
15
16 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
17 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
18 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
19 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
20 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
21 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
22 import org.opendaylight.vpnservice.elan.internal.ElanInstanceManager;
23 import org.opendaylight.vpnservice.interfacemgr.globals.InterfaceInfo;
24 import org.opendaylight.vpnservice.interfacemgr.globals.InterfaceServiceUtil;
25 import org.opendaylight.vpnservice.itm.globals.ITMConstants;
26 import org.opendaylight.vpnservice.mdsalutil.FlowEntity;
27 import org.opendaylight.vpnservice.mdsalutil.InstructionInfo;
28 import org.opendaylight.vpnservice.mdsalutil.InstructionType;
29 import org.opendaylight.vpnservice.mdsalutil.MDSALUtil;
30 import org.opendaylight.vpnservice.mdsalutil.MDSALUtil.MdsalOp;
31 import org.opendaylight.vpnservice.mdsalutil.MatchFieldType;
32 import org.opendaylight.vpnservice.mdsalutil.MatchInfo;
33 import org.opendaylight.vpnservice.mdsalutil.MetaDataUtil;
34 import org.opendaylight.vpnservice.mdsalutil.NwConstants;
35 import org.opendaylight.vpnservice.mdsalutil.interfaces.IMdsalApiManager;
36 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.PhysAddress;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.servicebinding.rev151015.ServiceBindings;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.servicebinding.rev151015.ServiceTypeFlowBased;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.servicebinding.rev151015.StypeOpenflow;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.servicebinding.rev151015.StypeOpenflowBuilder;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.servicebinding.rev151015.service.bindings.ServicesInfo;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.servicebinding.rev151015.service.bindings.ServicesInfoKey;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.servicebinding.rev151015.service.bindings.services.info.BoundServices;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.servicebinding.rev151015.service.bindings.services.info.BoundServicesBuilder;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.servicebinding.rev151015.service.bindings.services.info.BoundServicesKey;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.ElanDpnInterfaces;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.ElanForwardingTables;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.ElanInstances;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.ElanInterfaceForwardingEntries;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.ElanInterfaces;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.ElanState;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.ElanTagNameMap;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan._interface.forwarding.entries.ElanInterfaceMac;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan._interface.forwarding.entries.ElanInterfaceMacKey;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesList;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesListKey;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfaces;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfacesKey;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.forwarding.tables.MacTable;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.forwarding.tables.MacTableBuilder;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.forwarding.tables.MacTableKey;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.instances.ElanInstance;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.instances.ElanInstanceBuilder;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.instances.ElanInstanceKey;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.interfaces.ElanInterface;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.interfaces.ElanInterfaceKey;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.state.Elan;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.state.ElanBuilder;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.state.ElanKey;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.tag.name.map.ElanTagName;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.tag.name.map.ElanTagNameBuilder;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.tag.name.map.ElanTagNameKey;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.forwarding.entries.MacEntry;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.forwarding.entries.MacEntryKey;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.idmanager.rev150403.AllocateIdInput;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.idmanager.rev150403.AllocateIdInputBuilder;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.idmanager.rev150403.AllocateIdOutput;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.idmanager.rev150403.IdManagerService;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.idmanager.rev150403.ReleaseIdInput;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.idmanager.rev150403.ReleaseIdInputBuilder;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.meta.rev151007.IfIndexesInterfaceMap;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.meta.rev151007._if.indexes._interface.map.IfIndexInterface;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.meta.rev151007._if.indexes._interface.map.IfIndexInterfaceKey;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rpcs.rev151003.GetDpidFromInterfaceInputBuilder;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rpcs.rev151003.GetDpidFromInterfaceOutput;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rpcs.rev151003.GetEgressActionsForInterfaceInput;
96 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rpcs.rev151003.GetEgressActionsForInterfaceInputBuilder;
97 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rpcs.rev151003.GetEgressActionsForInterfaceOutput;
98 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rpcs.rev151003.OdlInterfaceRpcService;
99 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.itm.op.rev150701.TunnelList;
100 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.itm.rpcs.rev151217.CreateTerminatingServiceActionsInput;
101 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.itm.rpcs.rev151217.CreateTerminatingServiceActionsInputBuilder;
102 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.itm.rpcs.rev151217.GetExternalTunnelInterfaceNameInput;
103 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.itm.rpcs.rev151217.GetExternalTunnelInterfaceNameInputBuilder;
104 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.itm.rpcs.rev151217.GetExternalTunnelInterfaceNameOutput;
105 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.itm.rpcs.rev151217.GetTunnelInterfaceNameInput;
106 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.itm.rpcs.rev151217.GetTunnelInterfaceNameInputBuilder;
107 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.itm.rpcs.rev151217.GetTunnelInterfaceNameOutput;
108 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.itm.rpcs.rev151217.ItmRpcService;
109 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.itm.rpcs.rev151217.RemoveTerminatingServiceActionsInput;
110 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.itm.rpcs.rev151217.RemoveTerminatingServiceActionsInputBuilder;
111 import org.opendaylight.yangtools.yang.binding.DataObject;
112 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
113 import org.opendaylight.yangtools.yang.common.RpcResult;
114 import org.slf4j.Logger;
115 import org.slf4j.LoggerFactory;
116
117 import com.google.common.base.Optional;
118 import com.google.common.util.concurrent.CheckedFuture;
119 import com.google.common.util.concurrent.FutureCallback;
120 import com.google.common.util.concurrent.Futures;
121 import com.google.common.util.concurrent.ListenableFuture;
122
123 public class ElanUtils {
124
125     private static final ArrayList EMPTY_LIST = new ArrayList();
126
127     private static OdlInterfaceRpcService interfaceMgrRpcService;
128
129     private static ItmRpcService itmRpcService;
130
131     private static IMdsalApiManager mdsalMgr;
132
133     private static DataBroker dataBroker;
134
135     private static final Logger logger = LoggerFactory.getLogger(ElanUtils.class);
136
137     public static final FutureCallback<Void> DEFAULT_CALLBACK = new FutureCallback<Void>() {
138         @Override
139         public void onSuccess(Void result) {
140             logger.debug("Success in Datastore operation");
141         }
142
143         @Override
144         public void onFailure(Throwable error) {
145             logger.error("Error in Datastore operation", error);
146         }
147     };
148
149     /**
150      * Uses the IdManager to retrieve a brand new ElanTag.
151      *
152      * @param idManager
153      *            the id manager
154      * @param idKey
155      *            the id key
156      * @return the integer
157      */
158     public static Integer retrieveNewElanTag(IdManagerService idManager, String idKey) {
159
160         AllocateIdInput getIdInput = new AllocateIdInputBuilder().setPoolName(ElanConstants.ELAN_ID_POOL_NAME)
161                 .setIdKey(idKey).build();
162
163         try {
164             Future<RpcResult<AllocateIdOutput>> result = idManager.allocateId(getIdInput);
165             RpcResult<AllocateIdOutput> rpcResult = result.get();
166             if (rpcResult.isSuccessful()) {
167                 return rpcResult.getResult().getIdValue().intValue();
168             } else {
169                 logger.warn("RPC Call to Allocate Id returned with Errors {}", rpcResult.getErrors());
170             }
171         } catch (InterruptedException | ExecutionException e) {
172             logger.warn("Exception when Allocating Id",e);
173         }
174         return 0;
175     }
176
177     public static DataBroker getDataBroker() {
178         return dataBroker;
179     }
180
181     public final static void setIfaceMgrRpcService(OdlInterfaceRpcService rpcService) {
182         interfaceMgrRpcService = rpcService;
183     }
184
185     public final static void setItmRpcService(ItmRpcService itmService) {
186         itmRpcService = itmService;
187     }
188
189     public final static void setDataBroker(DataBroker broker) {
190         dataBroker = broker;
191     }
192
193     public final static void setMdsalManager(IMdsalApiManager mdsalApiManager) {
194         mdsalMgr = mdsalApiManager;
195     }
196
197     public static void releaseId(IdManagerService idManager, String poolName, String idKey) {
198         ReleaseIdInput releaseIdInput = new ReleaseIdInputBuilder().setPoolName(poolName).setIdKey(idKey).build();
199         Future<RpcResult<Void>> result = idManager.releaseId(releaseIdInput);
200     }
201
202     public static <T extends DataObject> Optional<T> read(DataBroker broker, LogicalDatastoreType datastoreType,
203             InstanceIdentifier<T> path) {
204         ReadOnlyTransaction tx = (broker != null ) ? broker.newReadOnlyTransaction() : dataBroker.newReadOnlyTransaction();
205         Optional<T> result = Optional.absent();
206         try {
207             CheckedFuture<Optional<T>, ReadFailedException> checkedFuture = tx.read(datastoreType, path);
208             result = checkedFuture.get();
209         } catch (Exception e) {
210             throw new RuntimeException(e);
211         }
212
213         return result;
214     }
215
216
217     public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType, InstanceIdentifier<T> path) {
218         WriteTransaction tx = broker.newWriteOnlyTransaction();
219         tx.delete(datastoreType, path);
220         Futures.addCallback(tx.submit(), DEFAULT_CALLBACK);
221     }
222
223
224     public static InstanceIdentifier<ElanInstance> getElanInstanceIdentifier() {
225         return InstanceIdentifier.builder(ElanInstances.class).child(ElanInstance.class).build();
226     }
227
228     //elan-instances config container
229     public static ElanInstance getElanInstanceByName(String elanInstanceName) {
230         InstanceIdentifier<ElanInstance> elanIdentifierId = getElanInstanceConfigurationDataPath(elanInstanceName);
231         Optional<ElanInstance> elanInstance = read(dataBroker, LogicalDatastoreType.CONFIGURATION, elanIdentifierId);
232         if(elanInstance.isPresent()) {
233             return elanInstance.get();
234         }
235         return null;
236     }
237
238     public static InstanceIdentifier<ElanInstance> getElanInstanceConfigurationDataPath(String elanInstanceName) {
239         return InstanceIdentifier.builder(ElanInstances.class).child(ElanInstance.class, new ElanInstanceKey(elanInstanceName)).build();
240     }
241
242     //elan-interfaces Config Container
243     public static ElanInterface getElanInterfaceByElanInterfaceName(String elanInterfaceName) {
244         InstanceIdentifier<ElanInterface> elanInterfaceId = getElanInterfaceConfigurationDataPathId(elanInterfaceName);
245         Optional<ElanInterface> existingElanInterface = read(dataBroker, LogicalDatastoreType.CONFIGURATION, elanInterfaceId);
246         if(existingElanInterface.isPresent()) {
247             return existingElanInterface.get();
248         }
249         return null;
250     }
251
252     public static InstanceIdentifier<ElanInterface> getElanInterfaceConfigurationDataPathId(String interfaceName) {
253         return InstanceIdentifier.builder(ElanInterfaces.class).child(ElanInterface.class,
254                 new ElanInterfaceKey(interfaceName)).build();
255     }
256
257     //elan-state Operational container
258     public static Elan getElanByName(String elanInstanceName) {
259         InstanceIdentifier<Elan> elanIdentifier = getElanInstanceOperationalDataPath(elanInstanceName);
260         Optional<Elan> elanInstance = read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanIdentifier);
261         if(elanInstance.isPresent()) {
262             return elanInstance.get();
263         }
264         return null;
265     }
266
267     public static InstanceIdentifier<Elan> getElanInstanceOperationalDataPath(String elanInstanceName) {
268         return InstanceIdentifier.builder(ElanState.class).child(Elan.class, new ElanKey(elanInstanceName)).build();
269     }
270
271     // grouping of forwarding-entries
272     public static MacEntry getInterfaceMacEntriesOperationalDataPath(String interfaceName, PhysAddress physAddress) {
273         InstanceIdentifier<MacEntry> existingMacEntryId = getInterfaceMacEntriesIdentifierOperationalDataPath(interfaceName, physAddress);
274         Optional<MacEntry> existingInterfaceMacEntry = read(dataBroker, LogicalDatastoreType.OPERATIONAL, existingMacEntryId);
275         if(existingInterfaceMacEntry.isPresent()) {
276             return existingInterfaceMacEntry.get();
277         }
278         return null;
279     }
280
281     public static MacEntry getInterfaceMacEntriesOperationalDataPathFromId(InstanceIdentifier identifier) {
282         Optional<MacEntry> existingInterfaceMacEntry = read(dataBroker, LogicalDatastoreType.OPERATIONAL, identifier);
283         if(existingInterfaceMacEntry.isPresent()) {
284             return existingInterfaceMacEntry.get();
285         }
286         return null;
287     }
288
289     public static InstanceIdentifier<MacEntry> getInterfaceMacEntriesIdentifierOperationalDataPath(String interfaceName, PhysAddress physAddress) {
290         return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class).child(ElanInterfaceMac.class,
291                 new ElanInterfaceMacKey(interfaceName)).child(MacEntry.class, new MacEntryKey(physAddress)).build();
292
293     }
294
295     //elan-forwarding-tables Operational container
296     public static MacEntry getMacTableByElanName(String elanName, PhysAddress physAddress) {
297         InstanceIdentifier<MacEntry> macId =  getMacEntryOperationalDataPath(elanName, physAddress);
298         Optional<MacEntry> existingElanMacEntry = read(dataBroker, LogicalDatastoreType.OPERATIONAL, macId);
299         if(existingElanMacEntry.isPresent()) {
300             return existingElanMacEntry.get();
301         }
302         return null;
303     }
304
305
306     public static MacEntry getMacEntryFromElanMacId(InstanceIdentifier identifier) {
307         Optional<MacEntry> existingInterfaceMacEntry = read(dataBroker, LogicalDatastoreType.OPERATIONAL, identifier);
308         if(existingInterfaceMacEntry.isPresent()) {
309             return existingInterfaceMacEntry.get();
310         }
311         return null;
312     }
313
314     public static InstanceIdentifier<MacEntry> getMacEntryOperationalDataPath(String elanName, PhysAddress physAddress) {
315         return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class,
316                 new MacTableKey(elanName)).child(MacEntry.class, new MacEntryKey(physAddress)).build();
317     }
318
319     public static InstanceIdentifier<MacTable> getElanMacTableOperationalDataPath(String elanName) {
320         return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class,
321                 new MacTableKey(elanName)).build();
322     }
323
324     //elan-interface-forwarding-entries Operational container
325     public static ElanInterfaceMac getElanInterfaceMacByInterfaceName(String interfaceName) {
326         InstanceIdentifier<ElanInterfaceMac> elanInterfaceId = getElanInterfaceMacEntriesOperationalDataPath(interfaceName);
327         Optional<ElanInterfaceMac> existingElanInterface = read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanInterfaceId);
328         if(existingElanInterface.isPresent()) {
329             return existingElanInterface.get();
330         }
331         return null;
332     }
333
334     /**
335      * Gets the elan interface mac addresses.
336      *
337      * @param interfaceName
338      *            the interface name
339      * @return the elan interface mac addresses
340      */
341     public static List<PhysAddress> getElanInterfaceMacAddresses(String interfaceName) {
342         List<PhysAddress> macAddresses = new ArrayList<PhysAddress>();
343         ElanInterfaceMac elanInterfaceMac = ElanUtils.getElanInterfaceMacByInterfaceName(interfaceName);
344         if (elanInterfaceMac != null && elanInterfaceMac.getMacEntry() != null) {
345             List<MacEntry> macEntries = elanInterfaceMac.getMacEntry();
346             for (MacEntry macEntry : macEntries) {
347                 macAddresses.add(macEntry.getMacAddress());
348             }
349         }
350         return macAddresses;
351     }
352
353     public static InstanceIdentifier<ElanInterfaceMac> getElanInterfaceMacEntriesOperationalDataPath(String interfaceName) {
354         return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class).child(ElanInterfaceMac.class,
355                 new ElanInterfaceMacKey(interfaceName)).build();
356     }
357
358     /**
359      * Returns the list of Interfaces that belong to an Elan on an specific DPN.
360      * Data retrieved from Elan's operational DS: elan-dpn-interfaces container
361      *
362      * @param elanInstanceName
363      *          name of the Elan to which the interfaces must belong to
364      * @param dpId
365      *          Id of the DPN where the interfaces are located
366      * @return
367      */
368     public static DpnInterfaces getElanInterfaceInfoByElanDpn(String elanInstanceName, BigInteger dpId) {
369         InstanceIdentifier<DpnInterfaces> elanDpnInterfacesId =
370                 getElanDpnInterfaceOperationalDataPath(elanInstanceName, dpId);
371         Optional<DpnInterfaces> elanDpnInterfaces = read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfacesId);
372         if ( elanDpnInterfaces.isPresent() ) {
373             return elanDpnInterfaces.get();
374         }
375         return null;
376     }
377
378     /**
379      * Returns the InstanceIdentifier that points to the Interfaces of an Elan in a
380      * given DPN in the Operational DS.
381      * Data retrieved from Elans's operational DS: dpn-interfaces list
382      *
383      * @param elanInstanceName
384      *          name of the Elan to which the interfaces must belong to
385      * @param dpId
386      *          Id of the DPN where the interfaces are located
387      * @return
388      */
389     public static InstanceIdentifier<DpnInterfaces> getElanDpnInterfaceOperationalDataPath(String elanInstanceName,
390             BigInteger dpId) {
391         return InstanceIdentifier.builder(ElanDpnInterfaces.class)
392                 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName))
393                 .child(DpnInterfaces.class, new DpnInterfacesKey(dpId)).build();
394     }
395
396     //elan-tag-name-map Operational Container
397     public static ElanTagName getElanInfoByElanTag(long elanTag) {
398         InstanceIdentifier<ElanTagName> elanId = getElanInfoEntriesOperationalDataPath(elanTag);
399         Optional<ElanTagName> existingElanInfo = ElanUtils.read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanId);
400         if(existingElanInfo.isPresent()) {
401             return existingElanInfo.get();
402         }
403         return null;
404     }
405
406     public static InstanceIdentifier<ElanTagName> getElanInfoEntriesOperationalDataPath(long elanTag) {
407         return InstanceIdentifier.builder(ElanTagNameMap.class).child(ElanTagName.class,
408                 new ElanTagNameKey(elanTag)).build();
409     }
410
411     // interface-index-tag operational container
412     public static Optional<IfIndexInterface> getInterfaceInfoByInterfaceTag(long interfaceTag) {
413         InstanceIdentifier<IfIndexInterface> interfaceId = getInterfaceInfoEntriesOperationalDataPath(interfaceTag);
414         return ElanUtils.read(dataBroker, LogicalDatastoreType.OPERATIONAL, interfaceId);
415     }
416
417     public static InstanceIdentifier<IfIndexInterface> getInterfaceInfoEntriesOperationalDataPath(long interfaceTag) {
418         return InstanceIdentifier.builder(IfIndexesInterfaceMap.class).child(IfIndexInterface.class,
419                 new IfIndexInterfaceKey((int) interfaceTag)).build();
420     }
421
422
423
424     public static InstanceIdentifier<ElanDpnInterfacesList> getElanDpnOperationDataPath(String elanInstanceName) {
425         return InstanceIdentifier.builder(ElanDpnInterfaces.class).child(ElanDpnInterfacesList.class,
426                 new ElanDpnInterfacesListKey(elanInstanceName)).build();
427     }
428
429     public static  ElanDpnInterfacesList getElanDpnInterfacesList(String elanName) {
430         InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanName);
431         Optional<ElanDpnInterfacesList> existingElanDpnInterfaces =
432                 ElanUtils.read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
433         if(existingElanDpnInterfaces.isPresent()) {
434             return existingElanDpnInterfaces.get();
435         }
436         return null;
437     }
438
439     /**
440      * This method is useful get all ELAN participating CSS dpIds to install
441      * program remote dmac entries and updating remote bc groups for tor
442      * integration.
443      *
444      * @param elanInstanceName
445      *            the elan instance name
446      * @return list of dpIds
447      */
448     public static List<BigInteger> getParticipatingDPNsInElanInstance(String elanInstanceName) {
449         List<BigInteger> dpIds = new ArrayList<BigInteger>();
450         InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
451         Optional<ElanDpnInterfacesList> existingElanDpnInterfaces =
452                 ElanUtils.read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
453         if (!existingElanDpnInterfaces.isPresent()) {
454             return dpIds;
455         }
456         List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().getDpnInterfaces();
457         for (DpnInterfaces dpnInterface: dpnInterfaces) {
458             dpIds.add(dpnInterface.getDpId());
459         }
460         return dpIds;
461     }
462
463     /**
464      * To check given dpId is already present in Elan instance. This can be used
465      * to program flow entry in external tunnel table when a new access port
466      * added for first time into the ELAN instance
467      *
468      * @param dpId
469      *            the dp id
470      * @param elanInstanceName
471      *            the elan instance name
472      * @return true if dpId is already present, otherwise return false
473      */
474     public static boolean isDpnAlreadyPresentInElanInstance(BigInteger dpId, String elanInstanceName) {
475         boolean isDpIdPresent = false;
476         InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
477         Optional<ElanDpnInterfacesList> existingElanDpnInterfaces =
478                 ElanUtils.read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
479         if (!existingElanDpnInterfaces.isPresent()) {
480             return isDpIdPresent;
481         }
482         List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().getDpnInterfaces();
483         for (DpnInterfaces dpnInterface: dpnInterfaces) {
484             if (dpnInterface.getDpId().equals(dpId)) {
485                 isDpIdPresent = true;
486                 break;
487             }
488         }
489         return isDpIdPresent;
490     }
491
492     public static ElanDpnInterfaces getElanDpnInterfacesList() {
493         InstanceIdentifier<ElanDpnInterfaces> elanDpnInterfaceId =
494                 InstanceIdentifier.builder(ElanDpnInterfaces.class).build();
495         Optional<ElanDpnInterfaces> existingElanDpnInterfaces =
496                 ElanUtils.read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
497         if(existingElanDpnInterfaces.isPresent()) {
498             return existingElanDpnInterfaces.get();
499         }
500         return null;
501     }
502
503     public static ElanForwardingTables getElanForwardingList() {
504         InstanceIdentifier<ElanForwardingTables> elanForwardingTableId =
505                 InstanceIdentifier.builder(ElanForwardingTables.class).build();
506         Optional<ElanForwardingTables> existingElanForwardingList =
507                 ElanUtils.read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanForwardingTableId);
508         if(existingElanForwardingList.isPresent()) {
509             return existingElanForwardingList.get();
510         }
511         return null;
512     }
513
514     /**
515      * Gets the elan mac table.
516      *
517      * @param elanName
518      *            the elan name
519      * @return the elan mac table
520      */
521     public static MacTable getElanMacTable(String elanName) {
522         InstanceIdentifier<MacTable> elanMacTableId = getElanMacTableOperationalDataPath(elanName);
523         Optional<MacTable> existingElanMacTable =
524                 ElanUtils.read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanMacTableId);
525         if (existingElanMacTable.isPresent()) {
526             return existingElanMacTable.get();
527         }
528         return null;
529     }
530
531     public static long getElanLocalBCGID(long elanTag) {
532         return ElanConstants.ELAN_GID_MIN + (((elanTag % ElanConstants.ELAN_GID_MIN) *2) - 1);
533     }
534
535     public static long getElanRemoteBCGID(long elanTag) {
536         return ElanConstants.ELAN_GID_MIN + (((elanTag % ElanConstants.ELAN_GID_MIN) *2));
537     }
538
539     public static BigInteger getElanMetadataLabel(long elanTag) {
540         return (BigInteger.valueOf(elanTag)).shiftLeft(24);
541     }
542
543     public static BigInteger getElanMetadataLabel(long elanTag, boolean isSHFlagSet ) {
544         int shBit = (isSHFlagSet) ? 1 : 0;
545         return (BigInteger.valueOf(elanTag)).shiftLeft(24).or(BigInteger.valueOf(shBit));
546     }
547
548     public static BigInteger getElanMetadataLabel(long elanTag, int lportTag) {
549         return getElanMetadataLabel(elanTag).or(MetaDataUtil.getLportTagMetaData(lportTag));
550     }
551
552     public static BigInteger getElanMetadataMask() {
553         return MetaDataUtil.METADATA_MASK_SERVICE.or(MetaDataUtil.METADATA_MASK_LPORT_TAG);
554     }
555
556     /**
557      * Setting INTERNAL_TUNNEL_TABLE, SMAC, DMAC, UDMAC in this DPN and also in
558      * other DPNs.
559      *
560      * @param elanInfo
561      *            the elan info
562      * @param interfaceInfo
563      *            the interface info
564      * @param macTimeout
565      *            the mac timeout
566      * @param macAddress
567      *            the mac address
568      */
569     public static void setupMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
570             String macAddress) {
571         synchronized (macAddress) {
572             logger.info("Acquired lock for mac : " + macAddress + ". Proceeding with install operation.");
573             setupKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress, mdsalMgr);
574             setupTermDmacFlows(interfaceInfo, mdsalMgr);
575             setupOrigDmacFlows(elanInfo, interfaceInfo, macAddress, mdsalMgr, dataBroker);
576         }
577     }
578
579     public static void setupDMacFlowonRemoteDpn(ElanInstance elanInfo, InterfaceInfo interfaceInfo, BigInteger dstDpId,
580             String macAddress) {
581         synchronized (macAddress) {
582             logger.info("Acquired lock for mac : " + macAddress + "Proceeding with install operation.");
583             setupOrigDmacFlowsonRemoteDpn(elanInfo, interfaceInfo, dstDpId, macAddress);
584         }
585     }
586
587
588     /**
589      * Inserts a Flow in SMAC table to state that the MAC has already been learnt.
590      *
591      * @param elanInfo
592      * @param interfaceInfo
593      * @param macTimeout
594      * @param macAddress
595      * @param mdsalApiManager
596      */
597     private static void setupKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
598             String macAddress, IMdsalApiManager mdsalApiManager) {
599         FlowEntity flowEntity = buildKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress);
600         mdsalApiManager.installFlow(flowEntity);
601         if (logger.isDebugEnabled()) {
602             logger.debug("Known Smac flow entry created for elan Name:{}, logical Interface port:{} and mac address:{}",
603                          elanInfo.getElanInstanceName(), elanInfo.getDescription(), macAddress);
604         }
605     }
606
607     public static FlowEntity buildKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout, String macAddress) {
608         BigInteger dpId = interfaceInfo.getDpId();
609         int lportTag = interfaceInfo.getInterfaceTag();
610         long elanTag = elanInfo.getElanTag();
611         // Matching metadata and eth_src fields
612         List<MatchInfo> mkMatches = new ArrayList<MatchInfo>();
613         mkMatches.add(new MatchInfo(MatchFieldType.metadata, new BigInteger[] {
614                 ElanUtils.getElanMetadataLabel(elanInfo.getElanTag(), lportTag),
615                 ElanUtils.getElanMetadataMask() }));
616         mkMatches.add(new MatchInfo(MatchFieldType.eth_src, new String[] { macAddress }));
617         List<InstructionInfo> mkInstructions = new ArrayList<InstructionInfo>();
618         mkInstructions.add(new InstructionInfo(InstructionType.goto_table, new long[] { ElanConstants.ELAN_DMAC_TABLE }));
619
620         FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpId, ElanConstants.ELAN_SMAC_TABLE,
621                 getKnownDynamicmacFlowRef(ElanConstants.ELAN_SMAC_TABLE, dpId, lportTag, macAddress, elanTag),
622                 20, elanInfo.getDescription(), (int)macTimeout, 0, ElanConstants.COOKIE_ELAN_KNOWN_SMAC.add(BigInteger.valueOf(elanTag)),
623                 mkMatches, mkInstructions);
624         flowEntity.setStrictFlag(true);
625         flowEntity.setSendFlowRemFlag(macTimeout != 0); //If Mac timeout is 0, the flow wont be deleted automatically, so no need to get notified
626         return flowEntity;
627     }
628
629     /**
630      * Installs a Flow in INTERNAL_TUNNEL_TABLE of the affected DPN that sends the packet through the specified
631      * interface if the tunnel_id matches the interface's lportTag
632      *
633      * @param interfaceInfo
634      * @param mdsalApiManager
635      */
636     private static void setupTermDmacFlows(InterfaceInfo interfaceInfo, IMdsalApiManager mdsalApiManager) {
637         BigInteger dpId = interfaceInfo.getDpId();
638         int lportTag = interfaceInfo.getInterfaceTag();
639         Flow flow = MDSALUtil.buildFlowNew(NwConstants.INTERNAL_TUNNEL_TABLE,
640                 getIntTunnelTableFlowRef(NwConstants.INTERNAL_TUNNEL_TABLE, lportTag), 5,
641                 String.format("%s:%d","ITM Flow Entry ",lportTag), 0, 0,
642                 ITMConstants.COOKIE_ITM.add(BigInteger.valueOf(lportTag)),
643                 getTunnelIdMatchForFilterEqualsLPortTag(lportTag),
644                 getInstructionsInPortForOutGroup(interfaceInfo.getInterfaceName()));
645         mdsalApiManager.installFlow(dpId, flow);
646         if (logger.isDebugEnabled()) {
647             logger.debug("Terminating service table flow entry created on dpn:{} for logical Interface port:{}",
648                          dpId, interfaceInfo.getPortName());
649         }
650     }
651
652     /**
653      * Constructs the FlowName for flows installed in the Internal Tunnel Table,
654      * consisting in tableId + elanTag.
655      *
656      * @param tableId
657      * @param elanTag
658      * @return
659      */
660     public static String getIntTunnelTableFlowRef(short tableId, int elanTag) {
661         return new StringBuffer().append(tableId).append(elanTag).toString();
662     }
663
664     /**
665      * Constructs the Matches that checks that the tunnel_id field contains a
666      * specific lportTag
667      *
668      * @param lportTag
669      *            lportTag that must be checked against the tunnel_id field
670      * @return
671      */
672     public static List<MatchInfo> getTunnelIdMatchForFilterEqualsLPortTag(int lportTag) {
673         List<MatchInfo> mkMatches = new ArrayList<MatchInfo>();
674         // Matching metadata
675         mkMatches.add(new MatchInfo(MatchFieldType.tunnel_id, new BigInteger[] {
676                 BigInteger.valueOf(lportTag)}));
677         return mkMatches;
678     }
679
680     /**
681      * Constructs the Instructions that take the packet over a given interface
682      *
683      * @param ifName
684      *          Name of the interface where the packet must be sent over. It can
685      *          be a local interface or a tunnel interface (internal or external)
686      * @return
687      */
688     public static List<Instruction> getInstructionsInPortForOutGroup(String ifName) {
689         List<Instruction> mkInstructions = new ArrayList<Instruction>();
690         List<Action> actions = ElanUtils.getEgressActionsForInterface(ifName, /*tunnelKey*/ null );
691
692         mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
693         return mkInstructions;
694     }
695
696
697     /**
698      * Returns the list of Actions to be taken when sending the packet through
699      * an Elan interface. Note that this interface can refer to an ElanInterface
700      * where the Elan VM is attached to a DPN or an ITM tunnel interface where
701      * Elan traffic can be sent through. In this latter case, the tunnelKey is
702      * mandatory and it can hold serviceId for internal tunnels or the VNI for
703      * external tunnels.
704      *
705      * @param ifName
706      *            the if name
707      * @param tunnelKey
708      *            the tunnel key
709      * @return the egress actions for interface
710      */
711     public static List<Action> getEgressActionsForInterface(String ifName, Long tunnelKey) {
712         List<Action> listAction = new ArrayList<Action>();
713         try {
714             GetEgressActionsForInterfaceInput getEgressActionInput =
715                     new GetEgressActionsForInterfaceInputBuilder().setIntfName(ifName).setTunnelKey(tunnelKey).build();
716             Future<RpcResult<GetEgressActionsForInterfaceOutput>> result =
717                     interfaceMgrRpcService.getEgressActionsForInterface(getEgressActionInput);
718             RpcResult<GetEgressActionsForInterfaceOutput> rpcResult = result.get();
719             if (!rpcResult.isSuccessful()) {
720                 logger.warn("RPC Call to Get egress actions for interface {} returned with Errors {}",
721                             ifName, rpcResult.getErrors());
722             } else {
723                 List<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action> actions =
724                         rpcResult.getResult().getAction();
725                 listAction = actions;
726             }
727         } catch (InterruptedException | ExecutionException e) {
728             logger.warn("Exception when egress actions for interface {}", ifName, e);
729         }
730         return listAction;
731     }
732
733     private static void setupOrigDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
734             IMdsalApiManager mdsalApiManager, DataBroker broker) {
735         BigInteger dpId = interfaceInfo.getDpId();
736         String ifName = interfaceInfo.getInterfaceName();
737         long ifTag = interfaceInfo.getInterfaceTag();
738         String elanInstanceName = elanInfo.getElanInstanceName();
739         List<DpnInterfaces> elanDpns = getInvolvedDpnsInElan(elanInstanceName);
740         if (elanDpns != null) {
741             Long elanTag = elanInfo.getElanTag();
742             for (DpnInterfaces elanDpn : elanDpns) {
743                 if (elanDpn.getDpId().equals(dpId)) {
744                     // On the local DPN set up a direct output flow
745                     setupLocalDmacFlow(elanTag, dpId, ifName, macAddress, elanInstanceName, mdsalApiManager, ifTag);
746                     logger.debug("Dmac flow entry created for elan Name:{}, logical port Name:{} and mac address:{} on dpn:{}",
747                                  elanInstanceName, interfaceInfo.getPortName(), macAddress, dpId);
748                 } else {
749                     // Check for the Remote DPN present in Inventory Manager
750                     if (isDpnPresent(elanDpn.getDpId())) {
751                         // For remote DPNs a flow is needed to indicate that packets of this ELAN going to this MAC
752                         // need to be forwarded through the appropiated ITM tunnel
753                         setupRemoteDmacFlow(elanDpn.getDpId(),   // srcDpn (the remote DPN in this case)
754                                             dpId,                // dstDpn (the local DPN)
755                                             interfaceInfo.getInterfaceTag(), // lportTag of the local interface
756                                             elanTag,             // identifier of the Elan
757                                             macAddress,          // MAC to be programmed in remote DPN
758                                             elanInstanceName);
759                         logger.debug("Dmac flow entry created for elan Name:{}, logical port Name:{} and mac address:{} on dpn:{}",
760                                      elanInstanceName, interfaceInfo.getPortName(), macAddress, elanDpn.getDpId());
761                     }
762                 }
763             }
764
765             // TODO (eperefr): Make sure that the same is performed against the ElanDevices.
766         }
767     }
768
769     private static void setupOrigDmacFlowsonRemoteDpn(ElanInstance elanInfo, InterfaceInfo interfaceInfo, BigInteger dstDpId, String macAddress) {
770         BigInteger dpId = interfaceInfo.getDpId();
771         String elanInstanceName = elanInfo.getElanInstanceName();
772         List<DpnInterfaces> remoteFEs = getInvolvedDpnsInElan(elanInstanceName);
773         for(DpnInterfaces remoteFE: remoteFEs) {
774             Long elanTag = elanInfo.getElanTag();
775             if (remoteFE.getDpId().equals(dstDpId)) {
776                 // Check for the Remote DPN present in Inventory Manager
777                 setupRemoteDmacFlow(dstDpId, dpId, interfaceInfo.getInterfaceTag(), elanTag, macAddress, elanInstanceName);
778                 if (logger.isDebugEnabled()) {
779                     logger.debug("Dmac flow entry created for elan Name:{}, logical port Name:{} and mac address {} on dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, remoteFE.getDpId());
780                 }
781                 break;
782             }
783         }
784     }
785
786
787     @SuppressWarnings("unchecked")
788     public static List<DpnInterfaces> getInvolvedDpnsInElan(String elanName) {
789         List<DpnInterfaces> dpns = ElanInstanceManager.getElanInstanceManager().getElanDPNByName(elanName);
790         if (dpns == null) {
791             return EMPTY_LIST;
792         }
793         return dpns;
794     }
795
796     private static void setupLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
797                                            String displayName, IMdsalApiManager mdsalApiManager, long ifTag) {
798         Flow flowEntity = buildLocalDmacFlowEntry(elanTag, dpId, ifName, macAddress, displayName, ifTag);
799         mdsalApiManager.installFlow(dpId, flowEntity);
800
801     }
802
803     public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, long lporTag, String macAddress, long elanTag) {
804         return new StringBuffer().append(tableId).append(elanTag).append(dpId).append(lporTag).append(macAddress).toString();
805     }
806
807     public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, BigInteger remoteDpId, String macAddress, long elanTag) {
808         return new StringBuffer().append(tableId).append(elanTag).append(dpId).append(remoteDpId).append(macAddress).toString();
809     }
810
811     private static String getKnownDynamicmacFlowRef(short elanDmacTable, BigInteger dpId, String extDeviceNodeId,
812             String dstMacAddress, long elanTag, boolean shFlag) {
813         return new StringBuffer().append(elanDmacTable).append(elanTag).append(dpId)
814                                  .append(extDeviceNodeId).append(dstMacAddress).append(shFlag)
815                                  .toString();
816     }
817
818     /**
819      * Builds the flow to be programmed in the DMAC table of the local DPN (that is, where the MAC is attached to).
820      * This flow consists in:
821      *
822      *  Match:
823      *     + elanTag in metadata
824      *     + packet goes to a MAC locally attached
825      *  Actions:
826      *     + optionally, pop-vlan + set-vlan-id
827      *     + output to ifName's portNumber
828      *
829      * @param elanTag the elan tag
830      * @param dpId the dp id
831      * @param ifName the if name
832      * @param macAddress the mac address
833      * @param displayName the display name
834      * @param ifTag the if tag
835      * @return the flow
836      */
837     public static Flow buildLocalDmacFlowEntry(long elanTag, BigInteger dpId, String ifName, String macAddress,
838                                                String displayName, long ifTag) {
839         List<MatchInfo> mkMatches = new ArrayList<MatchInfo>();
840         mkMatches.add(new MatchInfo(MatchFieldType.metadata,
841                 new BigInteger[] { ElanUtils.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE }));
842         mkMatches.add(new MatchInfo(MatchFieldType.eth_dst, new String[] { macAddress }));
843
844         List<Instruction> mkInstructions = new ArrayList<Instruction>();
845         List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
846         mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
847         Flow flow = MDSALUtil.buildFlowNew(ElanConstants.ELAN_DMAC_TABLE,
848                 getKnownDynamicmacFlowRef(ElanConstants.ELAN_DMAC_TABLE, dpId, ifTag, macAddress, elanTag), 20,
849                 displayName, 0, 0, ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)), mkMatches,
850                 mkInstructions);
851
852         return flow;
853     }
854
855     public static void setupRemoteDmacFlow(BigInteger srcDpId, BigInteger destDpId, int lportTag, long elanTag, String macAddress,
856                                            String displayName) {
857         Flow flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTag, elanTag, macAddress, displayName);
858         mdsalMgr.installFlow(srcDpId, flowEntity);
859     }
860
861     /**
862      * Builds a Flow to be programmed in a remote DPN's DMAC table.
863      * This flow consists in:
864      *  Match:
865      *    + elanTag in packet's metadata
866      *    + packet going to a MAC known to be located in another DPN
867      *  Actions:
868      *    + set_tunnel_id(lportTag)
869      *    + output ITM internal tunnel interface with the other DPN
870      *
871      * @param srcDpId
872      * @param destDpId
873      * @param lportTag
874      * @param elanTag
875      * @param macAddress
876      * @param displayName
877      * @return
878      */
879     public static Flow buildRemoteDmacFlowEntry(BigInteger srcDpId, BigInteger destDpId, int lportTag, long elanTag,
880                                                  String macAddress, String displayName) {
881         List<MatchInfo> mkMatches = new ArrayList<MatchInfo>();
882         mkMatches.add(new MatchInfo(MatchFieldType.metadata,
883                                     new BigInteger[]{ ElanUtils.getElanMetadataLabel(elanTag),
884                                                       MetaDataUtil.METADATA_MASK_SERVICE }));
885         mkMatches.add(new MatchInfo(MatchFieldType.eth_dst, new String[] { macAddress }));
886
887         List<Instruction> mkInstructions = new ArrayList<Instruction>();
888
889         //List of Action for the provided Source and Destination DPIDs
890         try {
891             List<Action> actions = getInternalItmEgressAction(srcDpId, destDpId, lportTag);
892             mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
893         } catch (Exception e) {
894             logger.error("Interface Not Found exception");
895         }
896
897
898         Flow flow = MDSALUtil.buildFlowNew(ElanConstants.ELAN_DMAC_TABLE,
899                 getKnownDynamicmacFlowRef(ElanConstants.ELAN_DMAC_TABLE, srcDpId, destDpId, macAddress, elanTag),
900                 20,  /* prio */
901                 displayName, 0,   /* idleTimeout */
902                 0,   /* hardTimeout */
903                 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
904
905         return flow;
906
907     }
908
909     public static void deleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, MacEntry macEntry) {
910         if (elanInfo == null || interfaceInfo == null) {
911             return;
912         }
913         String macAddress = macEntry.getMacAddress().getValue();
914         synchronized (macAddress) {
915             logger.info("Acquired lock for mac : " + macAddress + "Proceeding with remove operation.");
916             deleteMacFlows(elanInfo, interfaceInfo,  macAddress, /* alsoDeleteSMAC */ true);
917         }
918     }
919
920     public static void deleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress, boolean deleteSmac) {
921         String elanInstanceName = elanInfo.getElanInstanceName();
922         long ifTag = interfaceInfo.getInterfaceTag();
923         List<DpnInterfaces> remoteFEs = getInvolvedDpnsInElan(elanInstanceName);
924         BigInteger srcdpId = interfaceInfo.getDpId();
925         for (DpnInterfaces dpnInterface: remoteFEs) {
926             Long elanTag = elanInfo.getElanTag();
927             BigInteger dstDpId = dpnInterface.getDpId();
928             if (dstDpId.equals(srcdpId)) {
929                 if(deleteSmac) {
930                     mdsalMgr.removeFlow(srcdpId, MDSALUtil.buildFlow(ElanConstants.ELAN_SMAC_TABLE,
931                             getKnownDynamicmacFlowRef(ElanConstants.ELAN_SMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)));
932                 }
933                 mdsalMgr.removeFlow(srcdpId, MDSALUtil.buildFlow(ElanConstants.ELAN_DMAC_TABLE,
934                         getKnownDynamicmacFlowRef(ElanConstants.ELAN_DMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)));
935                 RemoveTerminatingServiceActionsInput removeTerminatingServiceActionsInput = new RemoveTerminatingServiceActionsInputBuilder().setServiceId(interfaceInfo.getInterfaceTag()).setDpnId(srcdpId).build();
936                 itmRpcService.removeTerminatingServiceActions(removeTerminatingServiceActionsInput);
937                 if (logger.isDebugEnabled()) {
938                     logger.debug("All the required flows deleted for elan:{}, logical Interface port:{} and mac address:{} on dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, srcdpId);
939                 }
940             } else if (isDpnPresent(dstDpId)) {
941                 mdsalMgr.removeFlow(dstDpId, MDSALUtil.buildFlow(ElanConstants.ELAN_DMAC_TABLE,
942                         getKnownDynamicmacFlowRef(ElanConstants.ELAN_DMAC_TABLE, dstDpId, srcdpId, macAddress, elanTag)));
943                 if (logger.isDebugEnabled()) {
944                     logger.debug("Dmac flow entry deleted for elan:{}, logical interface port:{} and mac address:{} on dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, dstDpId);
945                 }
946             }
947         }
948     }
949
950     /**
951      * Updates the Elan information in the Operational DS. It also updates the
952      * ElanInstance in the Config DS by setting the adquired elanTag.
953      *
954      * @param broker
955      *            the broker
956      * @param idManager
957      *            the id manager
958      * @param elanInstanceAdded
959      *            the elan instance added
960      */
961     public static void updateOperationalDataStore(DataBroker broker, IdManagerService idManager,
962             ElanInstance elanInstanceAdded) {
963         String elanInstanceName = elanInstanceAdded.getElanInstanceName();
964         long elanTag = ElanUtils.retrieveNewElanTag(idManager, elanInstanceName);
965         Elan elanInfo = new ElanBuilder().setName(elanInstanceName).setKey(new ElanKey(elanInstanceName)).build();
966
967         //Add the ElanState in the elan-state operational data-store
968         MDSALUtil.syncWrite(broker, LogicalDatastoreType.OPERATIONAL,
969                 ElanUtils.getElanInstanceOperationalDataPath(elanInstanceName), elanInfo);
970
971         //Add the ElanMacTable in the elan-mac-table operational data-store
972         MacTable elanMacTable = new MacTableBuilder().setKey(new MacTableKey(elanInstanceName)).build();
973         MDSALUtil.syncWrite(broker, LogicalDatastoreType.OPERATIONAL,
974                 ElanUtils.getElanMacTableOperationalDataPath(elanInstanceName), elanMacTable);
975
976         ElanTagName elanTagName = new ElanTagNameBuilder().setElanTag(elanTag).setKey(new ElanTagNameKey(elanTag))
977                 .setName(elanInstanceName).build();
978
979         //Add the ElanTag to ElanName in the elan-tag-name Operational data-store
980         MDSALUtil.syncWrite(broker, LogicalDatastoreType.OPERATIONAL,
981                 ElanUtils.getElanInfoEntriesOperationalDataPath(elanTag), elanTagName);
982
983         // Updates the ElanInstance Config DS by setting the just adquired elanTag
984         ElanInstance elanInstanceWithTag = new ElanInstanceBuilder().setElanInstanceName(elanInstanceName)
985                 .setDescription(elanInstanceAdded.getDescription())
986                 .setMacTimeout(elanInstanceAdded.getMacTimeout() == null ?  ElanConstants.DEFAULT_MAC_TIME_OUT
987                         : elanInstanceAdded.getMacTimeout())
988                 .setKey(elanInstanceAdded.getKey()).setElanTag(elanTag).build();
989         MDSALUtil.syncUpdate(broker, LogicalDatastoreType.CONFIGURATION,
990                 getElanInstanceConfigurationDataPath(elanInstanceName), elanInstanceWithTag);
991     }
992
993     public static boolean isDpnPresent(BigInteger dpnId) {
994         String dpn = String.format("%s:%s", "openflow",dpnId);
995         NodeId nodeId = new NodeId(dpn);
996
997         InstanceIdentifier<Node> node = InstanceIdentifier.builder(Nodes.class).child(Node.class, new NodeKey(nodeId))
998                 .build();
999         Optional<Node> nodePresent = read(dataBroker, LogicalDatastoreType.OPERATIONAL, node);
1000         return (nodePresent.isPresent());
1001     }
1002
1003     public static ServicesInfo getServiceInfo(String elanInstanceName, long elanTag, String interfaceName) {
1004         int priority = ElanConstants.ELAN_SERVICE_PRIORITY;
1005         int instructionKey = 0;
1006         List<Instruction> instructions = new ArrayList<Instruction>();
1007         instructions.add(MDSALUtil.buildAndGetWriteMetadaInstruction(ElanUtils.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE, ++instructionKey));
1008         instructions.add(MDSALUtil.buildAndGetGotoTableInstruction(ElanConstants.ELAN_SMAC_TABLE, ++instructionKey));
1009
1010         ServicesInfo serviceInfo = InterfaceServiceUtil.buildServiceInfo(String.format("%s.%s", elanInstanceName, interfaceName), ElanConstants.ELAN_SERVICE_INDEX,
1011                 priority, ElanConstants.COOKIE_ELAN_INGRESS_TABLE, instructions);
1012         return serviceInfo;
1013     }
1014
1015     public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
1016             InstanceIdentifier<T> path, FutureCallback<Void> callback) {
1017         WriteTransaction tx = broker.newWriteOnlyTransaction();
1018         tx.delete(datastoreType, path);
1019         Futures.addCallback(tx.submit(), callback);
1020     }
1021
1022     public static <T extends DataObject> void syncWrite(DataBroker broker, LogicalDatastoreType datastoreType,
1023             InstanceIdentifier<T> path, T data) {
1024         WriteTransaction tx = broker.newWriteOnlyTransaction();
1025         tx.put(datastoreType, path, data, true);
1026         CheckedFuture<Void, TransactionCommitFailedException> futures = tx.submit();
1027         try {
1028             futures.get();
1029         } catch (InterruptedException | ExecutionException e) {
1030             logger.error("Error writing to datastore (path, data) : ({}, {})", path, data);
1031             throw new RuntimeException(e.getMessage());
1032         }
1033     }
1034
1035
1036     public static BoundServices getBoundServices(String serviceName, short servicePriority, int flowPriority,
1037             BigInteger cookie, List<Instruction> instructions) {
1038         StypeOpenflowBuilder augBuilder = new StypeOpenflowBuilder().setFlowCookie(cookie).setFlowPriority(flowPriority).setInstruction(instructions);
1039         return new BoundServicesBuilder().setKey(new BoundServicesKey(servicePriority))
1040                 .setServiceName(serviceName).setServicePriority(servicePriority)
1041                 .setServiceType(ServiceTypeFlowBased.class).addAugmentation(StypeOpenflow.class, augBuilder.build()).build();
1042     }
1043
1044     public static InstanceIdentifier<BoundServices> buildServiceId(String vpnInterfaceName, short serviceIndex) {
1045         return InstanceIdentifier.builder(ServiceBindings.class).child(ServicesInfo.class, new ServicesInfoKey(vpnInterfaceName))
1046                 .child(BoundServices.class, new BoundServicesKey(serviceIndex)).build();
1047     }
1048
1049     /**
1050      * Builds the list of actions to be taken when sending the packet over a
1051      * VxLan Tunnel Interface, such as setting the tunnel_id field, the vlanId
1052      * if proceeds and output the packet over the right port.
1053      *
1054      * @param tunnelIfaceName
1055      *            the tunnel iface name
1056      * @param tunnelKey
1057      *            the tunnel key
1058      * @return the list
1059      */
1060     public static List<Action> buildItmEgressActions(String tunnelIfaceName, Long tunnelKey) {
1061         List<Action> result = EMPTY_LIST;
1062         if (tunnelIfaceName != null && !tunnelIfaceName.isEmpty()) {
1063             GetEgressActionsForInterfaceInput getEgressActInput = new GetEgressActionsForInterfaceInputBuilder()
1064                     .setIntfName(tunnelIfaceName).setTunnelKey(tunnelKey).build();
1065
1066             Future<RpcResult<GetEgressActionsForInterfaceOutput>> egressActionsOutputFuture =
1067                     interfaceMgrRpcService.getEgressActionsForInterface(getEgressActInput);
1068             try {
1069                 if (egressActionsOutputFuture.get().isSuccessful()) {
1070                     GetEgressActionsForInterfaceOutput egressActionsOutput = egressActionsOutputFuture.get().getResult();
1071                     result = egressActionsOutput.getAction();
1072                 }
1073             } catch (InterruptedException | ExecutionException e) {
1074                 logger.error("Error in RPC call getEgressActionsForInterface {}", e);
1075             }
1076         }
1077
1078         if ( result == null || result.size() == 0 ) {
1079             logger.warn("Could not build Egress actions for interface {} and tunnelId {}", tunnelIfaceName, tunnelKey);
1080         }
1081         return result;
1082     }
1083
1084     /**
1085      * Builds the list of actions to be taken when sending the packet over an
1086      * external VxLan tunnel interface, such as stamping the VNI on the VxLAN
1087      * header, setting the vlanId if it proceeds and output the packet over the
1088      * right port.
1089      *
1090      * @param srcDpnId
1091      *            Dpn where the tunnelInterface is located
1092      * @param torNode
1093      *            NodeId of the ExternalDevice where the packet must be sent to.
1094      * @param vni
1095      *            Vni to be stamped on the VxLAN Header.
1096      * @return the external itm egress action
1097      */
1098     public static List<Action> getExternalItmEgressAction(BigInteger srcDpnId, NodeId torNode, long vni ) {
1099         List<Action> result = EMPTY_LIST;
1100
1101         GetExternalTunnelInterfaceNameInput input = new GetExternalTunnelInterfaceNameInputBuilder()
1102                 .setDestinationNode(torNode.getValue()).setSourceNode(srcDpnId.toString()).build();
1103         Future<RpcResult<GetExternalTunnelInterfaceNameOutput>> output =
1104                 itmRpcService.getExternalTunnelInterfaceName(input);
1105         try {
1106             if (output.get().isSuccessful()) {
1107                 GetExternalTunnelInterfaceNameOutput tunnelInterfaceNameOutput = output.get().getResult();
1108                 String tunnelIfaceName = tunnelInterfaceNameOutput.getInterfaceName();
1109                 if ( logger.isDebugEnabled() )
1110                     logger.debug("Received tunnelInterfaceName from getTunnelInterfaceName RPC {}", tunnelIfaceName);
1111
1112                 result = buildItmEgressActions(tunnelIfaceName, vni);
1113             }
1114
1115         } catch (InterruptedException | ExecutionException e) {
1116             logger.error("Error in RPC call getTunnelInterfaceName {}", e);
1117         }
1118
1119         return result;
1120     }
1121
1122     /**
1123      * Builds the list of actions to be taken when sending the packet over an
1124      * internal VxLan tunnel interface, such as setting the serviceTag on the
1125      * VNI field of the VxLAN header, setting the vlanId if it proceeds and
1126      * output the packet over the right port.
1127      *
1128      * @param sourceDpnId
1129      *            Dpn where the tunnelInterface is located
1130      * @param destinationDpnId
1131      *            Dpn where the packet must be sent to. It is used here in order
1132      *            to select the right tunnel interface.
1133      * @param serviceTag
1134      *            serviceId to be sent on the VxLAN header.
1135      * @return the internal itm egress action
1136      */
1137     public static List<Action> getInternalItmEgressAction(BigInteger sourceDpnId, BigInteger destinationDpnId,
1138             long serviceTag) {
1139         List<Action> result = EMPTY_LIST;
1140
1141         logger.debug("In getInternalItmEgressAction Action source {}, destination {}, elanTag {}",
1142                      sourceDpnId, destinationDpnId, serviceTag);
1143
1144         GetTunnelInterfaceNameInput input = new GetTunnelInterfaceNameInputBuilder()
1145                 .setDestinationDpid(destinationDpnId).setSourceDpid(sourceDpnId).build();
1146         Future<RpcResult<GetTunnelInterfaceNameOutput>> output = itmRpcService.getTunnelInterfaceName(input);
1147         try {
1148             if (output.get().isSuccessful()) {
1149                 GetTunnelInterfaceNameOutput tunnelInterfaceNameOutput = output.get().getResult();
1150                 String tunnelIfaceName = tunnelInterfaceNameOutput.getInterfaceName();
1151                 logger.debug("Received tunnelInterfaceName from getTunnelInterfaceName RPC {}", tunnelIfaceName);
1152
1153                 result = buildItmEgressActions(tunnelIfaceName, serviceTag);
1154             }
1155         } catch (InterruptedException | ExecutionException e) {
1156             logger.error("Error in RPC call getTunnelInterfaceName {}", e);
1157         }
1158
1159         return result;
1160     }
1161
1162     public static List<MatchInfo> getTunnelMatchesForServiceId(int elanTag) {
1163         List<MatchInfo> mkMatches = new ArrayList<MatchInfo>();
1164         // Matching metadata
1165         mkMatches.add(new MatchInfo(MatchFieldType.tunnel_id, new BigInteger[]{BigInteger.valueOf(elanTag)}));
1166
1167         return mkMatches;
1168     }
1169
1170     public static void removeTerminatingServiceAction(BigInteger destDpId, int serviceId) {
1171         RemoveTerminatingServiceActionsInput input = new RemoveTerminatingServiceActionsInputBuilder().setDpnId(destDpId).setServiceId(serviceId).build();
1172         Future<RpcResult<Void>> futureObject = itmRpcService.removeTerminatingServiceActions(input);
1173         try {
1174             RpcResult<Void> result = futureObject.get();
1175             if (result.isSuccessful()) {
1176                 logger.debug("Successfully completed removeTerminatingServiceActions");
1177             } else {
1178                 logger.debug("Failure in removeTerminatingServiceAction RPC call");
1179             }
1180         } catch (InterruptedException | ExecutionException e) {
1181             logger.error("Error in RPC call removeTerminatingServiceActions {}", e);
1182         }
1183     }
1184
1185     public static void createTerminatingServiceActions(BigInteger destDpId, int serviceId, List<Action> actions) {
1186         List<Instruction> mkInstructions = new ArrayList<Instruction>();
1187         mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
1188         CreateTerminatingServiceActionsInput input = new CreateTerminatingServiceActionsInputBuilder().setDpnId(destDpId).setServiceId(serviceId).setInstruction(mkInstructions).build();
1189
1190         itmRpcService.createTerminatingServiceActions(input);
1191     }
1192
1193     public static TunnelList buildInternalTunnel(DataBroker broker) {
1194         InstanceIdentifier<TunnelList> tunnelListInstanceIdentifier = InstanceIdentifier.builder(TunnelList.class).build();
1195         Optional<TunnelList> tunnelList = read(broker, LogicalDatastoreType.CONFIGURATION, tunnelListInstanceIdentifier);
1196         if (tunnelList.isPresent()) {
1197             return tunnelList.get();
1198         }
1199         return null;
1200     }
1201
1202     /**
1203      * Installs a Flow in a DPN's DMAC table. The Flow is for a MAC that is
1204      * connected remotely in another CSS and accessible through an internal
1205      * tunnel. It also installs the flow for dropping the packet if it came over
1206      * an ITM tunnel (that is, if the Split-Horizon flag is set)
1207      *
1208      * @param localDpId
1209      *            Id of the DPN where the MAC Addr is accessible locally
1210      * @param remoteDpId
1211      *            Id of the DPN where the flow must be installed
1212      * @param lportTag
1213      *            lportTag of the interface where the mac is connected to.
1214      * @param elanTag
1215      *            Identifier of the ELAN
1216      * @param macAddress
1217      *            MAC to be installed in remoteDpId's DMAC table
1218      * @param displayName
1219      *            the display name
1220      */
1221     public static void installDmacFlowsToInternalRemoteMac(BigInteger localDpId, BigInteger remoteDpId, long lportTag,
1222             long elanTag, String macAddress, String displayName) {
1223         Flow flow = buildDmacFlowForInternalRemoteMac(localDpId, remoteDpId, lportTag, elanTag, macAddress, displayName);
1224         mdsalMgr.installFlow(remoteDpId, flow);
1225     }
1226
1227     /**
1228      * Installs a Flow in the specified DPN's DMAC table. The flow is for a MAC
1229      * that is connected remotely in an External Device (TOR) and that is
1230      * accessible through an external tunnel. It also installs the flow for
1231      * dropping the packet if it came over an ITM tunnel (that is, if the
1232      * Split-Horizon flag is set)
1233      *
1234      * @param dpnId
1235      *            Id of the DPN where the flow must be installed
1236      * @param extDeviceNodeId
1237      *            the ext device node id
1238      * @param elanTag
1239      *            the elan tag
1240      * @param vni
1241      *            the vni
1242      * @param macAddress
1243      *            the mac address
1244      * @param displayName
1245      *            the display name
1246      */
1247     public static List<ListenableFuture<Void>> installDmacFlowsToExternalRemoteMac(BigInteger dpnId,
1248             String extDeviceNodeId, Long elanTag, Long vni, String macAddress, String displayName) {
1249         List<ListenableFuture<Void>> futures = new ArrayList<>();
1250         synchronized (macAddress) {
1251             Flow flow = buildDmacFlowForExternalRemoteMac(dpnId, extDeviceNodeId, elanTag, vni, macAddress, displayName);
1252             futures.add(mdsalMgr.installFlow(dpnId, flow));
1253
1254             Flow dropFlow = buildDmacFlowDropIfPacketComingFromTunnel(dpnId, extDeviceNodeId, elanTag, macAddress);
1255             futures.add(mdsalMgr.installFlow(dpnId, dropFlow));
1256         }
1257         return futures;
1258     }
1259
1260     public static List<MatchInfo> buildMatchesForElanTagShFlagAndDstMac(long elanTag, boolean shFlag, String macAddr) {
1261         List<MatchInfo> mkMatches = new ArrayList<MatchInfo>();
1262         mkMatches.add(new MatchInfo(MatchFieldType.metadata, new BigInteger[] {
1263                 ElanUtils.getElanMetadataLabel(elanTag, shFlag), MetaDataUtil.METADATA_MASK_SERVICE_SH_FLAG }));
1264         mkMatches.add(new MatchInfo(MatchFieldType.eth_dst, new String[] { macAddr }));
1265
1266         return mkMatches;
1267     }
1268
1269     /**
1270      * Builds a Flow to be programmed in a DPN's DMAC table. This method must be used when the MAC is located in an
1271      * External Device (TOR).
1272      * The flow matches on the specified MAC and
1273      *   1) sends the packet over the CSS-TOR tunnel if SHFlag is not set, or
1274      *   2) drops it if SHFlag is set (what means the packet came from an external tunnel)
1275      *
1276      * @param dpId DPN whose DMAC table is going to be modified
1277      * @param extDeviceNodeId Hwvtep node where the mac is attached to
1278      * @param elanTag ElanId to which the MAC is being added to
1279      * @param vni the vni
1280      * @param dstMacAddress The mac address to be programmed
1281      * @param displayName the display name
1282      * @return the flow
1283      */
1284     public static Flow buildDmacFlowForExternalRemoteMac(BigInteger dpId, String extDeviceNodeId, long elanTag,
1285             Long vni, String dstMacAddress, String displayName ) {
1286         List<MatchInfo> mkMatches = buildMatchesForElanTagShFlagAndDstMac(elanTag, /*shFlag*/ false, dstMacAddress);
1287         List<Instruction> mkInstructions = new ArrayList<Instruction>();
1288         try {
1289             List<Action> actions = getExternalItmEgressAction(dpId, new NodeId(extDeviceNodeId), vni);
1290             mkInstructions.add( MDSALUtil.buildApplyActionsInstruction(actions) );
1291         } catch (Exception e) {
1292             logger.error("Could not get Egress Actions for DpId={}  externalNode={}", dpId, extDeviceNodeId );
1293         }
1294
1295         Flow flow = MDSALUtil.buildFlowNew(ElanConstants.ELAN_DMAC_TABLE,
1296                 getKnownDynamicmacFlowRef(ElanConstants.ELAN_DMAC_TABLE, dpId, extDeviceNodeId, dstMacAddress, elanTag,
1297                         false),
1298                 20,  /* prio */
1299                 displayName, 0,   /* idleTimeout */
1300                 0,   /* hardTimeout */
1301                 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
1302
1303         return flow;
1304     }
1305
1306     /**
1307      * Builds the flow that drops the packet if it came through an external tunnel, that is, if the Split-Horizon
1308      * flag is set.
1309      *
1310      * @param dpnId DPN whose DMAC table is going to be modified
1311      * @param extDeviceNodeId  Hwvtep node where the mac is attached to
1312      * @param elanTag ElanId to which the MAC is being added to
1313      * @param dstMacAddress The mac address to be programmed
1314      * @param displayName
1315      * @return
1316      */
1317     private static Flow buildDmacFlowDropIfPacketComingFromTunnel(BigInteger dpnId, String extDeviceNodeId,
1318             Long elanTag, String dstMacAddress) {
1319         List<MatchInfo> mkMatches = buildMatchesForElanTagShFlagAndDstMac(elanTag, /*shFlag*/ true, dstMacAddress);
1320         List<Instruction> mkInstructions = MDSALUtil.buildInstructionsDrop();
1321         String flowId = getKnownDynamicmacFlowRef(ElanConstants.ELAN_DMAC_TABLE, dpnId, extDeviceNodeId, dstMacAddress,
1322                 elanTag, true);
1323         Flow flow = MDSALUtil.buildFlowNew(ElanConstants.ELAN_DMAC_TABLE, flowId, 20,  /* prio */
1324                 "Drop", 0,   /* idleTimeout */
1325                 0,   /* hardTimeout */
1326                 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
1327
1328         return flow;
1329     }
1330
1331     private static String getDmacDropFlowId(Long elanTag, String dstMacAddress) {
1332         return new StringBuilder(ElanConstants.ELAN_DMAC_TABLE).append(elanTag).append(dstMacAddress).append("Drop")
1333                 .toString();
1334     }
1335
1336     /**
1337      * Builds a Flow to be programmed in a remote DPN's DMAC table. This method must be used when the MAC is located
1338      * in another CSS.
1339      *
1340      * This flow consists in:
1341      *  Match:
1342      *    + elanTag in packet's metadata
1343      *    + packet going to a MAC known to be located in another DPN
1344      *  Actions:
1345      *    + set_tunnel_id(lportTag)
1346      *    + output on ITM internal tunnel interface with the other DPN
1347      *
1348      * @param localDpId the local dp id
1349      * @param remoteDpId the remote dp id
1350      * @param lportTag the lport tag
1351      * @param elanTag the elan tag
1352      * @param macAddress the mac address
1353      * @param displayName the display name
1354      * @return the flow
1355      */
1356     public static Flow buildDmacFlowForInternalRemoteMac(BigInteger localDpId, BigInteger remoteDpId, long lportTag,
1357             long elanTag, String macAddress, String displayName) {
1358         List<MatchInfo> mkMatches = buildMatchesForElanTagShFlagAndDstMac(elanTag, /*shFlag*/ false, macAddress);
1359
1360         List<Instruction> mkInstructions = new ArrayList<Instruction>();
1361
1362         try {
1363             //List of Action for the provided Source and Destination DPIDs
1364             List<Action> actions = getInternalItmEgressAction(localDpId, remoteDpId, lportTag);
1365             mkInstructions.add( MDSALUtil.buildApplyActionsInstruction(actions) );
1366         } catch (Exception e) {
1367             logger.error("Could not get Egress Actions for localDpId={}  remoteDpId={}   lportTag={}",
1368                          localDpId, remoteDpId, lportTag);
1369         }
1370
1371         Flow flow = MDSALUtil.buildFlowNew(ElanConstants.ELAN_DMAC_TABLE,
1372                 getKnownDynamicmacFlowRef(ElanConstants.ELAN_DMAC_TABLE, localDpId, remoteDpId, macAddress, elanTag),
1373                 20,  /* prio */
1374                 displayName, 0,   /* idleTimeout */
1375                 0,   /* hardTimeout */
1376                 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
1377
1378         return flow;
1379
1380     }
1381
1382     /**
1383      * Installs or removes flows in DMAC table for MACs that are/were located in
1384      * an external Elan Device.
1385      *
1386      * @param dpId
1387      *            Id of the DPN where the DMAC table is going to be modified
1388      * @param extNodeId
1389      *            Id of the External Device where the MAC is located
1390      * @param elanTag
1391      *            Id of the ELAN
1392      * @param vni
1393      *            VNI of the LogicalSwitch to which the MAC belongs to, and that
1394      *            is associated with the ELAN
1395      * @param macAddress
1396      *            the mac address
1397      * @param elanInstanceName
1398      *            the elan instance name
1399      * @param addOrRemove
1400      *            Indicates if flows must be installed or removed.
1401      * @see org.opendaylight.vpnservice.mdsalutil.MDSALUtil.MdsalOp
1402      */
1403     public static void setupDmacFlowsToExternalRemoteMac(BigInteger dpId, String extNodeId, Long elanTag, Long vni,
1404             String macAddress, String elanInstanceName, MdsalOp addOrRemove) {
1405         if ( addOrRemove == MdsalOp.CREATION_OP ) {
1406             ElanUtils.installDmacFlowsToExternalRemoteMac(dpId, extNodeId, elanTag, vni, macAddress, elanInstanceName);
1407         } else if ( addOrRemove == MdsalOp.REMOVAL_OP ) {
1408             ElanUtils.deleteDmacFlowsToExternalMac(elanTag, dpId, extNodeId, macAddress );
1409         }
1410     }
1411
1412     /**
1413      * Delete dmac flows to external mac.
1414      *
1415      * @param elanTag
1416      *            the elan tag
1417      * @param dpId
1418      *            the dp id
1419      * @param extDeviceNodeId
1420      *            the ext device node id
1421      * @param macToRemove
1422      *            the mac to remove
1423      */
1424     public static List<ListenableFuture<Void>> deleteDmacFlowsToExternalMac(long elanTag, BigInteger dpId,
1425             String extDeviceNodeId, String macToRemove ) {
1426         List<ListenableFuture<Void>> futures = new ArrayList<>();
1427         synchronized (macToRemove) {
1428             // Removing the flows that sends the packet on an external tunnel
1429             String flowId = getKnownDynamicmacFlowRef(ElanConstants.ELAN_DMAC_TABLE, dpId, extDeviceNodeId,
1430                     macToRemove, elanTag, false);
1431             Flow flowToRemove = new FlowBuilder().setId(new FlowId(flowId)).setTableId(ElanConstants.ELAN_DMAC_TABLE)
1432                     .build();
1433             futures.add(mdsalMgr.removeFlow(dpId, flowToRemove));
1434
1435             // And now removing the drop flow
1436             flowId = getKnownDynamicmacFlowRef(ElanConstants.ELAN_DMAC_TABLE, dpId, extDeviceNodeId, macToRemove,
1437                     elanTag, true);
1438             flowToRemove = new FlowBuilder().setId(new FlowId(flowId)).setTableId(ElanConstants.ELAN_DMAC_TABLE)
1439                     .build();
1440             futures.add(mdsalMgr.removeFlow(dpId, flowToRemove));
1441         }
1442         return futures;
1443     }
1444
1445     /**
1446      * Gets the dpid from interface.
1447      *
1448      * @param interfaceName
1449      *            the interface name
1450      * @return the dpid from interface
1451      */
1452     public static BigInteger getDpidFromInterface(String interfaceName) {
1453         BigInteger dpId = null;
1454         Future<RpcResult<GetDpidFromInterfaceOutput>> output = interfaceMgrRpcService
1455                 .getDpidFromInterface(new GetDpidFromInterfaceInputBuilder().setIntfName(interfaceName).build());
1456         try {
1457             RpcResult<GetDpidFromInterfaceOutput> rpcResult = output.get();
1458             if (rpcResult.isSuccessful()) {
1459                 dpId = rpcResult.getResult().getDpid();
1460             }
1461         } catch (NullPointerException | InterruptedException | ExecutionException e) {
1462             logger.error("Failed to get the DPN ID: {} for interface {}: {} ", dpId, interfaceName, e);
1463         }
1464         return dpId;
1465     }
1466
1467 }
1468