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