Refactor ElanUtil interface maps to a non-static singleton
[netvirt.git] / elanmanager / impl / src / main / java / org / opendaylight / netvirt / elan / utils / ElanUtils.java
1 /*
2  * Copyright © 2016, 2017 Ericsson India Global Services Pvt Ltd. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.netvirt.elan.utils;
9
10 import com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Strings;
13 import com.google.common.collect.Lists;
14 import com.google.common.primitives.Ints;
15 import com.google.common.util.concurrent.CheckedFuture;
16 import com.google.common.util.concurrent.FutureCallback;
17 import com.google.common.util.concurrent.Futures;
18 import com.google.common.util.concurrent.ListenableFuture;
19 import com.google.common.util.concurrent.MoreExecutors;
20 import java.math.BigInteger;
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.Collections;
24 import java.util.List;
25 import java.util.concurrent.ExecutionException;
26 import java.util.concurrent.Future;
27 import javax.annotation.Nonnull;
28 import javax.annotation.Nullable;
29 import javax.inject.Inject;
30 import javax.inject.Singleton;
31 import org.apache.commons.lang3.StringUtils;
32 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
33 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
34 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
35 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
36 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
37 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
38 import org.opendaylight.genius.interfacemanager.globals.InterfaceInfo;
39 import org.opendaylight.genius.interfacemanager.globals.InterfaceServiceUtil;
40 import org.opendaylight.genius.interfacemanager.interfaces.IInterfaceManager;
41 import org.opendaylight.genius.itm.globals.ITMConstants;
42 import org.opendaylight.genius.mdsalutil.ActionInfo;
43 import org.opendaylight.genius.mdsalutil.FlowEntity;
44 import org.opendaylight.genius.mdsalutil.FlowEntityBuilder;
45 import org.opendaylight.genius.mdsalutil.InstructionInfo;
46 import org.opendaylight.genius.mdsalutil.MDSALUtil;
47 import org.opendaylight.genius.mdsalutil.MatchInfo;
48 import org.opendaylight.genius.mdsalutil.MetaDataUtil;
49 import org.opendaylight.genius.mdsalutil.NWUtil;
50 import org.opendaylight.genius.mdsalutil.NwConstants;
51 import org.opendaylight.genius.mdsalutil.actions.ActionNxResubmit;
52 import org.opendaylight.genius.mdsalutil.instructions.InstructionApplyActions;
53 import org.opendaylight.genius.mdsalutil.instructions.InstructionGotoTable;
54 import org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager;
55 import org.opendaylight.genius.mdsalutil.matches.MatchEthernetDestination;
56 import org.opendaylight.genius.mdsalutil.matches.MatchEthernetSource;
57 import org.opendaylight.genius.mdsalutil.matches.MatchMetadata;
58 import org.opendaylight.genius.mdsalutil.matches.MatchTunnelId;
59 import org.opendaylight.genius.mdsalutil.packet.ARP;
60 import org.opendaylight.genius.mdsalutil.packet.Ethernet;
61 import org.opendaylight.genius.mdsalutil.packet.IPv4;
62 import org.opendaylight.infrautils.utils.concurrent.JdkFutures;
63 import org.opendaylight.netvirt.elan.ElanException;
64 import org.opendaylight.netvirt.elan.arp.responder.ArpResponderUtil;
65 import org.opendaylight.netvirt.elan.cache.ElanInterfaceCache;
66 import org.opendaylight.netvirt.elanmanager.api.ElanHelper;
67 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
68 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddressBuilder;
69 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfacesState;
70 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface;
71 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.AdminStatus;
72 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.OperStatus;
73 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
74 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.PhysAddress;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInput;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInputBuilder;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdOutput;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdManagerService;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInput;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInputBuilder;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406.IfIndexesInterfaceMap;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._if.indexes._interface.map.IfIndexInterface;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._if.indexes._interface.map.IfIndexInterfaceKey;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfTunnel;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.ParentRefs;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeBase;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeVxlan;
96 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceInput;
97 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceInputBuilder;
98 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceOutput;
99 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.OdlInterfaceRpcService;
100 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceBindings;
101 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceModeIngress;
102 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceTypeFlowBased;
103 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflow;
104 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflowBuilder;
105 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.ServicesInfo;
106 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.ServicesInfoKey;
107 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServices;
108 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesBuilder;
109 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesKey;
110 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.ExternalTunnelList;
111 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnel;
112 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnelKey;
113 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.ItmRpcService;
114 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsInput;
115 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsInputBuilder;
116 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
117 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
118 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
119 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
120 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
121 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.config.rev150710.ElanConfig;
122 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInstance;
123 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInstanceBuilder;
124 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInterface;
125 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInterface.EtreeInterfaceType;
126 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTag;
127 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTagName;
128 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTagNameBuilder;
129 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanDpnInterfaces;
130 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanForwardingTables;
131 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInstances;
132 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaceForwardingEntries;
133 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaces;
134 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanState;
135 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanTagNameMap;
136 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeFlat;
137 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeVlan;
138 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeVxlan;
139 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan._interface.forwarding.entries.ElanInterfaceMac;
140 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan._interface.forwarding.entries.ElanInterfaceMacKey;
141 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesList;
142 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesListKey;
143 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfaces;
144 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfacesKey;
145 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTable;
146 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTableBuilder;
147 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTableKey;
148 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstance;
149 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstanceBuilder;
150 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.elan.instance.ElanSegments;
151 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterface;
152 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterfaceKey;
153 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntries;
154 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntriesBuilder;
155 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntriesKey;
156 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.Elan;
157 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.ElanBuilder;
158 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.ElanKey;
159 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagName;
160 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagNameBuilder;
161 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagNameKey;
162 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntry;
163 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntryKey;
164 import org.opendaylight.yangtools.yang.binding.DataObject;
165 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
166 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.InstanceIdentifierBuilder;
167 import org.opendaylight.yangtools.yang.common.RpcResult;
168 import org.slf4j.Logger;
169 import org.slf4j.LoggerFactory;
170
171 @Singleton
172 public class ElanUtils {
173
174     private static final Logger LOG = LoggerFactory.getLogger(ElanUtils.class);
175
176     private final DataBroker broker;
177     private final IMdsalApiManager mdsalManager;
178     private final OdlInterfaceRpcService interfaceManagerRpcService;
179     private final ItmRpcService itmRpcService;
180     private final IInterfaceManager interfaceManager;
181     private final ElanConfig elanConfig;
182     private final ElanItmUtils elanItmUtils;
183     private final ElanEtreeUtils elanEtreeUtils;
184     private final ElanInterfaceCache elanInterfaceCache;
185
186     public static final FutureCallback<Void> DEFAULT_CALLBACK = new FutureCallback<Void>() {
187         @Override
188         public void onSuccess(Void result) {
189             LOG.debug("Success in Datastore operation");
190         }
191
192         @Override
193         public void onFailure(Throwable error) {
194             LOG.error("Error in Datastore operation", error);
195         }
196     };
197
198     @Inject
199     public ElanUtils(DataBroker dataBroker, IMdsalApiManager mdsalManager,
200             OdlInterfaceRpcService interfaceManagerRpcService, ItmRpcService itmRpcService, ElanConfig elanConfig,
201             IInterfaceManager interfaceManager, ElanEtreeUtils elanEtreeUtils, ElanItmUtils elanItmUtils,
202             ElanInterfaceCache elanInterfaceCache) {
203         this.broker = dataBroker;
204         this.mdsalManager = mdsalManager;
205         this.interfaceManagerRpcService = interfaceManagerRpcService;
206         this.itmRpcService = itmRpcService;
207         this.interfaceManager = interfaceManager;
208         this.elanConfig = elanConfig;
209         this.elanEtreeUtils = elanEtreeUtils;
210         this.elanItmUtils = elanItmUtils;
211         this.elanInterfaceCache = elanInterfaceCache;
212     }
213
214     public final Boolean isOpenstackVniSemanticsEnforced() {
215         return elanConfig.isOpenstackVniSemanticsEnforced() != null
216                 ? elanConfig.isOpenstackVniSemanticsEnforced() : false;
217     }
218
219     /**
220      * Uses the IdManager to retrieve a brand new ElanTag.
221      *
222      * @param idManager
223      *            the id manager
224      * @param idKey
225      *            the id key
226      * @return the integer
227      */
228     public static Long retrieveNewElanTag(IdManagerService idManager, String idKey) {
229
230         AllocateIdInput getIdInput = new AllocateIdInputBuilder().setPoolName(ElanConstants.ELAN_ID_POOL_NAME)
231                 .setIdKey(idKey).build();
232
233         try {
234             Future<RpcResult<AllocateIdOutput>> result = idManager.allocateId(getIdInput);
235             RpcResult<AllocateIdOutput> rpcResult = result.get();
236             if (rpcResult.isSuccessful()) {
237                 return rpcResult.getResult().getIdValue();
238             } else {
239                 LOG.warn("RPC Call to Allocate Id returned with Errors {}", rpcResult.getErrors());
240             }
241         } catch (InterruptedException | ExecutionException e) {
242             LOG.warn("Exception when Allocating Id", e);
243         }
244         return 0L;
245     }
246
247     public static void releaseId(IdManagerService idManager, String poolName, String idKey) {
248         ReleaseIdInput releaseIdInput = new ReleaseIdInputBuilder().setPoolName(poolName).setIdKey(idKey).build();
249         JdkFutures.addErrorLogging(idManager.releaseId(releaseIdInput), LOG, "Release Id");
250     }
251
252     /**
253      * Read utility.
254      *
255      * @deprecated Consider using {@link #read2(LogicalDatastoreType, InstanceIdentifier)} with proper exception
256      *             handling instead
257      * @param broker dataBroker
258      * @param datastoreType Logical DataStore type
259      * @param path IID to read
260      * @param <T> T extends DataObject
261      * @return the read value T
262      */
263     @Deprecated
264     @SuppressWarnings("checkstyle:IllegalCatch")
265     public static <T extends DataObject> Optional<T> read(@Nonnull DataBroker broker,
266             LogicalDatastoreType datastoreType, InstanceIdentifier<T> path) {
267         try (ReadOnlyTransaction tx = broker.newReadOnlyTransaction()) {
268             return tx.read(datastoreType, path).get();
269         } catch (Exception e) {
270             throw new RuntimeException(e);
271         }
272     }
273
274     public <T extends DataObject> Optional<T> read2(LogicalDatastoreType datastoreType, InstanceIdentifier<T> path)
275             throws ReadFailedException {
276         try (ReadOnlyTransaction tx = broker.newReadOnlyTransaction()) {
277             CheckedFuture<Optional<T>, ReadFailedException> checkedFuture = tx.read(datastoreType, path);
278             return checkedFuture.checkedGet();
279         }
280     }
281
282     public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
283             InstanceIdentifier<T> path) {
284         WriteTransaction tx = broker.newWriteOnlyTransaction();
285         tx.delete(datastoreType, path);
286         Futures.addCallback(tx.submit(), DEFAULT_CALLBACK, MoreExecutors.directExecutor());
287     }
288
289     public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
290             InstanceIdentifier<T> path, FutureCallback<Void> callback) {
291         WriteTransaction tx = broker.newWriteOnlyTransaction();
292         tx.delete(datastoreType, path);
293         Futures.addCallback(tx.submit(), callback, MoreExecutors.directExecutor());
294     }
295
296     public static InstanceIdentifier<ElanInstance> getElanInstanceIdentifier() {
297         return InstanceIdentifier.builder(ElanInstances.class).child(ElanInstance.class).build();
298     }
299
300     public static InstanceIdentifier<ElanInterface> getElanInterfaceConfigurationDataPathId(String interfaceName) {
301         return InstanceIdentifier.builder(ElanInterfaces.class)
302                 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).build();
303     }
304
305     // elan-state Operational container
306     public static Elan getElanByName(DataBroker broker, String elanInstanceName) {
307         InstanceIdentifier<Elan> elanIdentifier = getElanInstanceOperationalDataPath(elanInstanceName);
308         return MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL, elanIdentifier).orNull();
309     }
310
311     public static InstanceIdentifier<Elan> getElanInstanceOperationalDataPath(String elanInstanceName) {
312         return InstanceIdentifier.builder(ElanState.class).child(Elan.class, new ElanKey(elanInstanceName)).build();
313     }
314
315     // grouping of forwarding-entries
316     public MacEntry getInterfaceMacEntriesOperationalDataPath(String interfaceName, PhysAddress physAddress) {
317         InstanceIdentifier<MacEntry> existingMacEntryId = getInterfaceMacEntriesIdentifierOperationalDataPath(
318                 interfaceName, physAddress);
319         return read(broker, LogicalDatastoreType.OPERATIONAL, existingMacEntryId).orNull();
320     }
321
322     public MacEntry getInterfaceMacEntriesOperationalDataPathFromId(InstanceIdentifier identifier) {
323         Optional<MacEntry> existingInterfaceMacEntry = read(broker,
324                 LogicalDatastoreType.OPERATIONAL, identifier);
325         return existingInterfaceMacEntry.orNull();
326     }
327
328     public static InstanceIdentifier<MacEntry> getInterfaceMacEntriesIdentifierOperationalDataPath(String interfaceName,
329             PhysAddress physAddress) {
330         return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class)
331                 .child(ElanInterfaceMac.class, new ElanInterfaceMacKey(interfaceName))
332                 .child(MacEntry.class, new MacEntryKey(physAddress)).build();
333
334     }
335
336     // elan-forwarding-tables Operational container
337     public Optional<MacEntry> getMacEntryForElanInstance(String elanName, PhysAddress physAddress) {
338         InstanceIdentifier<MacEntry> macId = getMacEntryOperationalDataPath(elanName, physAddress);
339         return read(broker, LogicalDatastoreType.OPERATIONAL, macId);
340     }
341
342     public MacEntry getMacEntryFromElanMacId(InstanceIdentifier identifier) {
343         Optional<MacEntry> existingInterfaceMacEntry = read(broker,
344                 LogicalDatastoreType.OPERATIONAL, identifier);
345         return existingInterfaceMacEntry.orNull();
346     }
347
348     public static InstanceIdentifier<MacEntry> getMacEntryOperationalDataPath(String elanName,
349             PhysAddress physAddress) {
350         return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class, new MacTableKey(elanName))
351                 .child(MacEntry.class, new MacEntryKey(physAddress)).build();
352     }
353
354     public static InstanceIdentifier<MacTable> getElanMacTableOperationalDataPath(String elanName) {
355         return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class, new MacTableKey(elanName))
356                 .build();
357     }
358
359     // elan-interface-forwarding-entries Operational container
360     public ElanInterfaceMac getElanInterfaceMacByInterfaceName(String interfaceName) {
361         return getElanInterfaceMacByInterfaceName(broker, interfaceName);
362     }
363
364     @Nullable
365     public static ElanInterfaceMac getElanInterfaceMacByInterfaceName(DataBroker dataBroker, String interfaceName) {
366         InstanceIdentifier<ElanInterfaceMac> elanInterfaceId = getElanInterfaceMacEntriesOperationalDataPath(
367                 interfaceName);
368         return read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanInterfaceId).orNull();
369     }
370
371     /**
372      * Gets the elan interface mac addresses.
373      *
374      * @param interfaceName
375      *            the interface name
376      * @return the elan interface mac addresses
377      */
378     public List<PhysAddress> getElanInterfaceMacAddresses(String interfaceName) {
379         List<PhysAddress> macAddresses = new ArrayList<>();
380         ElanInterfaceMac elanInterfaceMac = getElanInterfaceMacByInterfaceName(interfaceName);
381         if (elanInterfaceMac != null && elanInterfaceMac.getMacEntry() != null) {
382             List<MacEntry> macEntries = elanInterfaceMac.getMacEntry();
383             for (MacEntry macEntry : macEntries) {
384                 macAddresses.add(macEntry.getMacAddress());
385             }
386         }
387         return macAddresses;
388     }
389
390     public static InstanceIdentifier<ElanInterfaceMac> getElanInterfaceMacEntriesOperationalDataPath(
391             String interfaceName) {
392         return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class)
393                 .child(ElanInterfaceMac.class, new ElanInterfaceMacKey(interfaceName)).build();
394     }
395
396     /**
397      * Returns the list of Interfaces that belong to an Elan on an specific DPN.
398      * Data retrieved from Elan's operational DS: elan-dpn-interfaces container
399      *
400      * @param elanInstanceName
401      *            name of the Elan to which the interfaces must belong to
402      * @param dpId
403      *            Id of the DPN where the interfaces are located
404      * @return the elan interface Info
405      */
406     public DpnInterfaces getElanInterfaceInfoByElanDpn(String elanInstanceName, BigInteger dpId) {
407         InstanceIdentifier<DpnInterfaces> elanDpnInterfacesId = getElanDpnInterfaceOperationalDataPath(elanInstanceName,
408                 dpId);
409         return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfacesId).orNull();
410     }
411
412     /**
413      * Returns the InstanceIdentifier that points to the Interfaces of an Elan
414      * in a given DPN in the Operational DS. Data retrieved from Elans's
415      * operational DS: dpn-interfaces list
416      *
417      * @param elanInstanceName
418      *            name of the Elan to which the interfaces must belong to
419      * @param dpId
420      *            Id of the DPN where the interfaces are located
421      * @return the elan dpn interface
422      */
423     public static InstanceIdentifier<DpnInterfaces> getElanDpnInterfaceOperationalDataPath(String elanInstanceName,
424             BigInteger dpId) {
425         return InstanceIdentifier.builder(ElanDpnInterfaces.class)
426                 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName))
427                 .child(DpnInterfaces.class, new DpnInterfacesKey(dpId)).build();
428     }
429
430     // elan-tag-name-map Operational Container
431     public ElanTagName getElanInfoByElanTag(long elanTag) {
432         InstanceIdentifier<ElanTagName> elanId = getElanInfoEntriesOperationalDataPath(elanTag);
433         Optional<ElanTagName> existingElanInfo = read(broker,
434                 LogicalDatastoreType.OPERATIONAL, elanId);
435         return existingElanInfo.orNull();
436     }
437
438     public static InstanceIdentifier<ElanTagName> getElanInfoEntriesOperationalDataPath(long elanTag) {
439         return InstanceIdentifier.builder(ElanTagNameMap.class).child(ElanTagName.class, new ElanTagNameKey(elanTag))
440                 .build();
441     }
442
443     // interface-index-tag operational container
444     public Optional<IfIndexInterface> getInterfaceInfoByInterfaceTag(long interfaceTag) {
445         InstanceIdentifier<IfIndexInterface> interfaceId = getInterfaceInfoEntriesOperationalDataPath(interfaceTag);
446         return read(broker, LogicalDatastoreType.OPERATIONAL, interfaceId);
447     }
448
449     public static InstanceIdentifier<IfIndexInterface> getInterfaceInfoEntriesOperationalDataPath(long interfaceTag) {
450         return InstanceIdentifier.builder(IfIndexesInterfaceMap.class)
451                 .child(IfIndexInterface.class, new IfIndexInterfaceKey((int) interfaceTag)).build();
452     }
453
454     public static InstanceIdentifier<ElanDpnInterfacesList> getElanDpnOperationDataPath(String elanInstanceName) {
455         return InstanceIdentifier.builder(ElanDpnInterfaces.class)
456                 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName)).build();
457     }
458
459     public ElanDpnInterfacesList getElanDpnInterfacesList(String elanName) {
460         InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanName);
461         return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orNull();
462     }
463
464     public ElanDpnInterfaces getElanDpnInterfacesList() {
465         InstanceIdentifier<ElanDpnInterfaces> elanDpnInterfaceId = InstanceIdentifier.builder(ElanDpnInterfaces.class)
466                 .build();
467         return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orNull();
468     }
469
470     /**
471      * This method is useful get all ELAN participating CSS dpIds to install
472      * program remote dmac entries and updating remote bc groups for tor
473      * integration.
474      *
475      * @param elanInstanceName
476      *            the elan instance name
477      * @return list of dpIds
478      */
479     @Nonnull
480     public List<BigInteger> getParticipatingDpnsInElanInstance(String elanInstanceName) {
481         List<BigInteger> dpIds = new ArrayList<>();
482         InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
483         Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = read(broker,
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 boolean isDpnAlreadyPresentInElanInstance(BigInteger dpId, String elanInstanceName) {
507         InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
508         Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = read(broker,
509                 LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
510         if (!existingElanDpnInterfaces.isPresent()) {
511             return false;
512         }
513         List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().getDpnInterfaces();
514         for (DpnInterfaces dpnInterface : dpnInterfaces) {
515             if (dpnInterface.getDpId().equals(dpId)) {
516                 return true;
517             }
518         }
519         return false;
520     }
521
522     public ElanForwardingTables getElanForwardingList() {
523         InstanceIdentifier<ElanForwardingTables> elanForwardingTableId = InstanceIdentifier
524                 .builder(ElanForwardingTables.class).build();
525         return read(broker, LogicalDatastoreType.OPERATIONAL, elanForwardingTableId).orNull();
526     }
527
528     public static long getElanRemoteBroadCastGroupID(long elanTag) {
529         return ElanConstants.ELAN_GID_MIN + elanTag % ElanConstants.ELAN_GID_MIN * 2;
530     }
531
532     /**
533      * Gets the elan mac table.
534      *
535      * @param elanName
536      *            the elan name
537      * @return the elan mac table
538      */
539     public MacTable getElanMacTable(String elanName) {
540         return getElanMacTable(broker, elanName);
541     }
542
543     @Nullable
544     public static MacTable getElanMacTable(DataBroker dataBroker, String elanName) {
545         InstanceIdentifier<MacTable> elanMacTableId = getElanMacTableOperationalDataPath(elanName);
546         return read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanMacTableId).orNull();
547     }
548
549     public static long getElanLocalBCGId(long elanTag) {
550         return ElanConstants.ELAN_GID_MIN + (elanTag % ElanConstants.ELAN_GID_MIN * 2 - 1);
551     }
552
553     public static long getElanRemoteBCGId(long elanTag) {
554         return ElanConstants.ELAN_GID_MIN + elanTag % ElanConstants.ELAN_GID_MIN * 2;
555     }
556
557     public static long getEtreeLeafLocalBCGId(long etreeLeafTag) {
558         return ElanConstants.ELAN_GID_MIN + (etreeLeafTag % ElanConstants.ELAN_GID_MIN * 2 - 1);
559     }
560
561     public static long getEtreeLeafRemoteBCGId(long etreeLeafTag) {
562         return ElanConstants.ELAN_GID_MIN + etreeLeafTag % ElanConstants.ELAN_GID_MIN * 2;
563     }
564
565     public static BigInteger getElanMetadataLabel(long elanTag, boolean isSHFlagSet) {
566         int shBit = isSHFlagSet ? 1 : 0;
567         return BigInteger.valueOf(elanTag).shiftLeft(24).or(BigInteger.valueOf(shBit));
568     }
569
570     /**
571      * Setting SMAC, DMAC, UDMAC in this DPN and optionally in other DPNs.
572      *
573      * @param elanInfo
574      *            the elan info
575      * @param interfaceInfo
576      *            the interface info
577      * @param macTimeout
578      *            the mac timeout
579      * @param macAddress
580      *            the mac address
581      * @param configureRemoteFlows
582      *            true if remote dmac flows should be configured as well
583      * @param writeFlowGroupTx
584      *            the flow group tx
585      * @throws ElanException in case of issues creating the flow objects
586      */
587     public void setupMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo,
588                               long macTimeout, String macAddress, boolean configureRemoteFlows,
589                               WriteTransaction writeFlowGroupTx) throws ElanException {
590         synchronized (getElanMacDPNKey(elanInfo.getElanTag(), macAddress, interfaceInfo.getDpId())) {
591             setupKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress, mdsalManager,
592                 writeFlowGroupTx);
593             setupOrigDmacFlows(elanInfo, interfaceInfo, macAddress, configureRemoteFlows, mdsalManager,
594                     writeFlowGroupTx);
595         }
596     }
597
598     public void setupDMacFlowOnRemoteDpn(ElanInstance elanInfo, InterfaceInfo interfaceInfo, BigInteger dstDpId,
599                                          String macAddress, WriteTransaction writeFlowTx) throws ElanException {
600         String elanInstanceName = elanInfo.getElanInstanceName();
601         setupRemoteDmacFlow(dstDpId, interfaceInfo.getDpId(), interfaceInfo.getInterfaceTag(), elanInfo.getElanTag(),
602                 macAddress, elanInstanceName, writeFlowTx, interfaceInfo.getInterfaceName(), elanInfo);
603         LOG.info("Remote Dmac flow entry created for elan Name:{}, logical port Name:{} and"
604                 + " mac address {} on dpn:{}", elanInstanceName, interfaceInfo.getPortName(),
605                 macAddress, dstDpId);
606     }
607
608     /**
609      * Inserts a Flow in SMAC table to state that the MAC has already been
610      * learnt.
611      */
612     private void setupKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
613             String macAddress, IMdsalApiManager mdsalApiManager, WriteTransaction writeFlowGroupTx) {
614         FlowEntity flowEntity = buildKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress);
615         mdsalApiManager.addFlowToTx(flowEntity, writeFlowGroupTx);
616         LOG.debug("Known Smac flow entry created for elan Name:{}, logical Interface port:{} and mac address:{}",
617                 elanInfo.getElanInstanceName(), elanInfo.getDescription(), macAddress);
618     }
619
620     public FlowEntity buildKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
621             String macAddress) {
622         int lportTag = interfaceInfo.getInterfaceTag();
623         // Matching metadata and eth_src fields
624         List<MatchInfo> mkMatches = new ArrayList<>();
625         mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanInfo.getElanTag(), lportTag),
626                 ElanHelper.getElanMetadataMask()));
627         mkMatches.add(new MatchEthernetSource(new MacAddress(macAddress)));
628         List<InstructionInfo> mkInstructions = new ArrayList<>();
629         mkInstructions.add(new InstructionGotoTable(NwConstants.ELAN_DMAC_TABLE));
630         BigInteger dpId = interfaceInfo.getDpId();
631         long elanTag = getElanTag(elanInfo, interfaceInfo);
632         return new FlowEntityBuilder()
633             .setDpnId(dpId)
634             .setTableId(NwConstants.ELAN_SMAC_TABLE)
635             .setFlowId(getKnownDynamicmacFlowRef(NwConstants.ELAN_SMAC_TABLE, dpId, lportTag, macAddress, elanTag))
636             .setPriority(20)
637             .setFlowName(elanInfo.getDescription())
638             .setIdleTimeOut((int) macTimeout)
639             .setHardTimeOut(0)
640             .setCookie(ElanConstants.COOKIE_ELAN_KNOWN_SMAC.add(BigInteger.valueOf(elanTag)))
641             .setMatchInfoList(mkMatches)
642             .setInstructionInfoList(mkInstructions)
643             .setStrictFlag(true)
644             // If Mac timeout is 0, the flow won't be deleted automatically, so no need to get notified
645             .setSendFlowRemFlag(macTimeout != 0)
646             .build();
647     }
648
649     private Long getElanTag(ElanInstance elanInfo, InterfaceInfo interfaceInfo) {
650         EtreeInterface etreeInterface = elanInterfaceCache.getEtreeInterface(interfaceInfo.getInterfaceName()).orNull();
651         if (etreeInterface == null || etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
652             return elanInfo.getElanTag();
653         } else { // Leaf
654             EtreeInstance etreeInstance = elanInfo.getAugmentation(EtreeInstance.class);
655             if (etreeInstance == null) {
656                 LOG.warn("EtreeInterface {} is connected to a non-Etree network: {}",
657                          interfaceInfo.getInterfaceName(), elanInfo.getElanInstanceName());
658                 return elanInfo.getElanTag();
659             } else {
660                 return etreeInstance.getEtreeLeafTagVal().getValue();
661             }
662         }
663     }
664
665     /**
666      * Installs a Flow in INTERNAL_TUNNEL_TABLE of the affected DPN that sends
667      * the packet through the specified interface if the tunnel_id matches the
668      * interface's lportTag.
669      *
670      * @param interfaceInfo
671      *            the interface info
672      * @param mdsalApiManager
673      *            the mdsal API manager
674      * @param writeFlowGroupTx
675      *            the writeFLowGroup tx
676      */
677     public void setupTermDmacFlows(InterfaceInfo interfaceInfo, IMdsalApiManager mdsalApiManager,
678                                    WriteTransaction writeFlowGroupTx) {
679         BigInteger dpId = interfaceInfo.getDpId();
680         int lportTag = interfaceInfo.getInterfaceTag();
681         Flow flow = MDSALUtil.buildFlowNew(NwConstants.INTERNAL_TUNNEL_TABLE,
682                 getIntTunnelTableFlowRef(NwConstants.INTERNAL_TUNNEL_TABLE, lportTag), 5,
683                 String.format("%s:%d", "ITM Flow Entry ", lportTag), 0, 0,
684                 ITMConstants.COOKIE_ITM.add(BigInteger.valueOf(lportTag)),
685                 getTunnelIdMatchForFilterEqualsLPortTag(lportTag),
686                 getInstructionsInPortForOutGroup(interfaceInfo.getInterfaceName()));
687         mdsalApiManager.addFlowToTx(dpId, flow, writeFlowGroupTx);
688         LOG.debug("Terminating service table flow entry created on dpn:{} for logical Interface port:{}", dpId,
689                 interfaceInfo.getPortName());
690     }
691
692     /**
693      * Constructs the FlowName for flows installed in the Internal Tunnel Table,
694      * consisting in tableId + elanTag.
695      *
696      * @param tableId
697      *            table Id
698      * @param elanTag
699      *            elan Tag
700      * @return the Internal tunnel
701      */
702     public static String getIntTunnelTableFlowRef(short tableId, int elanTag) {
703         return new StringBuffer().append(tableId).append(elanTag).toString();
704     }
705
706     /**
707      * Constructs the Matches that checks that the tunnel_id field contains a
708      * specific lportTag.
709      *
710      * @param lportTag
711      *            lportTag that must be checked against the tunnel_id field
712      * @return the list of match Info
713      */
714     public static List<MatchInfo> getTunnelIdMatchForFilterEqualsLPortTag(int lportTag) {
715         List<MatchInfo> mkMatches = new ArrayList<>();
716         // Matching metadata
717         mkMatches.add(new MatchTunnelId(BigInteger.valueOf(lportTag)));
718         return mkMatches;
719     }
720
721     /**
722      * Constructs the Instructions that take the packet over a given interface.
723      *
724      * @param ifName
725      *            Name of the interface where the packet must be sent over. It
726      *            can be a local interface or a tunnel interface (internal or
727      *            external)
728      * @return the Instruction
729      */
730     public List<Instruction> getInstructionsInPortForOutGroup(String ifName) {
731         List<Instruction> mkInstructions = new ArrayList<>();
732         List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
733
734         mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
735         return mkInstructions;
736     }
737
738     /**
739      * Returns the list of Actions to be taken when sending the packet through
740      * an Elan interface. Note that this interface can refer to an ElanInterface
741      * where the Elan VM is attached to a DPN or an ITM tunnel interface where
742      * Elan traffic can be sent through. In this latter case, the tunnelKey is
743      * mandatory and it can hold serviceId for internal tunnels or the VNI for
744      * external tunnels.
745      *
746      * @param ifName
747      *            the if name
748      * @param tunnelKey
749      *            the tunnel key
750      * @return the egress actions for interface
751      */
752     @SuppressWarnings("checkstyle:IllegalCatch")
753     public List<Action> getEgressActionsForInterface(String ifName, Long tunnelKey) {
754         List<Action> listAction = new ArrayList<>();
755         try {
756             GetEgressActionsForInterfaceInput getEgressActionInput = new GetEgressActionsForInterfaceInputBuilder()
757                     .setIntfName(ifName).setTunnelKey(tunnelKey).build();
758             Future<RpcResult<GetEgressActionsForInterfaceOutput>> result = interfaceManagerRpcService
759                     .getEgressActionsForInterface(getEgressActionInput);
760             RpcResult<GetEgressActionsForInterfaceOutput> rpcResult = result.get();
761             if (!rpcResult.isSuccessful()) {
762                 LOG.debug("RPC Call to Get egress actions for interface {} returned with Errors {}", ifName,
763                         rpcResult.getErrors());
764             } else {
765                 List<Action> actions = rpcResult.getResult().getAction();
766                 listAction = actions;
767             }
768         } catch (Exception e) {
769             LOG.warn("Exception when egress actions for interface {}", ifName, e);
770         }
771         return listAction;
772     }
773
774     private void setupOrigDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
775                                     boolean configureRemoteFlows, IMdsalApiManager mdsalApiManager,
776                                     WriteTransaction writeFlowGroupTx)
777                                     throws ElanException {
778         BigInteger dpId = interfaceInfo.getDpId();
779         String ifName = interfaceInfo.getInterfaceName();
780         long ifTag = interfaceInfo.getInterfaceTag();
781         String elanInstanceName = elanInfo.getElanInstanceName();
782
783         Long elanTag = elanInfo.getElanTag();
784
785         setupLocalDmacFlow(elanTag, dpId, ifName, macAddress, elanInfo, mdsalApiManager, ifTag,
786                 writeFlowGroupTx);
787         LOG.debug("Dmac flow entry created for elan Name:{}, logical port Name:{} mand mac address:{} "
788                                     + "on dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, dpId);
789
790         if (!configureRemoteFlows) {
791             return;
792         }
793
794         List<DpnInterfaces> elanDpns = getInvolvedDpnsInElan(elanInstanceName);
795         for (DpnInterfaces elanDpn : elanDpns) {
796
797             if (elanDpn.getDpId().equals(dpId)) {
798                 continue;
799             }
800
801             // Check for the Remote DPN present in Inventory Manager
802             if (!isDpnPresent(elanDpn.getDpId())) {
803                 continue;
804             }
805
806             // For remote DPNs a flow is needed to indicate that packets of this ELAN going to this MAC need to be
807             // forwarded through the appropriate ITM tunnel
808             setupRemoteDmacFlow(elanDpn.getDpId(), // srcDpn (the remote DPN in this case)
809                     dpId, // dstDpn (the local DPN)
810                     interfaceInfo.getInterfaceTag(), // lportTag of the local interface
811                     elanTag,  // identifier of the Elan
812                     macAddress, // MAC to be programmed in remote DPN
813                     elanInstanceName, writeFlowGroupTx, ifName, elanInfo
814             );
815             LOG.debug("Remote Dmac flow entry created for elan Name:{}, logical port Name:{} and mac address:{} on"
816                         + " dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, elanDpn.getDpId());
817         }
818
819         // TODO: Make sure that the same is performed against the ElanDevices.
820     }
821
822     @Nonnull
823     public List<DpnInterfaces> getInvolvedDpnsInElan(String elanName) {
824         return getElanDPNByName(elanName);
825     }
826
827     @Nonnull
828     public List<DpnInterfaces> getElanDPNByName(String elanInstanceName) {
829         InstanceIdentifier<ElanDpnInterfacesList> elanIdentifier = getElanDpnOperationDataPath(elanInstanceName);
830         return MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL, elanIdentifier).toJavaUtil().map(
831                 ElanDpnInterfacesList::getDpnInterfaces).orElse(Collections.emptyList());
832     }
833
834     private void setupLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
835             ElanInstance elanInfo, IMdsalApiManager mdsalApiManager, long ifTag, WriteTransaction writeFlowGroupTx) {
836         Flow flowEntity = buildLocalDmacFlowEntry(elanTag, dpId, ifName, macAddress, elanInfo, ifTag);
837         mdsalApiManager.addFlowToTx(dpId, flowEntity, writeFlowGroupTx);
838         installEtreeLocalDmacFlow(elanTag, dpId, ifName, macAddress, elanInfo,
839                 ifTag, writeFlowGroupTx);
840     }
841
842     private void installEtreeLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
843             ElanInstance elanInfo, long ifTag, WriteTransaction writeFlowGroupTx) {
844         EtreeInterface etreeInterface = elanInterfaceCache.getEtreeInterface(ifName).orNull();
845         if (etreeInterface != null && etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
846             EtreeLeafTagName etreeTagName = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
847             if (etreeTagName == null) {
848                 LOG.warn("Interface {} seems like it belongs to Etree but etreeTagName from elanTag {} is null",
849                         ifName, elanTag);
850             } else {
851                 Flow flowEntity = buildLocalDmacFlowEntry(etreeTagName.getEtreeLeafTag().getValue(), dpId, ifName,
852                         macAddress, elanInfo, ifTag);
853                 mdsalManager.addFlowToTx(dpId, flowEntity, writeFlowGroupTx);
854             }
855         }
856     }
857
858     public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, long lporTag, String macAddress,
859             long elanTag) {
860         return new StringBuffer().append(tableId).append(elanTag).append(dpId).append(lporTag).append(macAddress)
861                 .toString();
862     }
863
864     public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, BigInteger remoteDpId,
865             String macAddress, long elanTag) {
866         return new StringBuffer().append(tableId).append(elanTag).append(dpId).append(remoteDpId).append(macAddress)
867                 .toString();
868     }
869
870     public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, String macAddress, long elanTag) {
871         return new StringBuffer().append(tableId).append(elanTag).append(dpId).append(macAddress).toString();
872     }
873
874     public static String getKnownDynamicmacFlowRef(short elanDmacTable, BigInteger dpId, String extDeviceNodeId,
875             String dstMacAddress, long elanTag, boolean shFlag) {
876         return new StringBuffer().append(elanDmacTable).append(elanTag).append(dpId).append(extDeviceNodeId)
877                 .append(dstMacAddress).append(shFlag).toString();
878     }
879
880     /**
881      * Builds the flow to be programmed in the DMAC table of the local DPN (that
882      * is, where the MAC is attached to). This flow consists in:
883      *
884      * <p>Match: + elanTag in metadata + packet goes to a MAC locally attached
885      * Actions: + optionally, pop-vlan + set-vlan-id + output to ifName's
886      * portNumber
887      *
888      * @param elanTag
889      *            the elan tag
890      * @param dpId
891      *            the dp id
892      * @param ifName
893      *            the if name
894      * @param macAddress
895      *            the mac address
896      * @param elanInfo
897      *            the elan info
898      * @param ifTag
899      *            the if tag
900      * @return the flow
901      */
902     public Flow buildLocalDmacFlowEntry(long elanTag, BigInteger dpId, String ifName, String macAddress,
903             ElanInstance elanInfo, long ifTag) {
904
905         List<MatchInfo> mkMatches = new ArrayList<>();
906         mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
907         mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddress)));
908
909         List<Instruction> mkInstructions = new ArrayList<>();
910         List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
911         mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
912         Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
913                 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, ifTag, macAddress, elanTag), 20,
914                 elanInfo.getElanInstanceName(), 0, 0, ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(
915                         BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
916
917         return flow;
918     }
919
920     public void setupRemoteDmacFlow(BigInteger srcDpId, BigInteger destDpId, int lportTag, long elanTag, String
921             macAddress, String displayName, WriteTransaction writeFlowGroupTx, String interfaceName, ElanInstance
922             elanInstance) throws ElanException {
923         if (interfaceManager.isExternalInterface(interfaceName)) {
924             LOG.debug("Ignoring install remote DMAC {} flow on provider interface {} elan {}",
925                     macAddress, interfaceName, elanInstance.getElanInstanceName());
926             return;
927         }
928         Flow flowEntity;
929         // if openstack-vni-semantics are enforced, segmentation ID is passed as network VNI for VxLAN based provider
930         // networks, 0 otherwise
931         long lportTagOrVni = !isOpenstackVniSemanticsEnforced() ? lportTag : isVxlan(elanInstance)
932                 ? elanInstance.getSegmentationId() : 0;
933         flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTagOrVni, elanTag, macAddress, displayName,
934                 elanInstance);
935         mdsalManager.addFlowToTx(srcDpId, flowEntity, writeFlowGroupTx);
936         setupEtreeRemoteDmacFlow(srcDpId, destDpId, lportTagOrVni, elanTag, macAddress, displayName, interfaceName,
937                 writeFlowGroupTx, elanInstance);
938     }
939
940     private void setupEtreeRemoteDmacFlow(BigInteger srcDpId, BigInteger destDpId, long lportTagOrVni, long elanTag,
941                                           String macAddress, String displayName, String interfaceName,
942                                           WriteTransaction writeFlowGroupTx, ElanInstance elanInstance)
943                                           throws ElanException {
944         Flow flowEntity;
945         EtreeInterface etreeInterface = elanInterfaceCache.getEtreeInterface(interfaceName).orNull();
946         if (etreeInterface != null && etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
947             EtreeLeafTagName etreeTagName = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
948             if (etreeTagName == null) {
949                 LOG.warn("Interface " + interfaceName
950                         + " seems like it belongs to Etree but etreeTagName from elanTag " + elanTag + " is null.");
951             } else {
952                 flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTagOrVni,
953                         etreeTagName.getEtreeLeafTag().getValue(), macAddress, displayName, elanInstance);
954                 mdsalManager.addFlowToTx(srcDpId, flowEntity, writeFlowGroupTx);
955             }
956         }
957     }
958
959     /**
960      * Builds a Flow to be programmed in a remote DPN's DMAC table. This flow
961      * consists in: Match: + elanTag in packet's metadata + packet going to a
962      * MAC known to be located in another DPN Actions: + set_tunnel_id
963      * + output ITM internal tunnel interface with the other DPN
964      *
965      * @param srcDpId
966      *            the src Dpn Id
967      * @param destDpId
968      *            dest Dp Id
969      * @param lportTagOrVni
970      *            lportTag or network VNI
971      * @param elanTag
972      *            elan Tag
973      * @param macAddress
974      *            macAddress
975      * @param displayName
976      *            display Name
977      * @param elanInstance
978      *            elanInstance
979      * @return the flow remote Dmac
980      * @throws ElanException in case of issues creating the flow objects
981      */
982     @SuppressWarnings("checkstyle:IllegalCatch")
983     public Flow buildRemoteDmacFlowEntry(BigInteger srcDpId, BigInteger destDpId, long lportTagOrVni, long elanTag,
984             String macAddress, String displayName, ElanInstance elanInstance) throws ElanException {
985         List<MatchInfo> mkMatches = new ArrayList<>();
986         mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
987         mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddress)));
988
989         List<Instruction> mkInstructions = new ArrayList<>();
990
991         // List of Action for the provided Source and Destination DPIDs
992         try {
993             List<Action> actions = null;
994             if (isVlan(elanInstance) || isFlat(elanInstance)) {
995                 String interfaceName = getExternalElanInterface(elanInstance.getElanInstanceName(), srcDpId);
996                 if (null == interfaceName) {
997                     LOG.info("buildRemoteDmacFlowEntry: Could not find interfaceName for {} {}", srcDpId,
998                         elanInstance);
999                 }
1000                 actions = getEgressActionsForInterface(interfaceName, null);
1001             } else if (isVxlan(elanInstance)) {
1002                 actions = elanItmUtils.getInternalTunnelItmEgressAction(srcDpId, destDpId, lportTagOrVni);
1003             }
1004             mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
1005         } catch (Exception e) {
1006             LOG.error("Could not get egress actions to add to flow for srcDpId=" + srcDpId + ", destDpId=" + destDpId
1007                     + ", lportTag/VNI=" + lportTagOrVni, e);
1008         }
1009
1010         Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
1011                 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, srcDpId, destDpId, macAddress, elanTag),
1012                 20, /* prio */
1013                 displayName, 0, /* idleTimeout */
1014                 0, /* hardTimeout */
1015                 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
1016
1017         return flow;
1018
1019     }
1020
1021     public void deleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, MacEntry macEntry,
1022             WriteTransaction deleteFlowGroupTx) {
1023         if (elanInfo == null || interfaceInfo == null) {
1024             return;
1025         }
1026         String macAddress = macEntry.getMacAddress().getValue();
1027         synchronized (getElanMacDPNKey(elanInfo.getElanTag(), macAddress, interfaceInfo.getDpId())) {
1028             deleteMacFlows(elanInfo, interfaceInfo, macAddress, /* alsoDeleteSMAC */ true, deleteFlowGroupTx);
1029         }
1030     }
1031
1032     public void deleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1033             boolean deleteSmac, WriteTransaction deleteFlowGroupTx) {
1034         String elanInstanceName = elanInfo.getElanInstanceName();
1035         List<DpnInterfaces> remoteFEs = getInvolvedDpnsInElan(elanInstanceName);
1036         BigInteger srcdpId = interfaceInfo.getDpId();
1037         boolean isFlowsRemovedInSrcDpn = false;
1038         for (DpnInterfaces dpnInterface : remoteFEs) {
1039             Long elanTag = elanInfo.getElanTag();
1040             BigInteger dstDpId = dpnInterface.getDpId();
1041             if (executeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1042                     elanTag, dstDpId, deleteFlowGroupTx)) {
1043                 isFlowsRemovedInSrcDpn = true;
1044             }
1045             executeEtreeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1046                     elanTag, dstDpId, deleteFlowGroupTx);
1047         }
1048         if (!isFlowsRemovedInSrcDpn) {
1049             deleteSmacAndDmacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, deleteFlowGroupTx);
1050         }
1051     }
1052
1053     private void executeEtreeDeleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1054             boolean deleteSmac, String elanInstanceName, BigInteger srcdpId, Long elanTag, BigInteger dstDpId,
1055             WriteTransaction deleteFlowGroupTx) {
1056         EtreeLeafTagName etreeLeafTag = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
1057         if (etreeLeafTag != null) {
1058             executeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1059                     etreeLeafTag.getEtreeLeafTag().getValue(), dstDpId, deleteFlowGroupTx);
1060         }
1061     }
1062
1063     private boolean executeDeleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1064             boolean deleteSmac, String elanInstanceName, BigInteger srcdpId, Long elanTag, BigInteger dstDpId,
1065             WriteTransaction deleteFlowGroupTx) {
1066         boolean isFlowsRemovedInSrcDpn = false;
1067         if (dstDpId.equals(srcdpId)) {
1068             isFlowsRemovedInSrcDpn = true;
1069             deleteSmacAndDmacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, deleteFlowGroupTx);
1070         } else if (isDpnPresent(dstDpId)) {
1071             mdsalManager
1072                     .removeFlowToTx(dstDpId,
1073                             MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, getKnownDynamicmacFlowRef(
1074                                     NwConstants.ELAN_DMAC_TABLE, dstDpId, srcdpId, macAddress, elanTag)),
1075                             deleteFlowGroupTx);
1076             LOG.debug("Dmac flow entry deleted for elan:{}, logical interface port:{} and mac address:{} on dpn:{}",
1077                     elanInstanceName, interfaceInfo.getPortName(), macAddress, dstDpId);
1078         }
1079         return isFlowsRemovedInSrcDpn;
1080     }
1081
1082     private void deleteSmacAndDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1083             boolean deleteSmac, WriteTransaction deleteFlowGroupTx) {
1084         String elanInstanceName = elanInfo.getElanInstanceName();
1085         long ifTag = interfaceInfo.getInterfaceTag();
1086         BigInteger srcdpId = interfaceInfo.getDpId();
1087         Long elanTag = elanInfo.getElanTag();
1088         if (deleteSmac) {
1089             mdsalManager
1090                     .removeFlowToTx(srcdpId,
1091                             MDSALUtil.buildFlow(NwConstants.ELAN_SMAC_TABLE, getKnownDynamicmacFlowRef(
1092                                     NwConstants.ELAN_SMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)),
1093                             deleteFlowGroupTx);
1094         }
1095         mdsalManager.removeFlowToTx(srcdpId,
1096                 MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE,
1097                         getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)),
1098                 deleteFlowGroupTx);
1099         LOG.debug("All the required flows deleted for elan:{}, logical Interface port:{} and MAC address:{} on dpn:{}",
1100                 elanInstanceName, interfaceInfo.getPortName(), macAddress, srcdpId);
1101     }
1102
1103     /**
1104      * Updates the Elan information in the Operational DS. It also updates the
1105      * ElanInstance in the Config DS by setting the adquired elanTag.
1106      *
1107      * @param broker
1108      *            the broker
1109      * @param idManager
1110      *            the id manager
1111      * @param elanInstanceAdded
1112      *            the elan instance added
1113      * @param elanInterfaces
1114      *            the elan interfaces
1115      * @param tx
1116      *            transaction
1117      *
1118      * @return the updated ELAN instance.
1119      */
1120     public static ElanInstance updateOperationalDataStore(DataBroker broker, IdManagerService idManager,
1121             ElanInstance elanInstanceAdded, List<String> elanInterfaces, WriteTransaction tx) {
1122         String elanInstanceName = elanInstanceAdded.getElanInstanceName();
1123         Long elanTag = elanInstanceAdded.getElanTag();
1124         if (elanTag == null || elanTag == 0L) {
1125             elanTag = retrieveNewElanTag(idManager, elanInstanceName);
1126         }
1127         Elan elanInfo = new ElanBuilder().setName(elanInstanceName).setElanInterfaces(elanInterfaces)
1128                 .setKey(new ElanKey(elanInstanceName)).build();
1129
1130         // Add the ElanState in the elan-state operational data-store
1131         tx.put(LogicalDatastoreType.OPERATIONAL, getElanInstanceOperationalDataPath(elanInstanceName),
1132                 elanInfo, WriteTransaction.CREATE_MISSING_PARENTS);
1133
1134         // Add the ElanMacTable in the elan-mac-table operational data-store
1135         MacTable elanMacTable = new MacTableBuilder().setKey(new MacTableKey(elanInstanceName)).build();
1136         tx.put(LogicalDatastoreType.OPERATIONAL, getElanMacTableOperationalDataPath(elanInstanceName),
1137                 elanMacTable, WriteTransaction.CREATE_MISSING_PARENTS);
1138
1139         ElanTagNameBuilder elanTagNameBuilder = new ElanTagNameBuilder().setElanTag(elanTag)
1140                 .setKey(new ElanTagNameKey(elanTag)).setName(elanInstanceName);
1141         long etreeLeafTag = -1;
1142         if (isEtreeInstance(elanInstanceAdded)) {
1143             etreeLeafTag = retrieveNewElanTag(idManager,elanInstanceName + ElanConstants
1144                     .LEAVES_POSTFIX);
1145             EtreeLeafTagName etreeLeafTagName = new EtreeLeafTagNameBuilder()
1146                     .setEtreeLeafTag(new EtreeLeafTag(etreeLeafTag)).build();
1147             elanTagNameBuilder.addAugmentation(EtreeLeafTagName.class, etreeLeafTagName);
1148             addTheLeafTagAsElanTag(broker, elanInstanceName, etreeLeafTag, tx);
1149         }
1150         ElanTagName elanTagName = elanTagNameBuilder.build();
1151
1152         // Add the ElanTag to ElanName in the elan-tag-name Operational
1153         // data-store
1154         tx.put(LogicalDatastoreType.OPERATIONAL,
1155                 getElanInfoEntriesOperationalDataPath(elanTag), elanTagName);
1156
1157         // Updates the ElanInstance Config DS by setting the just acquired
1158         // elanTag
1159         ElanInstanceBuilder elanInstanceBuilder = new ElanInstanceBuilder().setElanInstanceName(elanInstanceName)
1160                 .setDescription(elanInstanceAdded.getDescription())
1161                 .setMacTimeout(elanInstanceAdded.getMacTimeout() == null
1162                         ? Long.valueOf(ElanConstants.DEFAULT_MAC_TIME_OUT) : elanInstanceAdded.getMacTimeout())
1163                 .setKey(elanInstanceAdded.getKey()).setElanTag(elanTag);
1164         if (isEtreeInstance(elanInstanceAdded)) {
1165             EtreeInstance etreeInstance = new EtreeInstanceBuilder().setEtreeLeafTagVal(new EtreeLeafTag(etreeLeafTag))
1166                     .build();
1167             elanInstanceBuilder.addAugmentation(EtreeInstance.class, etreeInstance);
1168         }
1169         ElanInstance elanInstanceWithTag = elanInstanceBuilder.build();
1170         tx.merge(LogicalDatastoreType.CONFIGURATION, ElanHelper.getElanInstanceConfigurationDataPath(elanInstanceName),
1171                 elanInstanceWithTag, WriteTransaction.CREATE_MISSING_PARENTS);
1172         return elanInstanceWithTag;
1173     }
1174
1175     private static void addTheLeafTagAsElanTag(DataBroker broker, String elanInstanceName, long etreeLeafTag,
1176             WriteTransaction tx) {
1177         ElanTagName etreeTagAsElanTag = new ElanTagNameBuilder().setElanTag(etreeLeafTag)
1178                 .setKey(new ElanTagNameKey(etreeLeafTag)).setName(elanInstanceName).build();
1179         tx.put(LogicalDatastoreType.OPERATIONAL,
1180                 getElanInfoEntriesOperationalDataPath(etreeLeafTag), etreeTagAsElanTag);
1181     }
1182
1183     private static boolean isEtreeInstance(ElanInstance elanInstanceAdded) {
1184         return elanInstanceAdded.getAugmentation(EtreeInstance.class) != null;
1185     }
1186
1187     public boolean isDpnPresent(BigInteger dpnId) {
1188         String dpn = String.format("%s:%s", "openflow", dpnId);
1189         NodeId nodeId = new NodeId(dpn);
1190
1191         InstanceIdentifier<Node> node = InstanceIdentifier.builder(Nodes.class).child(Node.class, new NodeKey(nodeId))
1192                 .build();
1193         return read(broker, LogicalDatastoreType.CONFIGURATION, node).isPresent();
1194     }
1195
1196     public static ServicesInfo getServiceInfo(String elanInstanceName, String interfaceName) {
1197         return InterfaceServiceUtil.buildServiceInfo(elanInstanceName + "." + interfaceName,
1198                 ElanConstants.ELAN_SERVICE_PRIORITY);
1199     }
1200
1201     public static String getElanServiceName(String elanName, String interfaceName) {
1202         return "elan." + elanName + interfaceName;
1203     }
1204
1205     public static BoundServices getBoundServices(String serviceName, short servicePriority, int flowPriority,
1206             BigInteger cookie, List<Instruction> instructions) {
1207         StypeOpenflowBuilder augBuilder = new StypeOpenflowBuilder().setFlowCookie(cookie).setFlowPriority(flowPriority)
1208                 .setInstruction(instructions);
1209         return new BoundServicesBuilder().setKey(new BoundServicesKey(servicePriority)).setServiceName(serviceName)
1210                 .setServicePriority(servicePriority).setServiceType(ServiceTypeFlowBased.class)
1211                 .addAugmentation(StypeOpenflow.class, augBuilder.build()).build();
1212     }
1213
1214     public static InstanceIdentifier<BoundServices> buildServiceId(String interfaceName, short serviceIndex) {
1215         return InstanceIdentifier.builder(ServiceBindings.class)
1216                 .child(ServicesInfo.class, new ServicesInfoKey(interfaceName, ServiceModeIngress.class))
1217                 .child(BoundServices.class, new BoundServicesKey(serviceIndex)).build();
1218     }
1219
1220     public static List<MatchInfo> getTunnelMatchesForServiceId(int elanTag) {
1221         List<MatchInfo> mkMatches = new ArrayList<>();
1222         // Matching metadata
1223         mkMatches.add(new MatchTunnelId(BigInteger.valueOf(elanTag)));
1224
1225         return mkMatches;
1226     }
1227
1228     public void removeTerminatingServiceAction(BigInteger destDpId, int serviceId) {
1229         RemoveTerminatingServiceActionsInput input = new RemoveTerminatingServiceActionsInputBuilder()
1230                 .setDpnId(destDpId).setServiceId(serviceId).build();
1231         Future<RpcResult<Void>> futureObject = itmRpcService.removeTerminatingServiceActions(input);
1232         try {
1233             RpcResult<Void> result = futureObject.get();
1234             if (result.isSuccessful()) {
1235                 LOG.debug("Successfully completed removeTerminatingServiceActions for ELAN with serviceId {} on "
1236                                 + "dpn {}", serviceId, destDpId);
1237             } else {
1238                 LOG.debug("Failure in removeTerminatingServiceAction RPC call for ELAN with serviceId {} on "
1239                         + "dpn {}", serviceId, destDpId);
1240             }
1241         } catch (InterruptedException | ExecutionException e) {
1242             LOG.error("Error in RPC call removeTerminatingServiceActions for ELAN with serviceId {} on "
1243                     + "dpn {}: {}", serviceId, destDpId, e);
1244         }
1245     }
1246
1247     /**
1248      * Gets the external tunnel.
1249      *
1250      * @param sourceDevice
1251      *            the source device
1252      * @param destinationDevice
1253      *            the destination device
1254      * @param datastoreType
1255      *            the datastore type
1256      * @return the external tunnel
1257      */
1258     public ExternalTunnel getExternalTunnel(String sourceDevice, String destinationDevice,
1259             LogicalDatastoreType datastoreType) {
1260         Class<? extends TunnelTypeBase> tunType = TunnelTypeVxlan.class;
1261         InstanceIdentifier<ExternalTunnel> iid = InstanceIdentifier.builder(ExternalTunnelList.class)
1262                 .child(ExternalTunnel.class, new ExternalTunnelKey(destinationDevice, sourceDevice, tunType)).build();
1263         return read(broker, datastoreType, iid).orNull();
1264     }
1265
1266     /**
1267      * Gets the external tunnel.
1268      *
1269      * @param interfaceName
1270      *            the interface name
1271      * @param datastoreType
1272      *            the datastore type
1273      * @return the external tunnel
1274      */
1275     public ExternalTunnel getExternalTunnel(String interfaceName, LogicalDatastoreType datastoreType) {
1276         ExternalTunnel externalTunnel = null;
1277         List<ExternalTunnel> externalTunnels = getAllExternalTunnels(datastoreType);
1278         for (ExternalTunnel tunnel : externalTunnels) {
1279             if (StringUtils.equalsIgnoreCase(interfaceName, tunnel.getTunnelInterfaceName())) {
1280                 externalTunnel = tunnel;
1281                 break;
1282             }
1283         }
1284         return externalTunnel;
1285     }
1286
1287     /**
1288      * Gets the all external tunnels.
1289      *
1290      * @param datastoreType
1291      *            the data store type
1292      * @return the all external tunnels
1293      */
1294     public List<ExternalTunnel> getAllExternalTunnels(LogicalDatastoreType datastoreType) {
1295         InstanceIdentifier<ExternalTunnelList> iid = InstanceIdentifier.builder(ExternalTunnelList.class).build();
1296         return read(broker, datastoreType, iid).toJavaUtil().map(ExternalTunnelList::getExternalTunnel).orElse(
1297                 Collections.emptyList());
1298     }
1299
1300     public static List<MatchInfo> buildMatchesForElanTagShFlagAndDstMac(long elanTag, boolean shFlag, String macAddr) {
1301         List<MatchInfo> mkMatches = new ArrayList<>();
1302         mkMatches.add(
1303                 new MatchMetadata(getElanMetadataLabel(elanTag, shFlag), MetaDataUtil.METADATA_MASK_SERVICE_SH_FLAG));
1304         mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddr)));
1305         return mkMatches;
1306     }
1307
1308     /**
1309      * Checks if is interface operational.
1310      *
1311      * @param interfaceName
1312      *            the interface name
1313      * @param dataBroker
1314      *            the data broker
1315      * @return true, if is interface operational
1316      */
1317     public static boolean isInterfaceOperational(String interfaceName, DataBroker dataBroker) {
1318         if (StringUtils.isBlank(interfaceName)) {
1319             return false;
1320         }
1321         Interface ifState = getInterfaceStateFromOperDS(interfaceName, dataBroker);
1322         if (ifState == null) {
1323             return false;
1324         }
1325         return ifState.getOperStatus() == OperStatus.Up && ifState.getAdminStatus() == AdminStatus.Up;
1326     }
1327
1328     /**
1329      * Gets the interface state from operational ds.
1330      *
1331      * @param interfaceName
1332      *            the interface name
1333      * @param dataBroker
1334      *            the data broker
1335      * @return the interface state from oper ds
1336      */
1337     public static org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1338         .ietf.interfaces.rev140508.interfaces.state.Interface getInterfaceStateFromOperDS(
1339             String interfaceName, DataBroker dataBroker) {
1340         InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1341             .ietf.interfaces.rev140508.interfaces.state.Interface> ifStateId = createInterfaceStateInstanceIdentifier(
1342                 interfaceName);
1343         return MDSALUtil.read(dataBroker, LogicalDatastoreType.OPERATIONAL, ifStateId).orNull();
1344     }
1345
1346     /**
1347      * Creates the interface state instance identifier.
1348      *
1349      * @param interfaceName
1350      *            the interface name
1351      * @return the instance identifier
1352      */
1353     public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1354         .ietf.interfaces.rev140508.interfaces.state.Interface> createInterfaceStateInstanceIdentifier(
1355             String interfaceName) {
1356         InstanceIdentifierBuilder<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1357             .ietf.interfaces.rev140508.interfaces.state.Interface> idBuilder = InstanceIdentifier
1358                 .builder(InterfacesState.class)
1359                 .child(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1360                         .ietf.interfaces.rev140508.interfaces.state.Interface.class,
1361                         new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1362                             .ietf.interfaces.rev140508.interfaces.state.InterfaceKey(
1363                                 interfaceName));
1364         return idBuilder.build();
1365     }
1366
1367     public static CheckedFuture<Void, TransactionCommitFailedException> waitForTransactionToComplete(
1368             WriteTransaction tx) {
1369         CheckedFuture<Void, TransactionCommitFailedException> futures = tx.submit();
1370         try {
1371             futures.get();
1372         } catch (InterruptedException | ExecutionException e) {
1373             LOG.error("Error writing to datastore {}", e);
1374         }
1375         return futures;
1376     }
1377
1378     public static boolean isVxlan(ElanInstance elanInstance) {
1379         return elanInstance != null && elanInstance.getSegmentType() != null
1380                 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1381                 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId() != 0;
1382     }
1383
1384     private static boolean isVxlanSegment(ElanInstance elanInstance) {
1385         if (elanInstance != null) {
1386             List<ElanSegments> elanSegments = elanInstance.getElanSegments();
1387             if (elanSegments != null) {
1388                 for (ElanSegments segment : elanSegments) {
1389                     if (segment != null && segment.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1390                             && segment.getSegmentationId() != null
1391                             && segment.getSegmentationId().longValue() != 0) {
1392                         return true;
1393                     }
1394                 }
1395             }
1396         }
1397         return false;
1398     }
1399
1400     public static boolean isVxlanNetworkOrVxlanSegment(ElanInstance elanInstance) {
1401         return isVxlan(elanInstance) || isVxlanSegment(elanInstance);
1402     }
1403
1404     public static Long getVxlanSegmentationId(ElanInstance elanInstance) {
1405         Long segmentationId = 0L;
1406         if (elanInstance == null) {
1407             return segmentationId;
1408         }
1409
1410         if (elanInstance.getSegmentType() != null
1411                 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1412                 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId().longValue() != 0) {
1413             segmentationId = elanInstance.getSegmentationId();
1414         } else {
1415             for (ElanSegments segment: elanInstance.getElanSegments()) {
1416                 if (segment != null && segment.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1417                     && segment.getSegmentationId() != null
1418                     && segment.getSegmentationId().longValue() != 0) {
1419                     segmentationId = segment.getSegmentationId();
1420                 }
1421             }
1422         }
1423         return segmentationId;
1424     }
1425
1426     public static boolean isVlan(ElanInstance elanInstance) {
1427         return elanInstance != null && elanInstance.getSegmentType() != null
1428                 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVlan.class)
1429                 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId() != 0;
1430     }
1431
1432     public static boolean isFlat(ElanInstance elanInstance) {
1433         return elanInstance != null && elanInstance.getSegmentType() != null
1434                 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeFlat.class);
1435     }
1436
1437     public void addDmacRedirectToDispatcherFlows(Long elanTag, String displayName,
1438             String macAddress, List<BigInteger> dpnIds) {
1439         for (BigInteger dpId : dpnIds) {
1440             WriteTransaction writeTx = broker.newWriteOnlyTransaction();
1441             mdsalManager.addFlowToTx(buildDmacRedirectToDispatcherFlow(dpId, macAddress, displayName, elanTag),
1442                     writeTx);
1443             writeTx.submit();
1444         }
1445     }
1446
1447     public void removeDmacRedirectToDispatcherFlows(Long elanTag, String macAddress, List<BigInteger> dpnIds) {
1448         for (BigInteger dpId : dpnIds) {
1449             String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, macAddress, elanTag);
1450             mdsalManager.removeFlow(dpId, MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, flowId));
1451         }
1452     }
1453
1454     public static FlowEntity buildDmacRedirectToDispatcherFlow(BigInteger dpId, String dstMacAddress,
1455             String displayName, long elanTag) {
1456         List<MatchInfo> matches = new ArrayList<>();
1457         matches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
1458         matches.add(new MatchEthernetDestination(new MacAddress(dstMacAddress)));
1459         List<InstructionInfo> instructions = new ArrayList<>();
1460         List<ActionInfo> actions = new ArrayList<>();
1461         actions.add(new ActionNxResubmit(NwConstants.LPORT_DISPATCHER_TABLE));
1462
1463         instructions.add(new InstructionApplyActions(actions));
1464         String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, dstMacAddress, elanTag);
1465         FlowEntity flow  = MDSALUtil.buildFlowEntity(dpId, NwConstants.ELAN_DMAC_TABLE, flowId, 20, displayName, 0, 0,
1466                 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)),
1467                 matches, instructions);
1468         return flow;
1469     }
1470
1471     public String getExternalElanInterface(String elanInstanceName, BigInteger dpnId) {
1472         DpnInterfaces dpnInterfaces = getElanInterfaceInfoByElanDpn(elanInstanceName, dpnId);
1473         if (dpnInterfaces == null || dpnInterfaces.getInterfaces() == null) {
1474             LOG.trace("Elan {} does not have interfaces in DPN {}", elanInstanceName, dpnId);
1475             return null;
1476         }
1477
1478         for (String dpnInterface : dpnInterfaces.getInterfaces()) {
1479             if (interfaceManager.isExternalInterface(dpnInterface)) {
1480                 return dpnInterface;
1481             }
1482         }
1483
1484         LOG.trace("Elan {} does not have any external interace attached to DPN {}", elanInstanceName, dpnId);
1485         return null;
1486     }
1487
1488     public static String getElanMacDPNKey(long elanTag, String macAddress, BigInteger dpnId) {
1489         String elanMacDmacDpnKey = "MAC-" + macAddress + " ELAN_TAG-" + elanTag + "DPN_ID-" + dpnId;
1490         return elanMacDmacDpnKey.intern();
1491     }
1492
1493     public static String getElanMacKey(long elanTag, String macAddress) {
1494         String elanMacKey = "MAC-" + macAddress + " ELAN_TAG-" + elanTag;
1495         return elanMacKey.intern();
1496     }
1497
1498     // TODO This should return a collection of futures
1499     public static void addToListenableFutureIfTxException(RuntimeException exception,
1500             List<ListenableFuture<Void>> futures) {
1501         Throwable cause = exception.getCause();
1502         if (cause != null && cause instanceof TransactionCommitFailedException) {
1503             futures.add(Futures.immediateFailedCheckedFuture((TransactionCommitFailedException) cause));
1504         }
1505     }
1506
1507     public static List<PhysAddress> getPhysAddress(List<String> macAddress) {
1508         Preconditions.checkNotNull(macAddress, "macAddress cannot be null");
1509         List<PhysAddress> physAddresses = new ArrayList<>();
1510         for (String mac : macAddress) {
1511             physAddresses.add(new PhysAddress(mac));
1512         }
1513         return physAddresses;
1514     }
1515
1516     public static List<StaticMacEntries> getStaticMacEntries(List<String> staticMacAddresses) {
1517         if (isEmpty(staticMacAddresses)) {
1518             return Collections.EMPTY_LIST;
1519         }
1520         StaticMacEntriesBuilder staticMacEntriesBuilder = new StaticMacEntriesBuilder();
1521         List<StaticMacEntries> staticMacEntries = new ArrayList<>();
1522         List<PhysAddress> physAddressList = getPhysAddress(staticMacAddresses);
1523         for (PhysAddress physAddress : physAddressList) {
1524             staticMacEntries.add(staticMacEntriesBuilder.setMacAddress(physAddress).build());
1525         }
1526         return staticMacEntries;
1527     }
1528
1529     public static InstanceIdentifier<StaticMacEntries> getStaticMacEntriesCfgDataPathIdentifier(String interfaceName,
1530                                                                                                 String macAddress) {
1531         return InstanceIdentifier.builder(ElanInterfaces.class)
1532                 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).child(StaticMacEntries.class,
1533                         new StaticMacEntriesKey(new PhysAddress(macAddress))).build();
1534     }
1535
1536     public static List<StaticMacEntries> getDeletedEntries(List<StaticMacEntries> originalStaticMacEntries,
1537                                                            List<StaticMacEntries> updatedStaticMacEntries) {
1538         if (isEmpty(originalStaticMacEntries)) {
1539             return Collections.EMPTY_LIST;
1540         }
1541         List<StaticMacEntries> deleted = Lists.newArrayList(originalStaticMacEntries);
1542         if (isNotEmpty(updatedStaticMacEntries)) {
1543             deleted.removeAll(updatedStaticMacEntries);
1544         }
1545         return deleted;
1546     }
1547
1548     public static <T> List<T> diffOf(List<T> orig, List<T> updated) {
1549         if (isEmpty(orig)) {
1550             return Collections.EMPTY_LIST;
1551         }
1552         List<T> diff = Lists.newArrayList(orig);
1553         if (isNotEmpty(updated)) {
1554             diff.removeAll(updated);
1555         }
1556         return diff;
1557     }
1558
1559     public static void segregateToBeDeletedAndAddEntries(List<StaticMacEntries> originalStaticMacEntries,
1560                                                              List<StaticMacEntries> updatedStaticMacEntries) {
1561         if (isNotEmpty(updatedStaticMacEntries)) {
1562             List<StaticMacEntries> existingClonedStaticMacEntries = new ArrayList<>();
1563             if (isNotEmpty(originalStaticMacEntries)) {
1564                 existingClonedStaticMacEntries.addAll(0, originalStaticMacEntries);
1565                 originalStaticMacEntries.removeAll(updatedStaticMacEntries);
1566                 updatedStaticMacEntries.removeAll(existingClonedStaticMacEntries);
1567             }
1568         }
1569     }
1570
1571     public static boolean isEmpty(Collection collection) {
1572         return collection == null || collection.isEmpty();
1573     }
1574
1575     public static boolean isNotEmpty(Collection collection) {
1576         return !isEmpty(collection);
1577     }
1578
1579     public Optional<IpAddress> getSourceIpAddress(Ethernet ethernet) {
1580         Optional<IpAddress> srcIpAddress = Optional.absent();
1581         if (ethernet.getPayload() == null) {
1582             return srcIpAddress;
1583         }
1584         byte[] ipAddrBytes = null;
1585         if (ethernet.getPayload() instanceof IPv4) {
1586             IPv4 ipv4 = (IPv4) ethernet.getPayload();
1587             ipAddrBytes = Ints.toByteArray(ipv4.getSourceAddress());
1588         } else if (ethernet.getPayload() instanceof ARP) {
1589             ipAddrBytes = ((ARP) ethernet.getPayload()).getSenderProtocolAddress();
1590         }
1591         if (ipAddrBytes != null) {
1592             String ipAddr = NWUtil.toStringIpAddress(ipAddrBytes);
1593             return Optional.of(IpAddressBuilder.getDefaultInstance(ipAddr));
1594         }
1595         return srcIpAddress;
1596     }
1597
1598     public List<MacEntry> getElanMacEntries(String elanName) {
1599         MacTable macTable = getElanMacTable(elanName);
1600         if (macTable == null) {
1601             return Collections.emptyList();
1602         }
1603         return macTable.getMacEntry();
1604     }
1605
1606     public boolean isTunnelInLogicalGroup(String interfaceName) {
1607         org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1608             .ietf.interfaces.rev140508.interfaces.Interface configIface =
1609             interfaceManager.getInterfaceInfoFromConfigDataStore(interfaceName);
1610         IfTunnel ifTunnel = configIface.getAugmentation(IfTunnel.class);
1611         if (ifTunnel != null && ifTunnel.getTunnelInterfaceType().isAssignableFrom(TunnelTypeVxlan.class)) {
1612             ParentRefs refs = configIface.getAugmentation(ParentRefs.class);
1613             if (refs != null && !Strings.isNullOrEmpty(refs.getParentInterface())) {
1614                 return true; //multiple VxLAN tunnels enabled, i.e. only logical tunnel should be treated
1615             }
1616         }
1617         return false;
1618     }
1619
1620     public static InstanceIdentifier<Flow> getFlowIid(Flow flow, BigInteger dpnId) {
1621         FlowKey flowKey = new FlowKey(new FlowId(flow.getId()));
1622         org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId nodeId =
1623                 new org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId("openflow:" + dpnId);
1624         org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node nodeDpn =
1625                 new NodeBuilder().setId(nodeId).setKey(new NodeKey(nodeId)).build();
1626         return InstanceIdentifier.builder(Nodes.class)
1627                 .child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node.class,
1628                         nodeDpn.getKey()).augmentation(FlowCapableNode.class)
1629                 .child(Table.class, new TableKey(flow.getTableId())).child(Flow.class, flowKey).build();
1630     }
1631
1632     public static String getElanInterfaceJobKey(String interfaceName) {
1633         return "elaninterface-" + interfaceName;
1634     }
1635
1636     public void removeArpResponderFlow(BigInteger dpnId, String ingressInterfaceName, String ipAddress,
1637             int lportTag) {
1638         LOG.info("Removing the ARP responder flow on DPN {} of Interface {} with IP {}", dpnId, ingressInterfaceName,
1639                 ipAddress);
1640         ArpResponderUtil.removeFlow(mdsalManager, dpnId, ArpResponderUtil.getFlowId(lportTag, ipAddress));
1641     }
1642 }
1643
1644