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