2 * Copyright (c) 2015, 2017 Ericsson India Global Services Pvt Ltd. and others. All rights reserved.
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
8 package org.opendaylight.ovsdb.hwvtepsouthbound;
10 import static java.util.Objects.requireNonNull;
12 import com.google.common.util.concurrent.ThreadFactoryBuilder;
13 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
14 import java.util.Collection;
16 import java.util.Optional;
17 import java.util.concurrent.ConcurrentHashMap;
18 import java.util.concurrent.ExecutionException;
19 import java.util.concurrent.Executors;
20 import java.util.concurrent.ScheduledExecutorService;
21 import java.util.concurrent.TimeUnit;
22 import org.opendaylight.mdsal.binding.api.DataBroker;
23 import org.opendaylight.mdsal.binding.api.ReadTransaction;
24 import org.opendaylight.mdsal.binding.api.ReadWriteTransaction;
25 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
26 import org.opendaylight.ovsdb.lib.error.SchemaVersionMismatchException;
27 import org.opendaylight.ovsdb.utils.mdsal.utils.MdsalUtils;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepGlobalAugmentation;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepGlobalRef;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepPhysicalSwitchAttributes;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.global.attributes.ConnectionInfo;
32 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
33 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
34 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
35 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
36 import org.opendaylight.yangtools.yang.binding.DataObject;
37 import org.opendaylight.yangtools.yang.binding.Identifiable;
38 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
39 import org.opendaylight.yangtools.yang.data.impl.codec.DeserializationException;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
43 public final class HwvtepSouthboundUtil {
44 private static final Logger LOG = LoggerFactory.getLogger(HwvtepSouthboundUtil.class);
45 private static final ScheduledExecutorService BACKGROUND_EXECUTOR =
46 Executors.newSingleThreadScheduledExecutor(new ThreadFactoryBuilder()
47 .setNameFormat("hwvteputil-executor-service-%d")
50 private static final String SCHEMA_VERSION_MISMATCH =
51 "{} column for {} table is not supported by this version of the {} schema: {}";
53 private static InstanceIdentifierCodec instanceIdentifierCodec;
56 private HwvtepSouthboundUtil() {
57 // Prevent instantiating a utility class
60 // FIXME: eliminate this static wiring by encapsulating the codec into a service
61 @Deprecated(forRemoval = true)
62 @SuppressFBWarnings("EI_EXPOSE_STATIC_REP2")
63 public static void setInstanceIdentifierCodec(InstanceIdentifierCodec iidc) {
64 instanceIdentifierCodec = iidc;
67 // FIXME: this should be an instance method
68 public static InstanceIdentifierCodec getInstanceIdentifierCodec() {
69 return instanceIdentifierCodec;
72 // FIXME: this should be an instance method
73 public static String serializeInstanceIdentifier(InstanceIdentifier<?> iid) {
74 return instanceIdentifierCodec.serialize(iid);
77 // FIXME: this should be an instance method
78 public static InstanceIdentifier<?> deserializeInstanceIdentifier(String iidString) {
79 InstanceIdentifier<?> result = null;
81 result = instanceIdentifierCodec.bindingDeserializer(iidString);
82 } catch (DeserializationException e) {
83 LOG.warn("Unable to deserialize iidString", e);
88 public static <D extends org.opendaylight.yangtools.yang.binding.DataObject> Optional<D> readNode(
90 LogicalDatastoreType logicalDatastoreType, final InstanceIdentifier<D> connectionIid) {
91 if (logicalDatastoreType == LogicalDatastoreType.OPERATIONAL) {
92 Node node = HwvtepOperGlobalListener.getNode((InstanceIdentifier<Node>) connectionIid);
94 return Optional.of((D)node);
96 LOG.debug("Node not available in cache. Read from datastore - {}", connectionIid);
99 try (ReadTransaction transaction = db.newReadOnlyTransaction()) {
100 return transaction.read(logicalDatastoreType, connectionIid).get();
101 } catch (InterruptedException | ExecutionException e) {
102 LOG.error("Read failed from datastore for Node : {}",connectionIid,e);
103 throw new IllegalStateException(e);
107 public static <D extends org.opendaylight.yangtools.yang.binding.DataObject> Optional<D> readNode(
108 ReadTransaction transaction,
109 LogicalDatastoreType logicalDatastoreType, final InstanceIdentifier<D> connectionIid) {
110 if (logicalDatastoreType == LogicalDatastoreType.OPERATIONAL) {
111 Node node = HwvtepOperGlobalListener.getNode((InstanceIdentifier<Node>) connectionIid);
113 return Optional.of((D)node);
115 LOG.debug("Node not available in cache. Read from datastore - {}", connectionIid);
119 return transaction.read(logicalDatastoreType, connectionIid).get();
120 } catch (InterruptedException | ExecutionException e) {
121 LOG.error("Read failed from datastore for Node : {}",connectionIid,e);
122 throw new IllegalStateException(e);
126 public static <D extends org.opendaylight.yangtools.yang.binding.DataObject> Optional<D> readNode(
127 ReadWriteTransaction transaction, final InstanceIdentifier<D> connectionIid) {
128 return readNode(transaction, LogicalDatastoreType.OPERATIONAL, connectionIid);
131 public static <D extends DataObject> Optional<D> readNode(ReadWriteTransaction transaction,
132 LogicalDatastoreType logicalDatastoreType,
133 InstanceIdentifier<D> connectionIid) {
134 if (logicalDatastoreType == LogicalDatastoreType.OPERATIONAL) {
135 Node node = HwvtepOperGlobalListener.getNode((InstanceIdentifier<Node>) connectionIid);
137 return Optional.of((D)node);
139 LOG.debug("Node not available in cache. Read from datastore - {}", connectionIid);
143 return transaction.read(logicalDatastoreType, connectionIid).get();
144 } catch (InterruptedException | ExecutionException e) {
145 LOG.error("Read failed from datastore for Node : {}",connectionIid,e);
146 throw new IllegalStateException(e);
150 public static Optional<HwvtepGlobalAugmentation> getManagingNode(DataBroker db,
151 HwvtepPhysicalSwitchAttributes node) {
152 Optional<HwvtepGlobalAugmentation> result = null;
153 HwvtepGlobalRef ref = requireNonNull(node).getManagedBy();
154 if (ref != null && ref.getValue() != null) {
155 result = getManagingNode(db, ref);
157 LOG.warn("Cannot find client for PhysicalSwitch without a specified ManagedBy {}", node);
158 return Optional.empty();
160 if (!result.isPresent()) {
161 LOG.warn("Failed to find managing node for PhysicalSwitch {}", node);
166 @SuppressWarnings("checkstyle:IllegalCatch")
167 public static Optional<HwvtepGlobalAugmentation> getManagingNode(DataBroker db, HwvtepGlobalRef ref) {
169 @SuppressWarnings("unchecked")
170 // Note: erasure makes this safe in combination with the typecheck
172 InstanceIdentifier<Node> path = (InstanceIdentifier<Node>) ref.getValue();
174 Optional<Node> optional = new MdsalUtils(db).readOptional(LogicalDatastoreType.OPERATIONAL, path);
175 if (optional != null && optional.isPresent()) {
176 HwvtepGlobalAugmentation hwvtepNode = null;
177 Node node = optional.get();
178 if (node instanceof HwvtepGlobalAugmentation) {
179 hwvtepNode = (HwvtepGlobalAugmentation) node;
180 } else if (node != null) {
181 hwvtepNode = node.augmentation(HwvtepGlobalAugmentation.class);
183 if (hwvtepNode != null) {
184 return Optional.of(hwvtepNode);
186 LOG.warn("Hwvtep switch claims to be managed by {} but " + "that HwvtepNode does not exist",
188 return Optional.empty();
191 LOG.warn("Mysteriously got back a thing which is *not* a topology Node: {}", optional);
192 return Optional.empty();
194 } catch (RuntimeException e) {
195 LOG.warn("Failed to get HwvtepNode {}", ref, e);
196 return Optional.empty();
200 public static String connectionInfoToString(final ConnectionInfo connectionInfo) {
201 return connectionInfo.getRemoteIp().stringValue() + ":" + connectionInfo.getRemotePort().getValue();
205 public static void schemaMismatchLog(String column, String table, SchemaVersionMismatchException ex) {
206 LOG.debug(SCHEMA_VERSION_MISMATCH, column, table, "hw_vtep", ex.getMessage());
209 public static <K, D> void updateData(Map<Class<? extends Identifiable>, Map<K, D>> map,
210 Class<? extends Identifiable> cls, K key, D data) {
211 LOG.debug("Updating data {} {} {}", cls, key, data);
215 if (!map.containsKey(cls)) {
216 map.put(cls, new ConcurrentHashMap<>());
218 map.get(cls).put(key, data);
221 public static <K, D> D getData(Map<Class<? extends Identifiable>, Map<K, D>> map,
222 Class<? extends Identifiable> cls, K key) {
226 if (map.containsKey(cls)) {
227 return map.get(cls).get(key);
232 public static <K, D> boolean containsKey(Map<Class<? extends Identifiable>, Map<K, D>> map,
233 Class<? extends Identifiable> cls, K key) {
237 if (map.containsKey(cls)) {
238 return map.get(cls).containsKey(key);
243 public static <K, D> void clearData(Map<Class<? extends Identifiable>, Map<K, D>> map,
244 Class<? extends Identifiable> cls, K key) {
245 LOG.debug("Clearing data {} {}", cls, key);
249 if (map.containsKey(cls)) {
250 map.get(cls).remove(key);
254 public static <T> boolean isEmpty(Collection<T> list) {
255 return list == null || list.isEmpty();
258 public static boolean isEmptyMap(Map<?, ?> map) {
259 return map == null || map.isEmpty();
262 public static InstanceIdentifier<Node> getGlobalNodeIid(final InstanceIdentifier<Node> physicalNodeIid) {
263 String nodeId = physicalNodeIid.firstKeyOf(Node.class).getNodeId().getValue();
264 int physicalSwitchIndex = nodeId.indexOf(HwvtepSouthboundConstants.PSWITCH_URI_PREFIX);
265 if (physicalSwitchIndex > 0) {
266 nodeId = nodeId.substring(0, physicalSwitchIndex - 1);
270 return physicalNodeIid.firstIdentifierOf(Topology.class).child(Node.class , new NodeKey(new NodeId(nodeId)));
273 public static Integer getRemotePort(Node node) {
274 HwvtepGlobalAugmentation augmentation = node.augmentation(HwvtepGlobalAugmentation.class);
275 if (augmentation != null && augmentation.getConnectionInfo() != null) {
276 return augmentation.getConnectionInfo().getRemotePort().getValue().toJava();
281 static void schedule(final Runnable command, final int delay, TimeUnit timeUnit) {
282 BACKGROUND_EXECUTOR.schedule(command, delay, timeUnit);