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