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