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