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