dfc112e269e68e4e86ae0e3e6273bcc96367e23c
[ovsdb.git] / hwvtepsouthbound / hwvtepsouthbound-impl / src / main / java / org / opendaylight / ovsdb / hwvtepsouthbound / HwvtepSouthboundUtil.java
1 /*
2  * Copyright (c) 2015, 2017 Ericsson India Global Services Pvt Ltd. 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.hwvtepsouthbound;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.util.concurrent.ThreadFactoryBuilder;
13 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
14 import java.util.Collection;
15 import java.util.Map;
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;
42
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")
48             .build());
49
50     private static final String SCHEMA_VERSION_MISMATCH =
51             "{} column for {} table is not supported by this version of the {} schema: {}";
52
53     private static InstanceIdentifierCodec instanceIdentifierCodec;
54
55
56     private HwvtepSouthboundUtil() {
57         // Prevent instantiating a utility class
58     }
59
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;
65     }
66
67     // FIXME: this should be an instance method
68     public static InstanceIdentifierCodec getInstanceIdentifierCodec() {
69         return instanceIdentifierCodec;
70     }
71
72     // FIXME: this should be an instance method
73     public static String serializeInstanceIdentifier(InstanceIdentifier<?> iid) {
74         return instanceIdentifierCodec.serialize(iid);
75     }
76
77     // FIXME: this should be an instance method
78     public static InstanceIdentifier<?> deserializeInstanceIdentifier(String iidString) {
79         InstanceIdentifier<?> result = null;
80         try {
81             result = instanceIdentifierCodec.bindingDeserializer(iidString);
82         } catch (DeserializationException e) {
83             LOG.warn("Unable to deserialize iidString", e);
84         }
85         return result;
86     }
87
88     public static <D extends org.opendaylight.yangtools.yang.binding.DataObject> Optional<D> readNode(
89             DataBroker db,
90             LogicalDatastoreType logicalDatastoreType, final InstanceIdentifier<D> connectionIid) {
91         if (logicalDatastoreType == LogicalDatastoreType.OPERATIONAL) {
92             Node node = HwvtepOperGlobalListener.getNode((InstanceIdentifier<Node>) connectionIid);
93             if (node != null) {
94                 return Optional.of((D)node);
95             } else {
96                 LOG.debug("Node not available in cache. Read from datastore - {}", connectionIid);
97             }
98         }
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 RuntimeException(e);
104         }
105     }
106
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);
112             if (node != null) {
113                 return Optional.of((D)node);
114             } else {
115                 LOG.debug("Node not available in cache. Read from datastore - {}", connectionIid);
116             }
117         }
118         try {
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 RuntimeException(e);
123         }
124     }
125
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);
129     }
130
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);
136             if (node != null) {
137                 return Optional.of((D)node);
138             } else {
139                 LOG.debug("Node not available in cache. Read from datastore - {}", connectionIid);
140             }
141         }
142         try {
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 RuntimeException(e);
147         }
148     }
149
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);
156         } else {
157             LOG.warn("Cannot find client for PhysicalSwitch without a specified ManagedBy {}", node);
158             return Optional.empty();
159         }
160         if (!result.isPresent()) {
161             LOG.warn("Failed to find managing node for PhysicalSwitch {}", node);
162         }
163         return result;
164     }
165
166     @SuppressWarnings("checkstyle:IllegalCatch")
167     public static Optional<HwvtepGlobalAugmentation> getManagingNode(DataBroker db, HwvtepGlobalRef ref) {
168         try {
169             @SuppressWarnings("unchecked")
170             // Note: erasure makes this safe in combination with the typecheck
171             // below
172             InstanceIdentifier<Node> path = (InstanceIdentifier<Node>) ref.getValue();
173
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);
182                 }
183                 if (hwvtepNode != null) {
184                     return Optional.of(hwvtepNode);
185                 } else {
186                     LOG.warn("Hwvtep switch claims to be managed by {} but " + "that HwvtepNode does not exist",
187                                     ref.getValue());
188                     return Optional.empty();
189                 }
190             } else {
191                 LOG.warn("Mysteriously got back a thing which is *not* a topology Node: {}", optional);
192                 return Optional.empty();
193             }
194         } catch (RuntimeException e) {
195             LOG.warn("Failed to get HwvtepNode {}", ref, e);
196             return Optional.empty();
197         }
198     }
199
200     public static String connectionInfoToString(final ConnectionInfo connectionInfo) {
201         return connectionInfo.getRemoteIp().stringValue() + ":" + connectionInfo.getRemotePort().getValue();
202     }
203
204
205     public static void schemaMismatchLog(String column, String table, SchemaVersionMismatchException ex) {
206         LOG.debug(SCHEMA_VERSION_MISMATCH, column, table, "hw_vtep", ex.getMessage());
207     }
208
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);
212         if (key == null) {
213             return;
214         }
215         if (!map.containsKey(cls)) {
216             map.put(cls, new ConcurrentHashMap<>());
217         }
218         map.get(cls).put(key, data);
219     }
220
221     public static <K, D> D getData(Map<Class<? extends Identifiable>, Map<K, D>> map,
222             Class<? extends Identifiable> cls, K key) {
223         if (key == null) {
224             return null;
225         }
226         if (map.containsKey(cls)) {
227             return map.get(cls).get(key);
228         }
229         return null;
230     }
231
232     public static <K, D> boolean containsKey(Map<Class<? extends Identifiable>, Map<K, D>> map,
233             Class<? extends Identifiable> cls, K key) {
234         if (key == null) {
235             return false;
236         }
237         if (map.containsKey(cls)) {
238             return map.get(cls).containsKey(key);
239         }
240         return false;
241     }
242
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);
246         if (key == null) {
247             return;
248         }
249         if (map.containsKey(cls)) {
250             map.get(cls).remove(key);
251         }
252     }
253
254     public static <T> boolean isEmpty(Collection<T> list) {
255         return list == null || list.isEmpty();
256     }
257
258     public static boolean isEmptyMap(Map<?, ?> map) {
259         return map == null || map.isEmpty();
260     }
261
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);
267         } else {
268             return null;
269         }
270         return physicalNodeIid.firstIdentifierOf(Topology.class).child(Node.class , new NodeKey(new NodeId(nodeId)));
271     }
272
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();
277         }
278         return 0;
279     }
280
281     static void schedule(final Runnable command, final int delay, TimeUnit timeUnit) {
282         BACKGROUND_EXECUTOR.schedule(command, delay, timeUnit);
283     }
284 }