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