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