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