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