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