ELAN FT Support for BE
[vpnservice.git] / elanmanager / elanmanager-impl / src / main / java / org / opendaylight / vpnservice / elan / utils / ElanUtils.java
1 /*
2  * Copyright (c) 2016 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.vpnservice.elan.utils;
9
10 import com.google.common.base.Optional;
11 import com.google.common.util.concurrent.FutureCallback;
12 import com.google.common.util.concurrent.Futures;
13 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
14 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
15 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
16 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
17 import org.opendaylight.vpnservice.elan.internal.ElanInstanceManager;
18 import com.google.common.util.concurrent.CheckedFuture;
19 import org.opendaylight.vpnservice.elan.internal.ElanServiceProvider;
20 import org.opendaylight.vpnservice.interfacemgr.globals.InterfaceInfo;
21 import org.opendaylight.vpnservice.interfacemgr.globals.InterfaceServiceUtil;
22 import org.opendaylight.vpnservice.itm.api.IITMProvider;
23 import org.opendaylight.vpnservice.mdsalutil.*;
24 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
25 import org.opendaylight.vpnservice.mdsalutil.interfaces.IMdsalApiManager;
26 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.PhysAddress;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.OutputActionCase;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.PushVlanActionCase;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.SetFieldCase;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
37 //import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice._interface.service.rev150602._interface.service.info.ServiceInfo;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.*;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.general.rev140714.ExtensionKey;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.general.rev140714.GeneralAugMatchNodesNodeTableFlow;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.general.rev140714.GeneralAugMatchNodesNodeTableFlowBuilder;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.general.rev140714.general.extension.grouping.ExtensionBuilder;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.general.rev140714.general.extension.list.grouping.ExtensionList;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.general.rev140714.general.extension.list.grouping.ExtensionListBuilder;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.*;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.nxm.nx.reg.grouping.NxmNxRegBuilder;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.*;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan._interface.forwarding.entries.ElanInterfaceMac;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan._interface.forwarding.entries.ElanInterfaceMacKey;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesList;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesListKey;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfaces;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfacesKey;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.forwarding.tables.MacTable;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.forwarding.tables.MacTableBuilder;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.forwarding.tables.MacTableKey;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.instances.ElanInstance;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.instances.ElanInstanceBuilder;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.instances.ElanInstanceKey;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.interfaces.ElanInterface;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.interfaces.ElanInterfaceKey;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.state.Elan;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.state.ElanBuilder;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.state.ElanKey;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.tag.name.map.ElanTagName;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.tag.name.map.ElanTagNameBuilder;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.tag.name.map.ElanTagNameKey;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.forwarding.entries.MacEntry;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.forwarding.entries.MacEntryKey;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.idmanager.rev150403.*;
71 //import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rev150331.IfIndexesInterfaceMap;
72 //import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rev150331._if.indexes._interface.map.IfIndexInterface;
73 //import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rev150331._if.indexes._interface.map.IfIndexInterfaceKey;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rpcs.rev151003.GetEgressActionsForInterfaceInputBuilder;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rpcs.rev151003.GetEgressActionsForInterfaceOutput;
76 import org.opendaylight.yangtools.yang.binding.DataObject;
77 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
78 import org.opendaylight.yangtools.yang.common.RpcResult;
79 import org.slf4j.Logger;
80 import org.slf4j.LoggerFactory;
81
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.meta.rev151007.IfIndexesInterfaceMap;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.meta.rev151007._if.indexes._interface.map.IfIndexInterface;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.meta.rev151007._if.indexes._interface.map.IfIndexInterfaceKey;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.servicebinding.rev151015.service.bindings.ServicesInfo;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.servicebinding.rev151015.ServiceBindings;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.servicebinding.rev151015.ServiceTypeFlowBased;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.servicebinding.rev151015.StypeOpenflow;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.servicebinding.rev151015.StypeOpenflowBuilder;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.servicebinding.rev151015.service.bindings.ServicesInfoKey;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.servicebinding.rev151015.service.bindings.services.info.BoundServices;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.servicebinding.rev151015.service.bindings.services.info.BoundServicesBuilder;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.servicebinding.rev151015.service.bindings.services.info.BoundServicesKey;
94
95
96 import java.math.BigInteger;
97 import java.util.ArrayList;
98 import java.util.List;
99 import java.util.concurrent.ExecutionException;
100 import java.util.concurrent.Future;
101
102 public class ElanUtils {
103
104     private static ElanServiceProvider elanServiceProvider;
105     private static final Logger logger = LoggerFactory.getLogger(ElanUtils.class);
106
107     public static final FutureCallback<Void> DEFAULT_CALLBACK =
108             new FutureCallback<Void>() {
109                 public void onSuccess(Void result) {
110                     logger.debug("Success in Datastore operation");
111                 }
112
113                 public void onFailure(Throwable error) {
114                     logger.error("Error in Datastore operation", error);
115                 };
116             };
117
118     public static Integer getUniqueId(IdManagerService idManager, String poolName, String idKey) {
119         AllocateIdInput getIdInput = new AllocateIdInputBuilder()
120                                            .setPoolName(poolName)
121                                            .setIdKey(idKey).build();
122
123         try {
124             Future<RpcResult<AllocateIdOutput>> result = idManager.allocateId(getIdInput);
125             RpcResult<AllocateIdOutput> rpcResult = result.get();
126             if(rpcResult.isSuccessful()) {
127                 return rpcResult.getResult().getIdValue().intValue();
128             } else {
129                 logger.warn("RPC Call to Allocate Id returned with Errors {}", rpcResult.getErrors());
130             }
131         } catch (InterruptedException | ExecutionException e) {
132             logger.warn("Exception when Allocating Id",e);
133         }
134         return 0;
135     }
136
137     public static void setElanServiceProvider(ElanServiceProvider elanService) {
138         elanServiceProvider = elanService;
139     }
140     public static void releaseId(IdManagerService idManager, String poolName, String idKey) {
141         ReleaseIdInput releaseIdInput = new ReleaseIdInputBuilder().setPoolName(poolName).setIdKey(idKey).build();
142         Future<RpcResult<Void>> result = idManager.releaseId(releaseIdInput);
143     }
144
145     public static <T extends DataObject> Optional<T> read(DataBroker broker, LogicalDatastoreType datastoreType,
146             InstanceIdentifier<T> path) {
147
148         ReadOnlyTransaction tx = broker.newReadOnlyTransaction();
149
150         Optional<T> result = Optional.absent();
151         try {
152             result = tx.read(datastoreType, path).get();
153         } catch (Exception e) {
154             throw new RuntimeException(e);
155         }
156
157         return result;
158     }
159
160
161     public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType, InstanceIdentifier<T> path) {
162         WriteTransaction tx = broker.newWriteOnlyTransaction();
163         tx.delete(datastoreType, path);
164         Futures.addCallback(tx.submit(), DEFAULT_CALLBACK);
165     }
166
167     public static InstanceIdentifier<ElanInstance> getElanInstanceIdentifier(String elanName) {
168         return InstanceIdentifier.builder(ElanInstances.class)
169                 .child(ElanInstance.class, new ElanInstanceKey(elanName)).build();
170     }
171
172     public static InstanceIdentifier<ElanInstance> getElanInstanceIdentifier() {
173         return InstanceIdentifier.builder(ElanInstances.class).child(ElanInstance.class).build();
174     }
175
176     //elan-instances config container
177     public static ElanInstance getElanInstanceByName(String elanInstanceName) {
178         DataBroker broker = elanServiceProvider.getBroker();
179         InstanceIdentifier<ElanInstance> elanIdentifierId = getElanInstanceConfigurationDataPath(elanInstanceName);
180         Optional<ElanInstance> elanInstance = read(broker, LogicalDatastoreType.CONFIGURATION, elanIdentifierId);
181         if(elanInstance.isPresent()) {
182             return elanInstance.get();
183         }
184         return null;
185     }
186
187     public static InstanceIdentifier<ElanInstance> getElanInstanceConfigurationDataPath(String elanInstanceName) {
188         return InstanceIdentifier.builder(ElanInstances.class).child(ElanInstance.class, new ElanInstanceKey(elanInstanceName)).build();
189     }
190
191     //elan-interfaces Config Container
192     public static ElanInterface getElanInterfaceByElanInterfaceName(String elanInterfaceName) {
193         DataBroker broker = elanServiceProvider.getBroker();
194         InstanceIdentifier<ElanInterface> elanInterfaceId = getElanInterfaceConfigurationDataPathId(elanInterfaceName);
195         Optional<ElanInterface> existingElanInterface = read(broker, LogicalDatastoreType.CONFIGURATION, elanInterfaceId);
196         if(existingElanInterface.isPresent()) {
197             return existingElanInterface.get();
198         }
199         return null;
200     }
201
202     public static class RegMatch {
203
204         final Class<? extends NxmNxReg> reg;
205         final Long value;
206
207         public RegMatch(Class<? extends NxmNxReg> reg, Long value) {
208             super();
209             this.reg = reg;
210             this.value = value;
211         }
212
213         public static RegMatch of(Class<? extends NxmNxReg> reg, Long value) {
214             return new RegMatch(reg, value);
215         }
216     }
217
218     public static void addNxRegMatch(MatchBuilder match, RegMatch... matches) {
219         ArrayList<ExtensionList> extensions = new ArrayList<>();
220         for (RegMatch rm : matches) {
221             Class<? extends ExtensionKey> key;
222             if (NxmNxReg0.class.equals(rm.reg)) {
223                 key = NxmNxReg0Key.class;
224             } else if (NxmNxReg1.class.equals(rm.reg)) {
225                 key = NxmNxReg1Key.class;
226             } else if (NxmNxReg2.class.equals(rm.reg)) {
227                 key = NxmNxReg2Key.class;
228             } else if (NxmNxReg3.class.equals(rm.reg)) {
229                 key = NxmNxReg3Key.class;
230             } else if (NxmNxReg4.class.equals(rm.reg)) {
231                 key = NxmNxReg4Key.class;
232             } else if (NxmNxReg5.class.equals(rm.reg)) {
233                 key = NxmNxReg5Key.class;
234             } else if (NxmNxReg6.class.equals(rm.reg)) {
235                 key = NxmNxReg6Key.class;
236             } else {
237                 key = NxmNxReg7Key.class;
238             }
239             NxAugMatchNodesNodeTableFlow am = new NxAugMatchNodesNodeTableFlowBuilder().setNxmNxReg(
240                     new NxmNxRegBuilder().setReg(rm.reg).setValue(rm.value).build()).build();
241             extensions.add(new ExtensionListBuilder().setExtensionKey(key)
242                     .setExtension(new ExtensionBuilder().addAugmentation(NxAugMatchNodesNodeTableFlow.class, am).build())
243                     .build());
244         }
245         GeneralAugMatchNodesNodeTableFlow m = new GeneralAugMatchNodesNodeTableFlowBuilder().setExtensionList(
246                 extensions).build();
247         match.addAugmentation(GeneralAugMatchNodesNodeTableFlow.class, m);
248     }
249
250     public static InstanceIdentifier<ElanInterface> getElanInterfaceConfigurationDataPathId(String interfaceName) {
251         return InstanceIdentifier.builder(ElanInterfaces.class).child(ElanInterface.class,
252                 new ElanInterfaceKey(interfaceName)).build();
253     }
254
255     //elan-state Operational container
256     public static Elan getElanByName(String elanInstanceName) {
257         DataBroker broker = elanServiceProvider.getBroker();
258         InstanceIdentifier<Elan> elanIdentifier = getElanInstanceOperationalDataPath(elanInstanceName);
259         Optional<Elan> elanInstance = read(broker, LogicalDatastoreType.OPERATIONAL, elanIdentifier);
260         if(elanInstance.isPresent()) {
261             return elanInstance.get();
262         }
263         return null;
264     }
265
266     public static InstanceIdentifier<Elan> getElanInstanceOperationalDataPath(String elanInstanceName) {
267         return InstanceIdentifier.builder(ElanState.class).child(Elan.class, new ElanKey(elanInstanceName)).build();
268     }
269
270     // grouping of forwarding-entries
271     public static MacEntry getInterfaceMacEntriesOperationalDataPath(String interfaceName, PhysAddress physAddress) {
272         DataBroker broker = elanServiceProvider.getBroker();
273         InstanceIdentifier<MacEntry> existingMacEntryId = getInterfaceMacEntriesIdentifierOperationalDataPath(interfaceName, physAddress);
274         Optional<MacEntry> existingInterfaceMacEntry = read(broker, LogicalDatastoreType.OPERATIONAL, existingMacEntryId);
275         if(existingInterfaceMacEntry.isPresent()) {
276             return existingInterfaceMacEntry.get();
277         }
278         return null;
279     }
280
281     public static MacEntry getInterfaceMacEntriesOperationalDataPathFromId(InstanceIdentifier identifier) {
282         DataBroker broker = elanServiceProvider.getBroker();
283         Optional<MacEntry> existingInterfaceMacEntry = read(broker, LogicalDatastoreType.OPERATIONAL, identifier);
284         if(existingInterfaceMacEntry.isPresent()) {
285             return existingInterfaceMacEntry.get();
286         }
287         return null;
288     }
289
290     public static InstanceIdentifier<MacEntry> getInterfaceMacEntriesIdentifierOperationalDataPath(String interfaceName, PhysAddress physAddress) {
291         return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class).child(ElanInterfaceMac.class,
292                 new ElanInterfaceMacKey(interfaceName)).child(MacEntry.class, new MacEntryKey(physAddress)).build();
293
294     }
295
296     //elan-forwarding-tables Operational container
297     public static MacEntry getMacTableByElanName(String elanName, PhysAddress physAddress) {
298         DataBroker broker = elanServiceProvider.getBroker();
299         InstanceIdentifier<MacEntry> macId =  getMacEntryOperationalDataPath(elanName, physAddress);
300         Optional<MacEntry> existingElanMacEntry = read(broker, LogicalDatastoreType.OPERATIONAL, macId);
301         if(existingElanMacEntry.isPresent()) {
302             return existingElanMacEntry.get();
303         }
304         return null;
305     }
306
307
308     public static MacEntry getMacEntryFromElanMacId(InstanceIdentifier identifier) {
309         DataBroker broker = elanServiceProvider.getBroker();
310         Optional<MacEntry> existingInterfaceMacEntry = read(broker, LogicalDatastoreType.OPERATIONAL, identifier);
311         if(existingInterfaceMacEntry.isPresent()) {
312             return existingInterfaceMacEntry.get();
313         }
314         return null;
315     }
316
317     public static InstanceIdentifier<MacEntry> getMacEntryOperationalDataPath(String elanName, PhysAddress physAddress) {
318         return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class,
319                 new MacTableKey(elanName)).child(MacEntry.class, new MacEntryKey(physAddress)).build();
320     }
321
322     public static InstanceIdentifier<MacTable> getElanMacTableOperationalDataPath(String elanName) {
323         return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class,
324                 new MacTableKey(elanName)).build();
325     }
326
327     //elan-interface-forwarding-entries Operational container
328     public static ElanInterfaceMac getElanInterfaceMacByInterfaceName(String interfaceName) {
329         DataBroker broker = elanServiceProvider.getBroker();
330         InstanceIdentifier<ElanInterfaceMac> elanInterfaceId = getElanInterfaceMacEntriesOperationalDataPath(interfaceName);
331         Optional<ElanInterfaceMac> existingElanInterface = read(broker, LogicalDatastoreType.OPERATIONAL, elanInterfaceId);
332         if(existingElanInterface.isPresent()) {
333             return existingElanInterface.get();
334         }
335         return null;
336     }
337
338     public static InstanceIdentifier<ElanInterfaceMac> getElanInterfaceMacEntriesOperationalDataPath(String interfaceName) {
339         return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class).child(ElanInterfaceMac.class,
340                 new ElanInterfaceMacKey(interfaceName)).build();
341     }
342
343     //elan-dpn-interfaces Operational Container
344     public static DpnInterfaces getElanInterfaceInfoByElanDpn(String elanInstanceName, BigInteger dpId) {
345         DataBroker broker = elanServiceProvider.getBroker();
346         InstanceIdentifier<DpnInterfaces> elanDpnInterfacesId = getElanDpnInterfaceOperationalDataPath(elanInstanceName, dpId);
347         Optional<DpnInterfaces> elanDpnInterfaces = read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfacesId);
348         if(elanDpnInterfaces.isPresent()) {
349             return elanDpnInterfaces.get();
350         }
351         return null;
352     }
353
354     public static InstanceIdentifier<DpnInterfaces> getElanDpnInterfaceOperationalDataPath(String elanInstanceName, BigInteger dpId) {
355         return InstanceIdentifier.builder(ElanDpnInterfaces.class).child(ElanDpnInterfacesList.class,
356                 new ElanDpnInterfacesListKey(elanInstanceName)).child(DpnInterfaces.class, new DpnInterfacesKey(dpId)).build();
357     }
358
359     //elan-tag-name-map Operational Container
360     public static ElanTagName getElanInfoByElanTag(long elanTag) {
361         DataBroker broker = elanServiceProvider.getBroker();
362         InstanceIdentifier<ElanTagName> elanId = getElanInfoEntriesOperationalDataPath(elanTag);
363         Optional<ElanTagName> existingElanInfo = ElanUtils.read(broker, LogicalDatastoreType.OPERATIONAL, elanId);
364         if(existingElanInfo.isPresent()) {
365             return existingElanInfo.get();
366         }
367         return null;
368     }
369
370     public static InstanceIdentifier<ElanTagName> getElanInfoEntriesOperationalDataPath(long elanTag) {
371         return InstanceIdentifier.builder(ElanTagNameMap.class).child(ElanTagName.class,
372                 new ElanTagNameKey(elanTag)).build();
373     }
374
375     // interface-index-tag operational container
376     public static IfIndexInterface getInterfaceInfoByInterfaceTag(long interfaceTag) {
377         DataBroker broker = elanServiceProvider.getBroker();
378         InstanceIdentifier<IfIndexInterface> interfaceId = getInterfaceInfoEntriesOperationalDataPath(interfaceTag);
379         Optional<IfIndexInterface> existingInterfaceInfo = ElanUtils.read(broker, LogicalDatastoreType.OPERATIONAL, interfaceId);
380         if(existingInterfaceInfo.isPresent()) {
381             return existingInterfaceInfo.get();
382         }
383         return null;
384     }
385
386     public static InstanceIdentifier<IfIndexInterface> getInterfaceInfoEntriesOperationalDataPath(long interfaceTag) {
387         return InstanceIdentifier.builder(IfIndexesInterfaceMap.class).child(IfIndexInterface.class,
388                 new IfIndexInterfaceKey((int) interfaceTag)).build();
389     }
390
391
392
393     public static InstanceIdentifier<ElanDpnInterfacesList> getElanDpnOperationDataPath(String elanInstanceName) {
394         return InstanceIdentifier.builder(ElanDpnInterfaces.class).child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName)).build();
395     }
396
397     public static  ElanDpnInterfacesList getElanDpnInterfacesList(String elanName) {
398         DataBroker broker = elanServiceProvider.getBroker();
399         InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanName);
400         Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = ElanUtils.read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
401         if(existingElanDpnInterfaces.isPresent()) {
402             return existingElanDpnInterfaces.get();
403         }
404         return null;
405     }
406
407     public static  ElanDpnInterfaces getElanDpnInterfacesList() {
408         DataBroker broker = elanServiceProvider.getBroker();
409         InstanceIdentifier<ElanDpnInterfaces> elanDpnInterfaceId = InstanceIdentifier.builder(ElanDpnInterfaces.class).build();
410         Optional<ElanDpnInterfaces> existingElanDpnInterfaces = ElanUtils.read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
411         if(existingElanDpnInterfaces.isPresent()) {
412             return existingElanDpnInterfaces.get();
413         }
414         return null;
415     }
416
417     public static ElanForwardingTables getElanForwardingList() {
418         DataBroker broker = elanServiceProvider.getBroker();
419         InstanceIdentifier<ElanForwardingTables> elanForwardingTableId = InstanceIdentifier.builder(ElanForwardingTables.class).build();
420         Optional<ElanForwardingTables> existingElanForwardingList = ElanUtils.read(broker, LogicalDatastoreType.OPERATIONAL, elanForwardingTableId);
421         if(existingElanForwardingList.isPresent()) {
422             return existingElanForwardingList.get();
423         }
424         return null;
425     }
426
427
428     public static long getElanLocalBCGID(long elanTag) {
429         return ElanConstants.ELAN_GID_MIN + (((elanTag % ElanConstants.ELAN_GID_MIN) *2) - 1);
430     }
431
432     public static long getElanRemoteBCGID(long elanTag) {
433         return ElanConstants.ELAN_GID_MIN + (((elanTag % ElanConstants.ELAN_GID_MIN) *2));
434     }
435
436     public static BigInteger getElanMetadataLabel(long elanTag) {
437         return (BigInteger.valueOf(elanTag)).shiftLeft(24);
438     }
439
440     public static BigInteger getElanMetadataLabel(long elanTag, int lportTag) {
441         return getElanMetadataLabel(elanTag).or(MetaDataUtil.getLportTagMetaData(lportTag));
442     }
443
444     public static BigInteger getElanMetadataMask() {
445         return MetaDataUtil.METADATA_MASK_SERVICE.or(MetaDataUtil.METADATA_MASK_LPORT_TAG);
446     }
447
448     public static void setupMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
449                                      String macAddress) {
450         IMdsalApiManager mdsalApiManager = elanServiceProvider.getMdsalManager();
451         DataBroker broker = elanServiceProvider.getBroker();
452         IITMProvider itmManager = elanServiceProvider.getItmManager();
453         synchronized (macAddress) {
454             logger.info("Acquired lock for mac : " + macAddress + "Proceeding with install operation.");
455             setupKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress, mdsalApiManager);
456             setupTermDmacFlows(interfaceInfo, itmManager);
457             setupOrigDmacFlows(elanInfo, interfaceInfo, macAddress, mdsalApiManager, broker);
458         }
459     }
460
461     public static void setupDMacFlowonRemoteDpn(ElanInstance elanInfo, InterfaceInfo interfaceInfo, BigInteger dstDpId,
462                                      String macAddress) {
463         synchronized (macAddress) {
464             logger.info("Acquired lock for mac : " + macAddress + "Proceeding with install operation.");
465             setupOrigDmacFlowsonRemoteDpn(elanInfo, interfaceInfo, dstDpId, macAddress);
466         }
467     }
468
469
470     private static void setupKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
471                                            String macAddress, IMdsalApiManager mdsalApiManager) {
472         FlowEntity flowEntity = getKnownSmacFlowEntity(elanInfo, interfaceInfo, macTimeout, macAddress);
473         mdsalApiManager.installFlow(flowEntity);
474         if (logger.isDebugEnabled()) {
475             logger.debug("Known Smac flow entry created for elan Name:{}, logical Interface port:{} and mac address:{}", elanInfo.getElanInstanceName(), elanInfo.getDescription(), macAddress);
476         }
477     }
478
479     private static FlowEntity getKnownSmacFlowEntity(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout, String macAddress) {
480         BigInteger dpId = interfaceInfo.getDpId();
481         int lportTag = interfaceInfo.getInterfaceTag();
482         long elanTag = elanInfo.getElanTag();
483         // Matching metadata and eth_src fields
484         List<MatchInfo> mkMatches = new ArrayList<MatchInfo>();
485         mkMatches.add(new MatchInfo(MatchFieldType.metadata, new BigInteger[] {
486                 ElanUtils.getElanMetadataLabel(elanInfo.getElanTag(), lportTag),
487                 ElanUtils.getElanMetadataMask() }));
488         mkMatches.add(new MatchInfo(MatchFieldType.eth_src, new String[] { macAddress }));
489         List<InstructionInfo> mkInstructions = new ArrayList<InstructionInfo>();
490         mkInstructions.add(new InstructionInfo(InstructionType.goto_table, new long[] { ElanConstants.ELAN_DMAC_TABLE }));
491
492         FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpId, ElanConstants.ELAN_SMAC_TABLE,
493                 getKnownDynamicmacFlowRef(ElanConstants.ELAN_SMAC_TABLE, dpId, lportTag, macAddress, elanTag),
494                 20, elanInfo.getDescription(), (int)macTimeout, 0, ElanConstants.COOKIE_ELAN_KNOWN_SMAC.add(BigInteger.valueOf(elanTag)),
495                 mkMatches, mkInstructions);
496         flowEntity.setStrictFlag(true);
497         flowEntity.setSendFlowRemFlag(macTimeout != 0); //If Mac timeout is 0, the flow wont be deleted automatically, so no need to get notified
498         return flowEntity;
499     }
500
501     private static void setupTermDmacFlows(InterfaceInfo interfaceInfo, IITMProvider itmManager) {
502         BigInteger dpId = interfaceInfo.getDpId();
503         long lportGroupId = interfaceInfo.getGroupId();
504         int lportTag = interfaceInfo.getInterfaceTag();
505         List <ActionInfo> actionsInfos = new ArrayList <ActionInfo> ();
506         actionsInfos = getEgressActionsForInterface(interfaceInfo.getInterfaceName());
507
508         //FIXME [ELANBE] ITM Service API to invoke Terminating Service
509         //itmManager.createTerminatingServiceActions(dpId, lportTag, actionsInfos);
510         if (logger.isDebugEnabled()) {
511             logger.debug("Terminating service table flow entry created on dpn:{} for logical Interface port:{}", dpId, interfaceInfo.getPortName());
512         }
513     }
514
515     public static List<ActionInfo> getEgressActionsForInterface(String ifName) {
516         List<ActionInfo> listActionInfo = new ArrayList<ActionInfo>();
517         try {
518             Future<RpcResult<GetEgressActionsForInterfaceOutput>> result =
519                     elanServiceProvider.getInterfaceManagerRpcService().getEgressActionsForInterface(
520                             new GetEgressActionsForInterfaceInputBuilder().setIntfName(ifName).build());
521             RpcResult<GetEgressActionsForInterfaceOutput> rpcResult = result.get();
522             System.out.println("Data is populated");
523             if(!rpcResult.isSuccessful()) {
524                 logger.warn("RPC Call to Get egress actions for interface {} returned with Errors {}", ifName, rpcResult.getErrors());
525             } else {
526                 List<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action> actions =
527                         rpcResult.getResult().getAction();
528                 for (Action action : actions) {
529                     org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.Action actionClass = action.getAction();
530                     if (actionClass instanceof OutputActionCase) {
531                         System.out.println("Data ");
532                         listActionInfo.add(new ActionInfo(ActionType.output,
533                                 new String[] {((OutputActionCase)actionClass).getOutputAction()
534                                         .getOutputNodeConnector().getValue()}));
535                     } else if (actionClass instanceof PushVlanActionCase) {
536                         listActionInfo.add(new ActionInfo(ActionType.push_vlan, new String[] {}));
537                     } else if (actionClass instanceof SetFieldCase) {
538                         if (((SetFieldCase)actionClass).getSetField().getVlanMatch() != null) {
539                             int vlanVid = ((SetFieldCase)actionClass).getSetField().getVlanMatch().getVlanId().getVlanId().getValue();
540                             listActionInfo.add(new ActionInfo(ActionType.set_field_vlan_vid,
541                                     new String[] { Long.toString(vlanVid) }));
542                         }
543                     }
544                 }
545             }
546         } catch (InterruptedException | ExecutionException e) {
547             logger.warn("Exception when egress actions for interface {}", ifName, e);
548         }
549         return listActionInfo;
550     }
551
552     private static void setupOrigDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
553                                            IMdsalApiManager mdsalApiManager, DataBroker broker) {
554         BigInteger dpId = interfaceInfo.getDpId();
555         String ifName = interfaceInfo.getInterfaceName();
556         long ifTag = interfaceInfo.getInterfaceTag();
557         long groupId = interfaceInfo.getGroupId();
558         String elanInstanceName = elanInfo.getElanInstanceName();
559         List<DpnInterfaces> remoteFEs = getInvolvedDpnsInElan(elanInstanceName);
560         if(remoteFEs != null) {
561             for (DpnInterfaces remoteFE : remoteFEs) {
562                 Long elanTag = elanInfo.getElanTag();
563                 if (remoteFE.getDpId().equals(dpId)) {
564                     // On the local FE set up a direct output flow
565                     setupLocalDmacFlow(elanTag, dpId, ifName, macAddress, elanInstanceName, mdsalApiManager, ifTag);
566                     if (logger.isDebugEnabled()) {
567                         logger.debug("Dmac flow entry created for elan Name:{}, logical port Name:{} and mac address:{} on dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, dpId);
568                     }
569                 } else {
570                     if (isDpnPresent(remoteFE.getDpId())) {
571                         // Check for the Remote DPN present in Inventory Manager
572                         setupRemoteDmacFlow(remoteFE.getDpId(), dpId, interfaceInfo.getInterfaceTag(), elanTag, macAddress, elanInstanceName);
573                         if (logger.isDebugEnabled()) {
574                             logger.debug("Dmac flow entry created for elan Name:{}, logical port Name:{} and mac address:{} on dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, remoteFE.getDpId());
575                         }
576                     }
577                 }
578             }
579         }
580     }
581
582     private static void setupOrigDmacFlowsonRemoteDpn(ElanInstance elanInfo, InterfaceInfo interfaceInfo, BigInteger dstDpId, String macAddress) {
583         BigInteger dpId = interfaceInfo.getDpId();
584         String elanInstanceName = elanInfo.getElanInstanceName();
585         List<DpnInterfaces> remoteFEs = getInvolvedDpnsInElan(elanInstanceName);
586         for(DpnInterfaces remoteFE: remoteFEs) {
587             Long elanTag = elanInfo.getElanTag();
588             if (remoteFE.getDpId().equals(dstDpId)) {
589                 // Check for the Remote DPN present in Inventory Manager
590                 setupRemoteDmacFlow(dstDpId, dpId, interfaceInfo.getInterfaceTag(), elanTag, macAddress, elanInstanceName);
591                 if (logger.isDebugEnabled()) {
592                     logger.debug("Dmac flow entry created for elan Name:{}, logical port Name:{} and mac address {} on dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, remoteFE.getDpId());
593                 }
594                 break;
595             }
596         }
597     }
598
599
600     @SuppressWarnings("unchecked")
601     public static List<DpnInterfaces> getInvolvedDpnsInElan(String elanName) {
602         List<DpnInterfaces> dpns = ElanInstanceManager.getElanInstanceManager().getElanDPNByName(elanName);
603         return dpns;
604     }
605
606     private static void setupLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
607                                            String displayName, IMdsalApiManager mdsalApiManager, long ifTag) {
608         FlowEntity flowEntity = getLocalDmacFlowEntry(elanTag, dpId, ifName, macAddress, displayName, ifTag);
609         mdsalApiManager.installFlow(flowEntity);
610
611     }
612
613     public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, long lporTag, String macAddress, long elanTag) {
614         return new StringBuffer().append(tableId).append(elanTag).append(dpId).append(lporTag).append(macAddress).toString();
615     }
616
617     public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, BigInteger remoteDpId, String macAddress, long elanTag) {
618         return new StringBuffer().append(tableId).append(elanTag).append(dpId).append(remoteDpId).append(macAddress).toString();
619     }
620
621     public static FlowEntity getLocalDmacFlowEntry(long elanTag, BigInteger dpId, String ifName, String macAddress,
622                                                    String displayName, long ifTag) {
623         List<MatchInfo> mkMatches = new ArrayList<MatchInfo>();
624         mkMatches.add(new MatchInfo(MatchFieldType.metadata, new BigInteger[] {
625                 ElanUtils.getElanMetadataLabel(elanTag),
626                 MetaDataUtil.METADATA_MASK_SERVICE }));
627         mkMatches.add(new MatchInfo(MatchFieldType.eth_dst, new String[] { macAddress }));
628
629         List<InstructionInfo> mkInstructions = new ArrayList<InstructionInfo>();
630         List <ActionInfo> actionsInfos = new ArrayList <ActionInfo> ();
631         actionsInfos.addAll(getEgressActionsForInterface(ifName));
632         mkInstructions.add(new InstructionInfo(InstructionType.write_actions, actionsInfos));
633
634         FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpId, ElanConstants.ELAN_DMAC_TABLE,
635                 getKnownDynamicmacFlowRef(ElanConstants.ELAN_DMAC_TABLE, dpId, ifTag, macAddress, elanTag),
636                 20, displayName, 0, 0, ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)),
637                 mkMatches, mkInstructions);
638         return flowEntity;
639     }
640
641     public static void setupRemoteDmacFlow(BigInteger srcDpId, BigInteger destDpId, int lportTag, long elanTag, String macAddress,
642                                            String displayName) {
643         IMdsalApiManager mdsalApiManager = elanServiceProvider.getMdsalManager();
644         FlowEntity flowEntity = getRemoteDmacFlowEntry(srcDpId, destDpId, lportTag, elanTag, macAddress, displayName);
645         mdsalApiManager.installFlow(flowEntity);
646     }
647
648     public static FlowEntity getRemoteDmacFlowEntry(BigInteger srcDpId, BigInteger destDpId, int lportTag, long elanTag,
649                                                     String macAddress, String displayName) {
650         IITMProvider itmManager = elanServiceProvider.getItmManager();
651         List<MatchInfo> mkMatches = new ArrayList<MatchInfo>();
652         mkMatches.add(new MatchInfo(MatchFieldType.metadata, new BigInteger[]{
653                 ElanUtils.getElanMetadataLabel(elanTag),
654                 MetaDataUtil.METADATA_MASK_SERVICE }));
655         mkMatches.add(new MatchInfo(MatchFieldType.eth_dst, new String[] { macAddress }));
656
657         List<InstructionInfo> mkInstructions = new ArrayList<InstructionInfo>();
658         //List of ActionInfo for the provided Source and Destination DPIDs
659         try {
660             //FIXME [ELANBE] Removing ITM API for now, will need this for multi dpn.
661             //List<ActionInfo> actionsInfos = itmManager.ITMIngressGetActions(srcDpId, destDpId, lportTag);
662             //mkInstructions.add(new InstructionInfo(InstructionType.write_actions, actionsInfos));
663         } catch (Exception e) {
664             logger.error("Interface Not Found exception");
665         }
666
667         FlowEntity flowEntity = MDSALUtil.buildFlowEntity(srcDpId, ElanConstants.ELAN_DMAC_TABLE,
668                 getKnownDynamicmacFlowRef(ElanConstants.ELAN_DMAC_TABLE, srcDpId, destDpId, macAddress, elanTag),
669                 20, displayName, 0, 0, ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)),
670                 mkMatches, mkInstructions);
671         return flowEntity;
672     }
673
674     public static void deleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, MacEntry macEntry) {
675         if (elanInfo == null || interfaceInfo == null) {
676             return;
677         }
678         String macAddress = macEntry.getMacAddress().getValue();
679         synchronized (macAddress) {
680             logger.info("Acquired lock for mac : " + macAddress + "Proceeding with remove operation.");
681             deleteMacFlows(elanInfo, interfaceInfo,  macAddress, true);
682         }
683     }
684
685     public static void deleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress, boolean deleteSmac) {
686         String elanInstanceName = elanInfo.getElanInstanceName();
687         String ifName = interfaceInfo.getInterfaceName();
688         long ifTag = interfaceInfo.getInterfaceTag();
689         List<DpnInterfaces> remoteFEs = getInvolvedDpnsInElan(elanInstanceName);
690         IMdsalApiManager mdsalApiManager = elanServiceProvider.getMdsalManager();
691         IITMProvider itmManager = elanServiceProvider.getItmManager();
692         BigInteger srcdpId = interfaceInfo.getDpId();
693         String displayName = elanInstanceName;
694         long groupId = interfaceInfo.getGroupId();
695         for (DpnInterfaces dpnInterface: remoteFEs) {
696             Long elanTag = elanInfo.getElanTag();
697             if (dpnInterface.getDpId().equals(srcdpId)) {
698                 if(deleteSmac) {
699                     mdsalApiManager.removeFlow(getKnownSmacFlowEntity(elanInfo, interfaceInfo, 0, macAddress));
700                 }
701                 mdsalApiManager.removeFlow(getLocalDmacFlowEntry(elanTag, dpnInterface.getDpId(), ifName, macAddress, displayName, ifTag));
702
703                 //FIXME [ELANBE] Removing ITM API for now, will need this for multi dpn.
704                 //itmManager.removeTerminatingServiceAction(dpnInterface.getDpId(), interfaceInfo.getInterfaceTag());
705                   if (logger.isDebugEnabled()) {
706                     logger.debug("All the required flows deleted for elan:{}, logical Interface port:{} and mac address:{} on dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, dpnInterface.getDpId());
707                 }
708             } else if (isDpnPresent(dpnInterface.getDpId())) {
709                 mdsalApiManager.removeFlow(
710                         getRemoteDmacFlowEntry(dpnInterface.getDpId(), srcdpId, interfaceInfo.getInterfaceTag(), elanTag, macAddress,
711                                 displayName));
712                 if (logger.isDebugEnabled()) {
713                     logger.debug("Dmac flow entry deleted for elan:{}, logical interface port:{} and mac address:{} on dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, dpnInterface.getDpId());
714                 }
715             }
716         }
717     }
718
719     public static void UpdateOperationalDataStore(DataBroker broker, IdManagerService idManager, ElanInstance elanInstanceAdded) {
720         String elanInstanceName = elanInstanceAdded.getElanInstanceName();
721         long elanTag = ElanUtils.getUniqueId(idManager, ElanConstants.ELAN_ID_POOL_NAME, elanInstanceName);
722         Elan elanInfo = new ElanBuilder().setName(elanInstanceName).setKey(new ElanKey(elanInstanceName)).build();
723         //Add the ElanState in the elan-state operational data-store
724         MDSALUtil.syncWrite(broker, LogicalDatastoreType.OPERATIONAL, ElanUtils.getElanInstanceOperationalDataPath(elanInstanceName), elanInfo);
725         //Add the ElanMacTable in the elan-mac-table operational data-store
726         MacTable elanMacTable = new MacTableBuilder().setKey(new MacTableKey(elanInstanceName)).build();
727         MDSALUtil.syncWrite(broker, LogicalDatastoreType.OPERATIONAL, ElanUtils.getElanMacTableOperationalDataPath(elanInstanceName), elanMacTable);
728         ElanTagName elanTagName = new ElanTagNameBuilder().setElanTag(elanTag).setKey(new ElanTagNameKey(elanTag)).setName(elanInstanceName).build();
729         //Add the ElanTag to ElanName in the elan-tag-name Operational data-store
730         MDSALUtil.syncWrite(broker, LogicalDatastoreType.OPERATIONAL, ElanUtils.getElanInfoEntriesOperationalDataPath(elanTag), elanTagName);
731         ElanInstance elanInstanceWithTag = new ElanInstanceBuilder().setElanInstanceName(elanInstanceName).setDescription(elanInstanceAdded.getDescription()).setMacTimeout(elanInstanceAdded
732                 .getMacTimeout() == null ? ElanConstants.DEFAULT_MAC_TIME_OUT : elanInstanceAdded.getMacTimeout()).setKey(elanInstanceAdded.getKey()).setElanTag(elanTag).build();
733         MDSALUtil.syncUpdate(broker, LogicalDatastoreType.CONFIGURATION, getElanInstanceIdentifier(elanInstanceName), elanInstanceWithTag);
734     }
735
736     public static boolean isDpnPresent(BigInteger dpnId) {
737         DataBroker broker = elanServiceProvider.getBroker();
738         boolean isPresent = false;
739         String dpn = String.format("%s:%s", "openflow",dpnId);
740         NodeId nodeId = new NodeId(dpn);
741         InstanceIdentifier<Node> node = InstanceIdentifier.builder(Nodes.class).child(Node.class, new NodeKey(nodeId)).build();
742         Optional<Node> nodePresent = read(broker, LogicalDatastoreType.OPERATIONAL, node);
743         if(nodePresent.isPresent()) {
744             isPresent = true;
745         }
746         return isPresent;
747     }
748
749     public static ServicesInfo getServiceInfo(String elanInstanceName, long elanTag, String interfaceName) {
750         int priority = ElanConstants.ELAN_SERVICE_PRIORITY;
751         int instructionKey = 0;
752         List<Instruction> instructions = new ArrayList<Instruction>();
753         instructions.add(MDSALUtil.buildAndGetWriteMetadaInstruction(ElanUtils.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE, ++instructionKey));
754         instructions.add(MDSALUtil.buildAndGetGotoTableInstruction(ElanConstants.ELAN_SMAC_TABLE, ++instructionKey));
755
756         ServicesInfo serviceInfo = InterfaceServiceUtil.buildServiceInfo(String.format("%s.%s", elanInstanceName, interfaceName), ElanConstants.ELAN_SERVICE_INDEX,
757                 priority, ElanConstants.COOKIE_ELAN_INGRESS_TABLE, instructions);
758         return serviceInfo;
759     }
760
761     public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
762                                               InstanceIdentifier<T> path, FutureCallback<Void> callback) {
763         WriteTransaction tx = broker.newWriteOnlyTransaction();
764         tx.delete(datastoreType, path);
765         Futures.addCallback(tx.submit(), callback);
766     }
767
768     public static <T extends DataObject> void syncWrite(DataBroker broker, LogicalDatastoreType datastoreType,
769                                                         InstanceIdentifier<T> path, T data) {
770         WriteTransaction tx = broker.newWriteOnlyTransaction();
771         tx.put(datastoreType, path, data, true);
772         CheckedFuture<Void, TransactionCommitFailedException> futures = tx.submit();
773         try {
774             futures.get();
775         } catch (InterruptedException | ExecutionException e) {
776             logger.error("Error writing to datastore (path, data) : ({}, {})", path, data);
777             throw new RuntimeException(e.getMessage());
778         }
779     }
780
781
782     public static BoundServices getBoundServices(String serviceName, short servicePriority, int flowPriority,
783                                                  BigInteger cookie, List<Instruction> instructions) {
784         StypeOpenflowBuilder augBuilder = new StypeOpenflowBuilder().setFlowCookie(cookie).setFlowPriority(flowPriority).setInstruction(instructions);
785         return new BoundServicesBuilder().setKey(new BoundServicesKey(servicePriority))
786                 .setServiceName(serviceName).setServicePriority(servicePriority)
787                 .setServiceType(ServiceTypeFlowBased.class).addAugmentation(StypeOpenflow.class, augBuilder.build()).build();
788     }
789
790     public static InstanceIdentifier<BoundServices> buildServiceId(String vpnInterfaceName, short serviceIndex) {
791         return InstanceIdentifier.builder(ServiceBindings.class).child(ServicesInfo.class, new ServicesInfoKey(vpnInterfaceName))
792                 .child(BoundServices.class, new BoundServicesKey(serviceIndex)).build();
793     }
794
795 }