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