Cache DataTreeModification.getDataAfter()
[netvirt.git] / elanmanager / impl / src / main / java / org / opendaylight / netvirt / elan / l2gw / ha / HwvtepHAUtil.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.l2gw.ha;
9
10 import static org.opendaylight.controller.md.sal.binding.api.WriteTransaction.CREATE_MISSING_PARENTS;
11 import static org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType.OPERATIONAL;
12
13 import com.google.common.base.Optional;
14 import com.google.common.base.Strings;
15 import java.nio.charset.StandardCharsets;
16 import java.util.ArrayList;
17 import java.util.Collection;
18 import java.util.HashMap;
19 import java.util.HashSet;
20 import java.util.List;
21 import java.util.Set;
22 import java.util.concurrent.ExecutionException;
23 import java.util.stream.Collectors;
24 import javax.annotation.Nullable;
25 import org.opendaylight.controller.md.sal.binding.api.DataObjectModification;
26 import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
27 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
28 import org.opendaylight.genius.infra.Datastore;
29 import org.opendaylight.genius.infra.Datastore.Configuration;
30 import org.opendaylight.genius.infra.Datastore.Operational;
31 import org.opendaylight.genius.infra.TypedReadWriteTransaction;
32 import org.opendaylight.genius.infra.TypedWriteTransaction;
33 import org.opendaylight.genius.utils.hwvtep.HwvtepNodeHACache;
34 import org.opendaylight.netvirt.elan.l2gw.ha.commands.SwitchesCmd;
35 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Uri;
36 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepGlobalAugmentation;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepGlobalAugmentationBuilder;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepLogicalSwitchRef;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepNodeName;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepPhysicalLocatorRef;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.PhysicalSwitchAugmentation;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.PhysicalSwitchAugmentationBuilder;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.global.attributes.LogicalSwitches;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.global.attributes.LogicalSwitchesKey;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.global.attributes.Managers;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.global.attributes.ManagersBuilder;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.global.attributes.ManagersKey;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.global.attributes.Switches;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.global.attributes.managers.ManagerOtherConfigs;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.global.attributes.managers.ManagerOtherConfigsBuilder;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.global.attributes.managers.ManagerOtherConfigsKey;
53 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
54 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
55 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId;
56 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TpId;
57 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
58 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
59 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
60 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder;
61 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
62 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.node.TerminationPoint;
63 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.node.TerminationPointKey;
64 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
65 import org.slf4j.Logger;
66 import org.slf4j.LoggerFactory;
67
68 public final class HwvtepHAUtil {
69
70     private static final Logger LOG = LoggerFactory.getLogger(HwvtepHAUtil.class);
71
72     //TODO reuse HWvtepSouthboundConstants
73     public static final String HA_ENABLED = "ha_enabled";
74     public static final String HWVTEP_ENTITY_TYPE = "hwvtep";
75     public static final String TEP_PREFIX = "vxlan_over_ipv4:";
76     public static final String HA_ID = "ha_id";
77     public static final String HA_CHILDREN = "ha_children";
78     public static final String PHYSICALSWITCH = "/physicalswitch/";
79     public static final TopologyId HWVTEP_TOPOLOGY_ID = new TopologyId(new Uri("hwvtep:1"));
80     public static final String UUID = "uuid";
81     public static final String HWVTEP_URI_PREFIX = "hwvtep";
82     public static final String MANAGER_KEY = "managerKey";
83     public static final String L2GW_JOB_KEY = ":l2gw";
84
85     private HwvtepHAUtil() { }
86
87     public static HwvtepPhysicalLocatorRef buildLocatorRef(InstanceIdentifier<Node> nodeIid, String tepIp) {
88         InstanceIdentifier<TerminationPoint> tepId = buildTpId(nodeIid, tepIp);
89         return new HwvtepPhysicalLocatorRef(tepId);
90     }
91
92     public static String getNodeIdVal(InstanceIdentifier<?> iid) {
93         return iid.firstKeyOf(Node.class).getNodeId().getValue();
94     }
95
96     public static Uuid getUUid(String key) {
97         return new Uuid(java.util.UUID.nameUUIDFromBytes(key.getBytes(StandardCharsets.UTF_8)).toString());
98     }
99
100     public static InstanceIdentifier<TerminationPoint> buildTpId(InstanceIdentifier<Node> nodeIid,String tepIp) {
101         String tpKeyStr = TEP_PREFIX + tepIp;
102         TerminationPointKey tpKey = new TerminationPointKey(new TpId(tpKeyStr));
103         InstanceIdentifier<TerminationPoint> plIid = nodeIid.child(TerminationPoint.class, tpKey);
104         return plIid;
105     }
106
107     public static String getTepIpVal(HwvtepPhysicalLocatorRef locatorRef) {
108         InstanceIdentifier<TerminationPoint> tpId = (InstanceIdentifier<TerminationPoint>) locatorRef.getValue();
109         return tpId.firstKeyOf(TerminationPoint.class).getTpId().getValue().substring("vxlan_over_ipv4:".length());
110     }
111
112     public static String getLogicalSwitchSwitchName(HwvtepLogicalSwitchRef logicalSwitchRef) {
113         InstanceIdentifier<LogicalSwitches> id = (InstanceIdentifier<LogicalSwitches>) logicalSwitchRef.getValue();
114         return id.firstKeyOf(LogicalSwitches.class).getHwvtepNodeName().getValue();
115     }
116
117     public static String getNodeIdFromLocatorRef(HwvtepPhysicalLocatorRef locatorRef) {
118         InstanceIdentifier<TerminationPoint> tpId = (InstanceIdentifier<TerminationPoint>) locatorRef.getValue();
119         return tpId.firstKeyOf(Node.class).getNodeId().getValue();
120     }
121
122     public static String getNodeIdFromLogicalSwitches(HwvtepLogicalSwitchRef logicalSwitchRef) {
123         InstanceIdentifier<LogicalSwitches> id = (InstanceIdentifier<LogicalSwitches>) logicalSwitchRef.getValue();
124         return id.firstKeyOf(Node.class).getNodeId().getValue();
125     }
126
127     public static InstanceIdentifier<Node> createInstanceIdentifierFromHAId(String haUUidVal) {
128         String nodeString = HWVTEP_URI_PREFIX + "://"
129             + UUID + "/" + java.util.UUID.nameUUIDFromBytes(haUUidVal.getBytes(StandardCharsets.UTF_8)).toString();
130         NodeId nodeId = new NodeId(new Uri(nodeString));
131         NodeKey nodeKey = new NodeKey(nodeId);
132         TopologyKey topoKey = new TopologyKey(HWVTEP_TOPOLOGY_ID);
133         return InstanceIdentifier.builder(NetworkTopology.class)
134                 .child(Topology.class, topoKey)
135                 .child(Node.class, nodeKey)
136                 .build();
137     }
138
139     public static InstanceIdentifier<Node> convertToInstanceIdentifier(String nodeIdString) {
140         NodeId nodeId = new NodeId(new Uri(nodeIdString));
141         NodeKey nodeKey = new NodeKey(nodeId);
142         TopologyKey topoKey = new TopologyKey(HWVTEP_TOPOLOGY_ID);
143         return InstanceIdentifier.builder(NetworkTopology.class)
144                 .child(Topology.class, topoKey)
145                 .child(Node.class, nodeKey)
146                 .build();
147     }
148
149     /**
150      * Build other config data for HA node .
151      *
152      * @param key The key as in HA child device other config
153      * @param val The value as in HA child device other config
154      * @return return other config object
155      */
156     public static ManagerOtherConfigsBuilder getOtherConfigBuilder(String key, String val) {
157         ManagerOtherConfigsBuilder otherConfigsBuilder = new ManagerOtherConfigsBuilder();
158         ManagerOtherConfigsKey otherConfigsKey = new ManagerOtherConfigsKey(key);
159         otherConfigsBuilder.withKey(otherConfigsKey);
160         otherConfigsBuilder.setOtherConfigKey(key);
161         otherConfigsBuilder.setOtherConfigValue(val);
162         return otherConfigsBuilder;
163     }
164
165     public static String convertToGlobalNodeId(String psNodeId) {
166         int idx = psNodeId.indexOf(PHYSICALSWITCH);
167         if (idx > 0) {
168             return psNodeId.substring(0, idx);
169         }
170         return psNodeId;
171     }
172
173     /**
174      * Trnaform logical switch to nodepath passed .
175      *
176      * @param src {@link HwvtepLogicalSwitchRef} Logical Switch Ref which needs to be transformed
177      * @param nodePath {@link InstanceIdentifier} src needs to be transformed to this path
178      * @return ref {@link HwvtepLogicalSwitchRef} the transforrmed result
179      */
180     public static HwvtepLogicalSwitchRef convertLogicalSwitchRef(HwvtepLogicalSwitchRef src,
181                                                                  InstanceIdentifier<Node> nodePath) {
182         InstanceIdentifier<LogicalSwitches> srcId = (InstanceIdentifier<LogicalSwitches>)src.getValue();
183         HwvtepNodeName switchName = srcId.firstKeyOf(LogicalSwitches.class).getHwvtepNodeName();
184         InstanceIdentifier<LogicalSwitches> iid = nodePath.augmentation(HwvtepGlobalAugmentation.class)
185                 .child(LogicalSwitches.class, new LogicalSwitchesKey(switchName));
186         HwvtepLogicalSwitchRef ref = new HwvtepLogicalSwitchRef(iid);
187         return ref;
188     }
189
190     /**
191      * Trnaform locator reference to nodepath passed .
192      *
193      * @param src {@link HwvtepPhysicalLocatorRef} Logical Switch Ref which needs to be transformed
194      * @param nodePath {@link InstanceIdentifier} src needs to be transformed to this path
195      * @return physicalLocatorRef {@link HwvtepPhysicalLocatorRef} the transforrmed result
196      */
197     public static HwvtepPhysicalLocatorRef convertLocatorRef(HwvtepPhysicalLocatorRef src,
198                                                              InstanceIdentifier<Node> nodePath) {
199         InstanceIdentifier<TerminationPoint> srcTepPath = (InstanceIdentifier<TerminationPoint>)src.getValue();
200         TpId tpId = srcTepPath.firstKeyOf(TerminationPoint.class).getTpId();
201         InstanceIdentifier<TerminationPoint> tpPath =
202                 nodePath.child(TerminationPoint.class, new TerminationPointKey(tpId));
203         HwvtepPhysicalLocatorRef physicalLocatorRef = new HwvtepPhysicalLocatorRef(tpPath);
204         return physicalLocatorRef;
205     }
206
207     public static boolean isEmptyList(@Nullable List list) {
208         return list == null || list.isEmpty();
209     }
210
211     public static boolean isEmpty(Collection collection) {
212         return collection == null || collection.isEmpty();
213     }
214
215     @Nullable
216     public static Node getOriginal(DataObjectModification<Node> mod) {
217         Node node = null;
218         switch (mod.getModificationType()) {
219             case SUBTREE_MODIFIED:
220             case DELETE:
221                 node = mod.getDataBefore();
222                 break;
223             case WRITE:
224                 if (mod.getDataBefore() !=  null) {
225                     node = mod.getDataBefore();
226                 }
227                 break;
228             default:
229                 break;
230         }
231         return node;
232     }
233
234     @Nullable
235     public static Node getUpdated(DataObjectModification<Node> mod) {
236         switch (mod.getModificationType()) {
237             case SUBTREE_MODIFIED:
238             case WRITE:
239                 return mod.getDataAfter();
240             default:
241                 return null;
242         }
243     }
244
245     @Nullable
246     public static Node getCreated(DataObjectModification<Node> mod) {
247         if (mod.getModificationType() == DataObjectModification.ModificationType.WRITE
248                 && mod.getDataBefore() == null) {
249             return mod.getDataAfter();
250         }
251         return null;
252     }
253
254     @Nullable
255     public static Node getRemoved(DataObjectModification<Node> mod) {
256         if (mod.getModificationType() == DataObjectModification.ModificationType.DELETE) {
257             return mod.getDataBefore();
258         }
259         return null;
260     }
261
262     @Nullable
263     public static String getPsName(Node psNode) {
264         String psNodeId = psNode.getNodeId().getValue();
265         if (psNodeId.contains(PHYSICALSWITCH)) {
266             return psNodeId.substring(psNodeId.indexOf(PHYSICALSWITCH) + PHYSICALSWITCH.length());
267         }
268         return null;
269     }
270
271     @Nullable
272     public static String getPsName(InstanceIdentifier<Node> psNodeIid) {
273         String psNodeId = psNodeIid.firstKeyOf(Node.class).getNodeId().getValue();
274         if (psNodeId.contains(PHYSICALSWITCH)) {
275             return psNodeId.substring(psNodeId.indexOf(PHYSICALSWITCH) +  PHYSICALSWITCH.length());
276         }
277         return null;
278     }
279
280     public static InstanceIdentifier<Node> getGlobalNodePathFromPSNode(Node psNode) {
281         String psNodeId = psNode.getNodeId().getValue();
282         if (psNodeId.contains(PHYSICALSWITCH)) {
283             return convertToInstanceIdentifier(psNodeId.substring(0, psNodeId.indexOf(PHYSICALSWITCH)));
284         }
285         return convertToInstanceIdentifier(psNodeId);
286     }
287
288     @Nullable
289     public static InstanceIdentifier<Node> convertPsPath(Node psNode, InstanceIdentifier<Node> nodePath) {
290         String psNodeId = psNode.getNodeId().getValue();
291         if (psNodeId.contains(PHYSICALSWITCH)) {
292             String psName = psNodeId.substring(psNodeId.indexOf(PHYSICALSWITCH) + PHYSICALSWITCH.length());
293             String haPsNodeIdVal = nodePath.firstKeyOf(Node.class).getNodeId().getValue() + PHYSICALSWITCH + psName;
294             InstanceIdentifier<Node> haPsPath = convertToInstanceIdentifier(haPsNodeIdVal);
295             return haPsPath;
296         } else {
297             LOG.error("Failed to find ps path from node {}", psNode);
298             return null;
299         }
300     }
301
302     public static NodeBuilder getNodeBuilderForPath(InstanceIdentifier<Node> haPath) {
303         NodeBuilder nodeBuilder = new NodeBuilder();
304         nodeBuilder.setNodeId(haPath.firstKeyOf(Node.class).getNodeId());
305         return nodeBuilder;
306     }
307
308     @Nullable
309     public static String getHAIdFromManagerOtherConfig(Node node) {
310         if (node.augmentation(HwvtepGlobalAugmentation.class) == null) {
311             return null;
312         }
313         HwvtepGlobalAugmentation globalAugmentation = node.augmentation(HwvtepGlobalAugmentation.class);
314         if (globalAugmentation != null) {
315             List<Managers> managers = globalAugmentation.getManagers();
316             if (managers != null && !managers.isEmpty() && managers.get(0).getManagerOtherConfigs() != null) {
317                 for (ManagerOtherConfigs configs : managers.get(0).getManagerOtherConfigs()) {
318                     if (HA_ID.equals(configs.getOtherConfigKey())) {
319                         return configs.getOtherConfigValue();
320                     }
321                 }
322             }
323         }
324         return null;
325     }
326
327     /**
328      * Returns ha child node path from ha node of config data tree.
329      *
330      * @param haGlobalConfigNodeOptional HA global node
331      * @return ha Child ids
332      */
333     public static  List<NodeId> getChildNodeIdsFromManagerOtherConfig(Optional<Node> haGlobalConfigNodeOptional) {
334         List<NodeId> childNodeIds = new ArrayList<>();
335         if (!haGlobalConfigNodeOptional.isPresent()) {
336             return childNodeIds;
337         }
338         HwvtepGlobalAugmentation augmentation =
339                 haGlobalConfigNodeOptional.get().augmentation(HwvtepGlobalAugmentation.class);
340         if (augmentation != null && augmentation.getManagers() != null
341                 && augmentation.getManagers().size() > 0) {
342             Managers managers = augmentation.getManagers().get(0);
343             if (null == managers.getManagerOtherConfigs()) {
344                 return childNodeIds;
345             }
346             for (ManagerOtherConfigs otherConfigs : managers.getManagerOtherConfigs()) {
347                 if (HA_CHILDREN.equals(otherConfigs.getOtherConfigKey())) {
348                     String nodeIdsVal = otherConfigs.getOtherConfigValue();
349                     if (nodeIdsVal != null) {
350                         String[] parts = nodeIdsVal.split(",");
351                         for (String part : parts) {
352                             childNodeIds.add(new NodeId(part));
353                         }
354                     }
355
356                 }
357             }
358         }
359         return childNodeIds;
360     }
361
362     public static HwvtepGlobalAugmentation getGlobalAugmentationOfNode(Node node) {
363         HwvtepGlobalAugmentation result = null;
364         if (node != null) {
365             result = node.augmentation(HwvtepGlobalAugmentation.class);
366         }
367         if (result == null) {
368             result = new HwvtepGlobalAugmentationBuilder().build();
369         }
370         return result;
371     }
372
373     public static PhysicalSwitchAugmentation getPhysicalSwitchAugmentationOfNode(Node psNode) {
374         PhysicalSwitchAugmentation result = null;
375         if (psNode != null) {
376             result = psNode.augmentation(PhysicalSwitchAugmentation.class);
377         }
378         if (result == null) {
379             result = new PhysicalSwitchAugmentationBuilder().build();
380         }
381         return result;
382     }
383
384     /**
385      * Transform child managers (Source) to HA managers using HA node path.
386      *
387      * @param childNode Child Node
388      * @param haGlobalCfg HA global config node
389      * @return Transformed managers
390      */
391     public static List<Managers> buildManagersForHANode(Node childNode, Optional<Node> haGlobalCfg) {
392
393         Set<NodeId> nodeIds = new HashSet<>();
394         nodeIds.add(childNode.getNodeId());
395         List<NodeId> childNodeIds = getChildNodeIdsFromManagerOtherConfig(haGlobalCfg);
396         nodeIds.addAll(childNodeIds);
397
398         ManagersBuilder builder1 = new ManagersBuilder();
399
400         builder1.withKey(new ManagersKey(new Uri(MANAGER_KEY)));
401         List<ManagerOtherConfigs> otherConfigses = new ArrayList<>();
402         String children = nodeIds.stream().map(NodeId::getValue).collect(Collectors.joining(","));
403         otherConfigses.add(getOtherConfigBuilder(HA_CHILDREN, children).build());
404         builder1.setManagerOtherConfigs(otherConfigses);
405         List<Managers> managers = new ArrayList<>();
406         managers.add(builder1.build());
407         return managers;
408     }
409
410     /**
411      * Transform child switch (Source) to HA swicthes using HA node path.
412      *
413      * @param childNode  HA child node
414      * @param haNodePath  HA node path
415      * @param haNode Ha node object
416      * @return Transformed switches
417      */
418     public static List<Switches> buildSwitchesForHANode(Node childNode,
419                                                         InstanceIdentifier<Node> haNodePath,
420                                                         Optional<Node> haNode) {
421         List<Switches> psList = new ArrayList<>();
422         boolean switchesAlreadyPresent = false;
423         if (haNode.isPresent()) {
424             Node node = haNode.get();
425             HwvtepGlobalAugmentation augmentation = node.augmentation(HwvtepGlobalAugmentation.class);
426             if (augmentation != null) {
427                 if (augmentation.getSwitches() != null) {
428                     if (augmentation.getSwitches().size() > 0) {
429                         switchesAlreadyPresent = true;
430                     }
431                 }
432             }
433         }
434         if (!switchesAlreadyPresent) {
435             HwvtepGlobalAugmentation augmentation = childNode.augmentation(HwvtepGlobalAugmentation.class);
436             if (augmentation != null && augmentation.getSwitches() != null) {
437                 List<Switches> src = augmentation.getSwitches();
438                 if (src != null && src.size() > 0) {
439                     psList.add(new SwitchesCmd().transform(haNodePath, src.get(0)));
440                 }
441             }
442         }
443         return psList;
444     }
445
446     /**
447      * Build HA Global node from child nodes in config data tress.
448      *
449      * @param tx Transaction
450      * @param childNode Child Node object
451      * @param haNodePath Ha node path
452      * @param haGlobalCfg HA global node object
453      */
454     public static void buildGlobalConfigForHANode(TypedWriteTransaction<Configuration> tx,
455                                                   Node childNode,
456                                                   InstanceIdentifier<Node> haNodePath,
457                                                   Optional<Node> haGlobalCfg) {
458
459         NodeBuilder nodeBuilder = new NodeBuilder();
460         HwvtepGlobalAugmentationBuilder hwvtepGlobalBuilder = new HwvtepGlobalAugmentationBuilder();
461         hwvtepGlobalBuilder.setSwitches(buildSwitchesForHANode(childNode, haNodePath, haGlobalCfg));
462         hwvtepGlobalBuilder.setManagers(buildManagersForHANode(childNode, haGlobalCfg));
463
464         nodeBuilder.setNodeId(haNodePath.firstKeyOf(Node.class).getNodeId());
465         nodeBuilder.addAugmentation(HwvtepGlobalAugmentation.class, hwvtepGlobalBuilder.build());
466         Node configHANode = nodeBuilder.build();
467         tx.merge(haNodePath, configHANode, CREATE_MISSING_PARENTS);
468     }
469
470     public static <D extends Datastore> void deleteNodeIfPresent(TypedReadWriteTransaction<D> tx,
471             InstanceIdentifier<?> iid) throws ExecutionException, InterruptedException {
472         if (tx.read(iid).get().isPresent()) {
473             LOG.info("Deleting child node {}", getNodeIdVal(iid));
474             tx.delete(iid);
475         }
476     }
477
478     /**
479      * Delete PS data of HA node of Config Data tree.
480      *
481      * @param key Node object
482      * @param haNode Ha Node from which to be deleted
483      * @param tx Transaction
484      */
485     public static void deletePSNodesOfNode(InstanceIdentifier<Node> key, Node haNode,
486             TypedReadWriteTransaction<Configuration> tx) throws ExecutionException, InterruptedException {
487         //read from switches attribute and clean up them
488         HwvtepGlobalAugmentation globalAugmentation = haNode.augmentation(HwvtepGlobalAugmentation.class);
489         if (globalAugmentation == null) {
490             return;
491         }
492         HashMap<InstanceIdentifier<Node>,Boolean> deleted = new HashMap<>();
493         List<Switches> switches = globalAugmentation.getSwitches();
494         if (switches != null) {
495             for (Switches switche : switches) {
496                 InstanceIdentifier<Node> psId = (InstanceIdentifier<Node>)switche.getSwitchRef().getValue();
497                 deleteNodeIfPresent(tx, psId);
498                 deleted.put(psId, Boolean.TRUE);
499             }
500         }
501         //also read from managed by attribute of switches and cleanup them as a back up if the above cleanup fails
502         Optional<Topology> topologyOptional = tx .read(key.firstIdentifierOf(Topology.class)).get();
503         String deletedNodeId = key.firstKeyOf(Node.class).getNodeId().getValue();
504         if (topologyOptional.isPresent()) {
505             Topology topology = topologyOptional.get();
506             if (topology.getNode() != null) {
507                 for (Node psNode : topology.getNode()) {
508                     PhysicalSwitchAugmentation ps = psNode.augmentation(PhysicalSwitchAugmentation.class);
509                     if (ps != null) {
510                         InstanceIdentifier<Node> iid = (InstanceIdentifier<Node>)ps.getManagedBy().getValue();
511                         String nodeIdVal = iid.firstKeyOf(Node.class).getNodeId().getValue();
512                         if (deletedNodeId.equals(nodeIdVal)) {
513                             InstanceIdentifier<Node> psNodeId =
514                                     convertToInstanceIdentifier(psNode.getNodeId().getValue());
515                             if (deleted.containsKey(psNodeId)) {
516                                 deleteNodeIfPresent(tx, psNodeId);
517                             }
518                         }
519                     }
520                 }
521             }
522         }
523     }
524
525     /**
526      * Delete switches from Node in Operational Data Tree .
527      *
528      * @param haPath HA node path from whih switches will be deleted
529      * @param tx  Transaction object
530      */
531     public static void deleteSwitchesManagedByNode(InstanceIdentifier<Node> haPath,
532             TypedReadWriteTransaction<Operational> tx) throws ExecutionException, InterruptedException {
533
534         Optional<Node> nodeOptional = tx.read(haPath).get();
535         if (!nodeOptional.isPresent()) {
536             return;
537         }
538         Node node = nodeOptional.get();
539         HwvtepGlobalAugmentation globalAugmentation = node.augmentation(HwvtepGlobalAugmentation.class);
540         if (globalAugmentation == null) {
541             return;
542         }
543         List<Switches> switches = globalAugmentation.getSwitches();
544         if (switches != null) {
545             for (Switches switche : switches) {
546                 InstanceIdentifier<Node> id = (InstanceIdentifier<Node>)switche.getSwitchRef().getValue();
547                 deleteNodeIfPresent(tx, id);
548             }
549         }
550     }
551
552     /**
553      * Returns true/false if all the childrens are deleted from Operational Data store.
554      *
555      * @param children IID for the child node to read from OP data tree
556      * @param tx Transaction
557      * @return true/false boolean
558      * @throws ReadFailedException Exception thrown if read fails
559      */
560     public static boolean areAllChildDeleted(Set<InstanceIdentifier<Node>> children,
561                                              ReadWriteTransaction tx) throws ReadFailedException {
562         for (InstanceIdentifier<Node> childId : children) {
563             if (tx.read(OPERATIONAL, childId).checkedGet().isPresent()) {
564                 return false;
565             }
566         }
567         return true;
568     }
569
570     public static void addToCacheIfHAChildNode(InstanceIdentifier<Node> childPath, Node childNode,
571             HwvtepNodeHACache hwvtepNodeHACache) {
572         String haId = HwvtepHAUtil.getHAIdFromManagerOtherConfig(childNode);
573         if (!Strings.isNullOrEmpty(haId)) {
574             InstanceIdentifier<Node> parentId = HwvtepHAUtil.createInstanceIdentifierFromHAId(haId);
575             hwvtepNodeHACache.addChild(parentId, childPath/*child*/);
576         }
577     }
578 }