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