Optimization to read the OvsdbNode from the cache.
[ovsdb.git] / southbound / southbound-impl / src / main / java / org / opendaylight / ovsdb / southbound / SouthboundUtil.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. 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.ovsdb.southbound;
9
10 import com.google.common.annotations.VisibleForTesting;
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.util.concurrent.CheckedFuture;
14 import java.net.InetAddress;
15 import java.net.NetworkInterface;
16 import java.net.SocketException;
17 import java.util.Enumeration;
18 import java.util.concurrent.ExecutionException;
19
20 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
21 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
22 import org.opendaylight.controller.md.sal.binding.api.ReadTransaction;
23 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
24 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
25 import org.opendaylight.ovsdb.lib.error.SchemaVersionMismatchException;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAttributes;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeAugmentation;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeRef;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ConnectionInfo;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.port._interface.attributes.InterfaceExternalIds;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.port._interface.attributes.InterfaceExternalIdsBuilder;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.port._interface.attributes.PortExternalIds;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.port._interface.attributes.PortExternalIdsBuilder;
34 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
35 import org.opendaylight.yangtools.yang.binding.DataObject;
36 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 public final class SouthboundUtil {
41
42     private static final Logger LOG = LoggerFactory.getLogger(SouthboundUtil.class);
43     private static final String SCHEMA_VERSION_MISMATCH =
44             "{} column for {} table is not supported by this version of the {} schema: {}";
45
46     private SouthboundUtil() {
47         // Prevent instantiating a utility class
48     }
49
50     public static Optional<OvsdbNodeAugmentation> getManagingNode(DataBroker db, OvsdbBridgeAttributes mn) {
51         Preconditions.checkNotNull(mn);
52         try {
53             OvsdbNodeRef ref = mn.getManagedBy();
54             if (ref != null && ref.getValue() != null) {
55                 ReadOnlyTransaction transaction = db.newReadOnlyTransaction();
56                 @SuppressWarnings("unchecked")
57                 // Note: erasure makes this safe in combination with the typecheck below
58                 InstanceIdentifier<Node> path = (InstanceIdentifier<Node>) ref.getValue();
59
60                 CheckedFuture<Optional<Node>, ReadFailedException> nf = transaction.read(
61                         LogicalDatastoreType.OPERATIONAL, path);
62                 transaction.close();
63                 Optional<Node> optional = nf.get();
64                 if (optional != null && optional.isPresent()) {
65                     OvsdbNodeAugmentation ovsdbNode = null;
66                     Node node = optional.get();
67                     if (node instanceof OvsdbNodeAugmentation) {
68                         ovsdbNode = (OvsdbNodeAugmentation) node;
69                     } else if (node != null) {
70                         ovsdbNode = node.augmentation(OvsdbNodeAugmentation.class);
71                     }
72                     if (ovsdbNode != null) {
73                         return Optional.of(ovsdbNode);
74                     } else {
75                         LOG.warn("OvsdbManagedNode {} claims to be managed by {} but "
76                                 + "that OvsdbNode does not exist", mn, ref.getValue());
77                         return Optional.absent();
78                     }
79                 } else {
80                     LOG.warn("Mysteriously got back a thing which is *not* a topology Node: {}", optional);
81                     return Optional.absent();
82                 }
83             } else {
84                 LOG.warn("Cannot find client for OvsdbManagedNode without a specified ManagedBy {}", mn);
85                 return Optional.absent();
86             }
87         } catch (InterruptedException | ExecutionException e) {
88             LOG.warn("Failed to get OvsdbNode that manages OvsdbManagedNode {}", mn, e);
89             return Optional.absent();
90         }
91     }
92
93     public static <D extends DataObject> Optional<D> readNode(ReadTransaction transaction,
94                                                               InstanceIdentifier<D> connectionIid) {
95         Optional<D> node;
96         try {
97             if (OvsdbOperGlobalListener.OPER_NODE_CACHE.containsKey(connectionIid)) {
98                 node = Optional.of((D)OvsdbOperGlobalListener.OPER_NODE_CACHE.get(connectionIid));
99             } else {
100                 node = transaction.read(LogicalDatastoreType.OPERATIONAL, connectionIid).checkedGet();
101             }
102         } catch (ReadFailedException e) {
103             LOG.warn("Read Operational/DS for Node failed! {}", connectionIid, e);
104             throw new RuntimeException(e);
105         }
106         return node;
107
108     }
109
110     @VisibleForTesting
111     static String getLocalControllerHostIpAddress() {
112         String ipaddress = null;
113         try {
114             Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
115             if (ifaces != null) {
116                 while (ifaces.hasMoreElements()) {
117                     NetworkInterface iface = ifaces.nextElement();
118
119                     for (Enumeration<InetAddress> inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) {
120                         InetAddress inetAddr = inetAddrs.nextElement();
121                         if (!inetAddr.isLoopbackAddress() && inetAddr.isSiteLocalAddress()) {
122                             ipaddress = inetAddr.getHostAddress();
123                             break;
124                         }
125                     }
126                 }
127             } else {
128                 LOG.warn("Local Host don't have any associated IP address");
129             }
130         } catch (SocketException e) {
131             LOG.warn("Exception while fetching local host ip address ",e);
132         }
133         return ipaddress;
134     }
135
136     public static String getControllerTarget(Node ovsdbNode) {
137         String target = null;
138         String ipAddr = null;
139         OvsdbNodeAugmentation ovsdbNodeAugmentation = ovsdbNode.augmentation(OvsdbNodeAugmentation.class);
140         ConnectionInfo connectionInfo = ovsdbNodeAugmentation.getConnectionInfo();
141         LOG.info("connectionInfo: {}", connectionInfo);
142         if (connectionInfo != null && connectionInfo.getLocalIp() != null) {
143             ipAddr = connectionInfo.getLocalIp().stringValue();
144         }
145         if (ipAddr == null) {
146             ipAddr = getLocalControllerHostIpAddress();
147         }
148
149         if (ipAddr != null) {
150             target = SouthboundConstants.OPENFLOW_CONNECTION_PROTOCOL + ":"
151                     + ipAddr + ":" + SouthboundConstants.DEFAULT_OPENFLOW_PORT;
152         }
153
154         return target;
155     }
156
157     public static String connectionInfoToString(final ConnectionInfo connectionInfo) {
158         return connectionInfo.getRemoteIp().stringValue() + ":" + connectionInfo.getRemotePort().getValue();
159     }
160
161     public static void schemaMismatchLog(String column, String table, SchemaVersionMismatchException ex) {
162         LOG.debug(SCHEMA_VERSION_MISMATCH, column, table, SouthboundConstants.OPEN_V_SWITCH, ex.getMessage());
163     }
164
165     public static PortExternalIds createExternalIdsForPort(String key, String value) {
166         return new PortExternalIdsBuilder()
167             .setExternalIdKey(key)
168             .setExternalIdValue(value).build();
169     }
170
171     public static InterfaceExternalIds createExternalIdsForInterface(String key, String value) {
172         return new InterfaceExternalIdsBuilder()
173             .setExternalIdKey(key)
174             .setExternalIdValue(value).build();
175     }
176
177     @SuppressWarnings("checkstyle:IllegalCatch")
178     public static String getOvsdbNodeId(InstanceIdentifier<Node> nodeIid) {
179         String nodeId = "";
180         if (nodeIid != null) {
181             try {
182                 nodeId = nodeIid.toString();
183                 nodeId = nodeIid.firstKeyOf(Node.class).getNodeId().getValue();
184             } catch (Exception exp) {
185                 LOG.debug("Exception in getting the value from {} ", nodeIid);
186             }
187         }
188         return nodeId;
189     }
190 }