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