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