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