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