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