Fixed EVC create
[unimgr.git] / impl / src / main / java / org / opendaylight / unimgr / impl / UnimgrUtils.java
1 /*
2  * Copyright (c) 2015 CableLabs 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.unimgr.impl;
9
10 import java.net.InetAddress;
11 import java.net.UnknownHostException;
12 import java.util.ArrayList;
13 import java.util.HashMap;
14 import java.util.HashSet;
15 import java.util.List;
16 import java.util.Map;
17 import java.util.Map.Entry;
18 import java.util.Set;
19 import java.util.UUID;
20
21 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
22 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
23 import org.opendaylight.controller.md.sal.binding.api.ReadTransaction;
24 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
25 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
26 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
27 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
28 import org.opendaylight.ovsdb.southbound.SouthboundConstants;
29 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
30 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
31 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.PortNumber;
32 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Uri;
33 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.VlanId;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAugmentation;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAugmentationBuilder;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeName;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeProtocolBase;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeAugmentation;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeAugmentationBuilder;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeRef;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbPortInterfaceAttributes.VlanMode;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbTerminationPointAugmentation;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbTerminationPointAugmentationBuilder;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.ControllerEntry;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.ControllerEntryBuilder;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.ProtocolEntry;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.ProtocolEntryBuilder;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ConnectionInfo;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ConnectionInfoBuilder;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.port._interface.attributes.Options;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.port._interface.attributes.OptionsBuilder;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.port._interface.attributes.OptionsKey;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.unimgr.rev151012.EvcAugmentation;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.unimgr.rev151012.Uni;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.unimgr.rev151012.UniAugmentation;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.unimgr.rev151012.UniAugmentationBuilder;
58 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
59 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
60 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Link;
61 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
62 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder;
63 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
64 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.node.TerminationPoint;
65 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.node.TerminationPointBuilder;
66 import org.opendaylight.yangtools.yang.binding.DataObject;
67 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
70
71 import com.google.common.base.Optional;
72 import com.google.common.collect.ImmutableBiMap;
73 import com.google.common.collect.Lists;
74 import com.google.common.util.concurrent.CheckedFuture;
75
76 public class UnimgrUtils {
77
78     private static final Logger LOG = LoggerFactory.getLogger(UnimgrUtils.class);
79
80     public static void createBridgeNode(DataBroker dataBroker,
81                                         Node ovsdbNode,
82                                         UniAugmentation uni,
83                                         String bridgeName) {
84         LOG.info("Creating a bridge on node {}", ovsdbNode.getNodeId().getValue());
85         InstanceIdentifier<Node> ovsdbNodeIid = uni.getOvsdbNodeRef().getValue().firstIdentifierOf(Node.class);
86         if (ovsdbNodeIid != null) {
87             NodeBuilder bridgeNodeBuilder = new NodeBuilder();
88             InstanceIdentifier<Node> bridgeIid = UnimgrMapper.createOvsdbBridgeNodeIid(ovsdbNode,
89                                                                                        bridgeName);
90             NodeId bridgeNodeId = new NodeId(ovsdbNode.getNodeId()
91                                            + UnimgrConstants.DEFAULT_BRIDGE_NODE_ID_SUFFIX
92                                            + bridgeName);
93             bridgeNodeBuilder.setNodeId(bridgeNodeId);
94             OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder = new OvsdbBridgeAugmentationBuilder();
95             ovsdbBridgeAugmentationBuilder.setBridgeName(new OvsdbBridgeName(bridgeName));
96             ovsdbBridgeAugmentationBuilder.setProtocolEntry(UnimgrUtils.createMdsalProtocols());
97             OvsdbNodeRef ovsdbNodeRef = new OvsdbNodeRef(ovsdbNodeIid);
98             ovsdbBridgeAugmentationBuilder.setManagedBy(ovsdbNodeRef);
99             bridgeNodeBuilder.addAugmentation(OvsdbBridgeAugmentation.class, ovsdbBridgeAugmentationBuilder.build());
100             WriteTransaction transaction = dataBroker.newWriteOnlyTransaction();
101             transaction.put(LogicalDatastoreType.CONFIGURATION, bridgeIid, bridgeNodeBuilder.build());
102             transaction.submit();
103         } else {
104             LOG.info("OvsdbNodeRef is null");
105         }
106     }
107
108     public static void createBridgeNode(DataBroker dataBroker,
109                                         InstanceIdentifier<Node> ovsdbNodeIid,
110                                         UniAugmentation uni,
111                                         String bridgeName) {
112         LOG.info("Creating a bridge on node {}", ovsdbNodeIid);
113         if (ovsdbNodeIid != null) {
114             NodeBuilder bridgeNodeBuilder = new NodeBuilder();
115             Optional<Node> optionalOvsdbNode = UnimgrUtils.readNode(dataBroker,
116                                                                     LogicalDatastoreType.OPERATIONAL,
117                                                                     ovsdbNodeIid);
118             if (optionalOvsdbNode.isPresent()) {
119                 Node ovsdbNode = optionalOvsdbNode.get();
120                 InstanceIdentifier<Node> bridgeIid = UnimgrMapper.createOvsdbBridgeNodeIid(ovsdbNode,
121                                                                                            bridgeName);
122                 NodeId bridgeNodeId = new NodeId(ovsdbNode.getNodeId().getValue()
123                                                + UnimgrConstants.DEFAULT_BRIDGE_NODE_ID_SUFFIX
124                                                + bridgeName);
125                 bridgeNodeBuilder.setNodeId(bridgeNodeId);
126                 OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder = new OvsdbBridgeAugmentationBuilder();
127                 ovsdbBridgeAugmentationBuilder.setBridgeName(new OvsdbBridgeName(bridgeName));
128                 ovsdbBridgeAugmentationBuilder.setProtocolEntry(UnimgrUtils.createMdsalProtocols());
129                 OvsdbNodeRef ovsdbNodeRef = new OvsdbNodeRef(ovsdbNodeIid);
130                 ovsdbBridgeAugmentationBuilder.setManagedBy(ovsdbNodeRef);
131                 bridgeNodeBuilder.addAugmentation(OvsdbBridgeAugmentation.class,
132                                                   ovsdbBridgeAugmentationBuilder.build());
133                 WriteTransaction transaction = dataBroker.newWriteOnlyTransaction();
134                 transaction.put(LogicalDatastoreType.CONFIGURATION,
135                                 bridgeIid,
136                                 bridgeNodeBuilder.build());
137                 transaction.submit();
138             }
139         } else {
140             LOG.info("OvsdbNodeRef is null");
141         }
142     }
143
144     public static List<ControllerEntry> createControllerEntries(String targetString) {
145         List<ControllerEntry> controllerEntries = new ArrayList<ControllerEntry>();
146         ControllerEntryBuilder controllerEntryBuilder = new ControllerEntryBuilder();
147         controllerEntryBuilder.setTarget(new Uri(targetString));
148         controllerEntries.add(controllerEntryBuilder.build());
149         return controllerEntries;
150     }
151
152     public static void createGreTunnel(DataBroker dataBroker,
153                                        Uni source,
154                                        Uni destination,
155                                        Node bridgeNode,
156                                        String bridgeName,
157                                        String portName) {
158         InstanceIdentifier<TerminationPoint> tpIid =
159                                                  UnimgrMapper.getTerminationPointIid(bridgeNode,
160                                                                                      portName);
161         OvsdbTerminationPointAugmentationBuilder tpAugmentationBuilder =
162                                                      new OvsdbTerminationPointAugmentationBuilder();
163         tpAugmentationBuilder.setName(portName);
164         ArrayList<Options> options = Lists.newArrayList();
165         OptionsKey optionKey = new OptionsKey("remote_ip");
166         Options destinationIp = new OptionsBuilder()
167                                         .setOption(destination.getIpAddress().getIpv4Address().getValue())
168                                         .setKey(optionKey).setValue(destination.getIpAddress().getIpv4Address().getValue())
169                                         .build();
170         options.add(destinationIp);
171         tpAugmentationBuilder.setOptions(options);
172         tpAugmentationBuilder.setInterfaceType(SouthboundConstants.OVSDB_INTERFACE_TYPE_MAP.get("gre"));
173         TerminationPointBuilder tpBuilder = new TerminationPointBuilder();
174         tpBuilder.setKey(InstanceIdentifier.keyOf(tpIid));
175         tpBuilder.addAugmentation(OvsdbTerminationPointAugmentation.class, tpAugmentationBuilder.build());
176         WriteTransaction transaction = dataBroker.newWriteOnlyTransaction();
177         transaction.put(LogicalDatastoreType.CONFIGURATION,
178                         tpIid,
179                         tpBuilder.build());
180         transaction.submit();
181     }
182
183     public static List<ProtocolEntry> createMdsalProtocols() {
184         List<ProtocolEntry> protocolList = new ArrayList<ProtocolEntry>();
185         ImmutableBiMap<String, Class<? extends OvsdbBridgeProtocolBase>> mapper =
186                 SouthboundConstants.OVSDB_PROTOCOL_MAP.inverse();
187         protocolList.add(new ProtocolEntryBuilder().
188                 setProtocol((Class<? extends OvsdbBridgeProtocolBase>) mapper.get("OpenFlow13")).build());
189         return protocolList;
190     }
191
192     public static OvsdbBridgeAugmentation createOvsdbBridgeAugmentation(Uni uni) throws Exception {
193         OvsdbNodeRef ovsdbNodeRef = uni.getOvsdbNodeRef();
194         if (ovsdbNodeRef != null && ovsdbNodeRef.getValue() != null) {
195             UUID bridgeUuid = UUID.randomUUID();
196             OvsdbBridgeAugmentation ovsdbBridge = new OvsdbBridgeAugmentationBuilder()
197                                                         .setBridgeName(
198                                                                 new OvsdbBridgeName(UnimgrConstants.DEFAULT_BRIDGE_NAME))
199                                                         .setManagedBy(ovsdbNodeRef)
200                                                         .setBridgeUuid(
201                                                                 new Uuid(bridgeUuid.toString()))
202                                                         .build();
203             return ovsdbBridge;
204         } else {
205             throw new Exception("Ovsdb Node Reference does not exist !");
206         }
207     }
208
209     public static void createOvsdbNode(DataBroker dataBroker,
210                                        NodeId ovsdbNodeId,
211                                        Uni uni) {
212         InstanceIdentifier<Node> ovsdbNodeIid = UnimgrMapper.getOvsdbNodeIid(uni.getIpAddress());
213         try {
214             NodeKey ovsdbNodeKey = new NodeKey(ovsdbNodeId);
215             Node nodeData = new NodeBuilder()
216                                     .setNodeId(ovsdbNodeId)
217                                     .setKey(ovsdbNodeKey)
218                                     .addAugmentation(OvsdbNodeAugmentation.class,
219                                                      UnimgrUtils.createOvsdbNodeAugmentation(uni))
220                                     .build();
221             // Submit the node to the datastore
222             WriteTransaction transaction = dataBroker.newWriteOnlyTransaction();
223             transaction.put(LogicalDatastoreType.CONFIGURATION, ovsdbNodeIid, nodeData);
224             transaction.submit();
225             LOG.info("Created and submitted a new OVSDB node {}", nodeData.getNodeId());
226         } catch (Exception e) {
227             LOG.error("Exception while creating OvsdbNodeAugmentation, " + "Uni is null. Node Id: {}", ovsdbNodeId);
228         }
229     }
230
231     public static Node createOvsdbNode(DataBroker dataBroker,
232                                        UniAugmentation uni) {
233         NodeId ovsdbNodeId = new NodeId(createOvsdbNodeId(uni.getIpAddress()));
234         try {
235             InstanceIdentifier<Node> ovsdbNodeIid = UnimgrMapper.getOvsdbNodeIid(ovsdbNodeId);
236             NodeKey ovsdbNodeKey = new NodeKey(ovsdbNodeId);
237             Node nodeData = new NodeBuilder()
238                                     .setNodeId(ovsdbNodeId)
239                                     .setKey(ovsdbNodeKey)
240                                     .addAugmentation(OvsdbNodeAugmentation.class,
241                                                      UnimgrUtils.createOvsdbNodeAugmentation(uni))
242                                     .build();
243             // Submit the node to the datastore
244             WriteTransaction transaction = dataBroker.newWriteOnlyTransaction();
245             transaction.put(LogicalDatastoreType.CONFIGURATION, ovsdbNodeIid, nodeData);
246             transaction.submit();
247             LOG.info("Created and submitted a new OVSDB node {}", nodeData.getNodeId());
248             return nodeData;
249         } catch (Exception e) {
250             LOG.error("Exception while creating OvsdbNodeAugmentation, " + "Uni is null. Node Id: {}", ovsdbNodeId);
251         }
252         return null;
253     }
254
255     public static OvsdbNodeAugmentation createOvsdbNodeAugmentation(Uni uni) {
256         ConnectionInfo connectionInfos = new ConnectionInfoBuilder()
257                                                 .setRemoteIp(uni.getIpAddress())
258                                                 .setRemotePort(new PortNumber(UnimgrConstants.OVSDB_PORT))
259                                                 .build();
260         OvsdbNodeAugmentation ovsdbNode = new OvsdbNodeAugmentationBuilder()
261                                                 .setConnectionInfo(connectionInfos).build();
262         return ovsdbNode;
263     }
264
265     public static NodeId createOvsdbNodeId(IpAddress ipAddress) {
266         String nodeId = UnimgrConstants.OVSDB_PREFIX
267                         + ipAddress.getIpv4Address().getValue().toString()
268                         + ":"
269                         + UnimgrConstants.OVSDB_PORT;
270         return new NodeId(nodeId);
271     }
272
273     public static OvsdbTerminationPointAugmentation createOvsdbTerminationPointAugmentation(Uni uni) {
274         // we will use nodeId to set interface port id
275         VlanId vlanID = new VlanId(1);
276         OvsdbTerminationPointAugmentation terminationPoint = new OvsdbTerminationPointAugmentationBuilder()
277                                                                      .setName(UnimgrConstants.DEFAULT_INTERNAL_IFACE)
278                                                                      .setVlanTag(vlanID)
279                                                                      .setVlanMode(VlanMode.Access)
280                                                                      .build();
281         return terminationPoint;
282     }
283
284     public static void createTerminationPointNode(DataBroker dataBroker,
285                                                   Uni uni,
286                                                   Node bridgeNode,
287                                                   String bridgeName,
288                                                   String portName,
289                                                   String type) {
290         InstanceIdentifier<TerminationPoint> tpIid = UnimgrMapper
291                                                         .getTerminationPointIid(bridgeNode,
292                                                                                 portName);
293         OvsdbTerminationPointAugmentationBuilder tpAugmentationBuilder = new OvsdbTerminationPointAugmentationBuilder();
294         tpAugmentationBuilder.setName(portName);
295         if (type != null) {
296             tpAugmentationBuilder.setInterfaceType(SouthboundConstants.OVSDB_INTERFACE_TYPE_MAP.get(type));
297         }
298         TerminationPointBuilder tpBuilder = new TerminationPointBuilder();
299         tpBuilder.setKey(InstanceIdentifier.keyOf(tpIid));
300         tpBuilder.addAugmentation(OvsdbTerminationPointAugmentation.class,
301                                   tpAugmentationBuilder.build());
302         WriteTransaction transaction = dataBroker.newWriteOnlyTransaction();
303         transaction.put(LogicalDatastoreType.CONFIGURATION,
304                         tpIid,
305                         tpBuilder.build());
306         transaction.submit();
307     }
308
309     public static <T extends DataObject> Map<InstanceIdentifier<T>,T> extract(
310             Map<InstanceIdentifier<?>, DataObject> changes, Class<T> klazz) {
311         Map<InstanceIdentifier<T>,T> result = new HashMap<InstanceIdentifier<T>,T>();
312         if (changes != null && changes.entrySet() != null) {
313             for (Entry<InstanceIdentifier<?>, DataObject> created : changes.entrySet()) {
314                 if (klazz.isInstance(created.getValue())) {
315                     @SuppressWarnings("unchecked")
316                     T value = (T) created.getValue();
317                     Class<?> type = created.getKey().getTargetType();
318                     if (type.equals(klazz)) {
319                         @SuppressWarnings("unchecked") // Actually checked above
320                         InstanceIdentifier<T> iid = (InstanceIdentifier<T>) created.getKey();
321                         result.put(iid, value);
322                     }
323                 }
324             }
325         }
326         return result;
327     }
328
329     public static <T extends DataObject> Map<InstanceIdentifier<T>,T> extractOriginal(
330             AsyncDataChangeEvent<InstanceIdentifier<?>,DataObject> changes,Class<T> klazz) {
331         return extract(changes.getOriginalData(),klazz);
332     }
333
334     public static <T extends DataObject> Set<InstanceIdentifier<T>> extractRemoved(
335             AsyncDataChangeEvent<InstanceIdentifier<?>,DataObject> changes,Class<T> klazz) {
336         Set<InstanceIdentifier<T>> result = new HashSet<InstanceIdentifier<T>>();
337         if (changes != null && changes.getRemovedPaths() != null) {
338             for (InstanceIdentifier<?> iid : changes.getRemovedPaths()) {
339                 if (iid.getTargetType().equals(klazz)) {
340                     @SuppressWarnings("unchecked") // Actually checked above
341                     InstanceIdentifier<T> iidn = (InstanceIdentifier<T>)iid;
342                     result.add(iidn);
343                 }
344             }
345         }
346         return result;
347     }
348
349     public static Optional<Node> findOvsdbNode(DataBroker dataBroker,
350                                                UniAugmentation uni) {
351         List<Node> ovsdbNodes = getOvsdbNodes(dataBroker);
352         Optional<Node> optionalOvsdb;
353         if (!ovsdbNodes.isEmpty()) {
354             for (Node ovsdbNode : ovsdbNodes) {
355                 OvsdbNodeAugmentation ovsdbNodeAugmentation = ovsdbNode
356                                                                   .getAugmentation(OvsdbNodeAugmentation.class);
357                 if (ovsdbNodeAugmentation.getConnectionInfo()
358                                          .getRemoteIp()
359                                          .getIpv4Address()
360                         .equals(uni.getIpAddress().getIpv4Address())) {
361                     LOG.info("Found ovsdb node");
362                     optionalOvsdb = Optional.of(ovsdbNode);
363                     return optionalOvsdb;
364                 }
365             }
366         }
367         return Optional.absent();
368     }
369
370     public static Optional<Node> findUniNode(DataBroker dataBroker,
371                                              IpAddress ipAddress) {
372         List<Node> uniNodes = getUniNodes(dataBroker);
373         if (!uniNodes.isEmpty()) {
374             for (Node uniNode : uniNodes) {
375                 UniAugmentation uniAugmentation = uniNode.getAugmentation(UniAugmentation.class);
376                 if (uniAugmentation.getIpAddress().equals(ipAddress)) {
377                     LOG.info("Found Uni node");
378                     return Optional.of(uniNode);
379                 }
380             }
381         }
382         return Optional.absent();
383     }
384
385     public static ConnectionInfo getConnectionInfo(DataBroker dataBroker,
386                                                    NodeId ovsdbNodeId) {
387         InstanceIdentifier<Node> nodeIid = UnimgrMapper.getOvsdbNodeIid(ovsdbNodeId);
388         Optional<Node> node = readNode(dataBroker,
389                                        LogicalDatastoreType.OPERATIONAL,
390                                        nodeIid);
391         if (node.isPresent()) {
392             Node ovsdbNode = node.get();
393             OvsdbNodeAugmentation ovsdbNodeAugmentation = ovsdbNode
394                                                               .getAugmentation(OvsdbNodeAugmentation.class);
395             ConnectionInfo connectionInfo = ovsdbNodeAugmentation.getConnectionInfo();
396             return connectionInfo;
397         } else {
398             return null;
399         }
400     }
401
402     public static List<Link> getEvcLinks(DataBroker dataBroker,
403                                          IpAddress ipAddress) {
404         List<Link> evcLinks = new ArrayList<>();
405         InstanceIdentifier<Topology> evcTopology = UnimgrMapper.getEvcTopologyIid();
406         Topology topology = UnimgrUtils.read(dataBroker,
407                                              LogicalDatastoreType.OPERATIONAL,
408                                              evcTopology);
409         if (topology != null && topology.getLink() != null) {
410             for (Link link : topology.getLink()) {
411                 EvcAugmentation evcAugmentation = link.getAugmentation(EvcAugmentation.class);
412                 if (evcAugmentation != null) {
413                     evcLinks.add(link);
414                 }
415             }
416         }
417         return evcLinks;
418     }
419
420     public static IpAddress getLocalIp() {
421         String ip;
422         try {
423             ip = InetAddress.getLocalHost().getHostAddress();
424             Ipv4Address ipv4 = new Ipv4Address(ip);
425             IpAddress ipAddress = new IpAddress(ipv4);
426             return ipAddress;
427         } catch (UnknownHostException e) {
428             LOG.info("Unable to retrieve controller's ip address, using loopback.");
429         }
430         return new IpAddress(UnimgrConstants.LOCAL_IP);
431     }
432
433     public static List<Node> getOvsdbNodes(DataBroker dataBroker) {
434         List<Node> ovsdbNodes = new ArrayList<>();
435         InstanceIdentifier<Topology> ovsdbTopoIdentifier = UnimgrMapper.getOvsdbTopologyIid();
436         Topology topology = UnimgrUtils.read(dataBroker,
437                                              LogicalDatastoreType.OPERATIONAL,
438                                              ovsdbTopoIdentifier);
439         if (topology != null && topology.getNode() != null) {
440             for (Node node : topology.getNode()) {
441                 OvsdbNodeAugmentation ovsdbNodeAugmentation = node.getAugmentation(OvsdbNodeAugmentation.class);
442                 if (ovsdbNodeAugmentation != null) {
443                     ovsdbNodes.add(node);
444                 }
445             }
446         }
447         return ovsdbNodes;
448     }
449
450     public static List<Node> getUniNodes(DataBroker dataBroker) {
451         List<Node> uniNodes = new ArrayList<>();
452         InstanceIdentifier<Topology> topologyInstanceIdentifier = UnimgrMapper.getUniTopologyIid();
453         Topology topology = read(dataBroker,
454                                  LogicalDatastoreType.CONFIGURATION,
455                                  topologyInstanceIdentifier);
456         if (topology != null && topology.getNode() != null) {
457             for (Node node : topology.getNode()) {
458                 UniAugmentation uniAugmentation = node.getAugmentation(UniAugmentation.class);
459                 if (uniAugmentation != null) {
460                     uniNodes.add(node);
461                 }
462             }
463         }
464         return uniNodes;
465     }
466
467     public static List<Node> getUniNodes(DataBroker dataBroker,
468                                          LogicalDatastoreType store) {
469         List<Node> uniNodes = new ArrayList<>();
470         InstanceIdentifier<Topology> topologyInstanceIdentifier = UnimgrMapper.getUniTopologyIid();
471         Topology topology = read(dataBroker,
472                                  store,
473                                  topologyInstanceIdentifier);
474         if (topology != null && topology.getNode() != null) {
475             for (Node node : topology.getNode()) {
476                 UniAugmentation uniAugmentation = node.getAugmentation(UniAugmentation.class);
477                 if (uniAugmentation != null) {
478                     uniNodes.add(node);
479                 }
480             }
481         }
482         return uniNodes;
483     }
484
485     public static <D extends org.opendaylight.yangtools.yang.binding.DataObject> D read(
486             DataBroker dataBroker,
487             final LogicalDatastoreType store,
488             final InstanceIdentifier<D> path)  {
489         D result = null;
490         final ReadOnlyTransaction transaction = dataBroker.newReadOnlyTransaction();
491         Optional<D> optionalDataObject;
492         CheckedFuture<Optional<D>, ReadFailedException> future = transaction.read(store, path);
493         try {
494             optionalDataObject = future.checkedGet();
495             if (optionalDataObject.isPresent()) {
496                 result = optionalDataObject.get();
497             } else {
498                 LOG.debug("{}: Failed to read {}",
499                         Thread.currentThread().getStackTrace()[1], path);
500             }
501         } catch (ReadFailedException e) {
502             LOG.warn("Failed to read {} ", path, e);
503         }
504         transaction.close();
505         return result;
506     }
507
508     @Deprecated
509     public static final Optional<Node> readNode(DataBroker dataBroker,
510                                                 InstanceIdentifier<?> genericNode) {
511         ReadTransaction read = dataBroker.newReadOnlyTransaction();
512         InstanceIdentifier<Node> nodeIid = genericNode.firstIdentifierOf(Node.class);
513         CheckedFuture<Optional<Node>, ReadFailedException> nodeFuture =
514                                                               read.read(LogicalDatastoreType.OPERATIONAL,
515                                                                         nodeIid);
516         try {
517             return nodeFuture.checkedGet();
518         } catch (ReadFailedException e) {
519             LOG.info("Unable to read node with Iid {}", nodeIid);
520         }
521         return Optional.absent();
522     }
523
524     public static final Optional<Node> readNode(DataBroker dataBroker,
525                                                 LogicalDatastoreType store,
526                                                 InstanceIdentifier<?> genericNode) {
527         ReadTransaction read = dataBroker.newReadOnlyTransaction();
528         InstanceIdentifier<Node> nodeIid = genericNode.firstIdentifierOf(Node.class);
529         CheckedFuture<Optional<Node>, ReadFailedException> nodeFuture = read
530                 .read(store, nodeIid);
531         try {
532             return nodeFuture.checkedGet();
533         } catch (ReadFailedException e) {
534             LOG.info("Unable to read node with Iid {}", nodeIid);
535         }
536         return Optional.absent();
537     }
538
539     public static void updateUniNode(LogicalDatastoreType dataStore,
540                                      InstanceIdentifier<?> uniKey,
541                                      UniAugmentation uni,
542                                      Node ovsdbNode,
543                                      DataBroker dataBroker) {
544         InstanceIdentifier<Node> ovsdbNodeIid = UnimgrMapper.getOvsdbNodeIid(ovsdbNode.getNodeId());
545         OvsdbNodeRef ovsdbNodeRef = new OvsdbNodeRef(ovsdbNodeIid);
546         UniAugmentationBuilder updatedUniBuilder = new UniAugmentationBuilder(uni);
547         if (ovsdbNodeRef != null) {
548             updatedUniBuilder.setOvsdbNodeRef(ovsdbNodeRef);
549         }
550         Optional<Node> optionalNode = readNode(dataBroker,
551                                                LogicalDatastoreType.CONFIGURATION,
552                                                uniKey);
553         if (optionalNode.isPresent()) {
554             Node node = optionalNode.get();
555             WriteTransaction transaction = dataBroker.newWriteOnlyTransaction();
556             NodeBuilder nodeBuilder = new NodeBuilder();
557             nodeBuilder.setKey(node.getKey());
558             nodeBuilder.setNodeId(node.getNodeId());
559             nodeBuilder.addAugmentation(UniAugmentation.class, updatedUniBuilder.build());
560             transaction.put(dataStore, uniKey.firstIdentifierOf(Node.class), nodeBuilder.build());
561             transaction.submit();
562         }
563     }
564
565     public static void updateUniNode(LogicalDatastoreType dataStore,
566                                      InstanceIdentifier<?> uniKey,
567                                      UniAugmentation uni,
568                                      InstanceIdentifier<?> ovsdbNodeIid,
569                                      DataBroker dataBroker) {
570         OvsdbNodeRef ovsdbNodeRef = new OvsdbNodeRef(ovsdbNodeIid);
571         UniAugmentationBuilder updatedUniBuilder = new UniAugmentationBuilder(uni);
572         if (ovsdbNodeRef != null) {
573             updatedUniBuilder.setOvsdbNodeRef(ovsdbNodeRef);
574         }
575         Optional<Node> optionalNode = readNode(dataBroker,
576                                                LogicalDatastoreType.CONFIGURATION,
577                                                uniKey);
578         if (optionalNode.isPresent()) {
579             Node node = optionalNode.get();
580             WriteTransaction transaction = dataBroker.newWriteOnlyTransaction();
581             NodeBuilder nodeBuilder = new NodeBuilder();
582             nodeBuilder.setKey(node.getKey());
583             nodeBuilder.setNodeId(node.getNodeId());
584             nodeBuilder.addAugmentation(UniAugmentation.class, updatedUniBuilder.build());
585             transaction.put(dataStore, uniKey.firstIdentifierOf(Node.class), nodeBuilder.build());
586             transaction.submit();
587         }
588     }
589 }