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