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