Migrate to Objects.requireNonNull()
[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 java.util.Collection;
14 import java.util.Map;
15 import java.util.Optional;
16 import java.util.concurrent.ConcurrentHashMap;
17 import java.util.concurrent.ExecutionException;
18 import java.util.concurrent.Executors;
19 import java.util.concurrent.ScheduledExecutorService;
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.ovsdb.utils.mdsal.utils.MdsalUtils;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepGlobalAugmentation;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepGlobalRef;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepPhysicalSwitchAttributes;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.global.attributes.ConnectionInfo;
30 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
31 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
32 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
33 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
34 import org.opendaylight.yangtools.yang.binding.DataObject;
35 import org.opendaylight.yangtools.yang.binding.Identifiable;
36 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
37 import org.opendaylight.yangtools.yang.data.impl.codec.DeserializationException;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41 public final class HwvtepSouthboundUtil {
42
43     private static final Logger LOG = LoggerFactory.getLogger(HwvtepSouthboundUtil.class);
44     private static final String SCHEMA_VERSION_MISMATCH =
45             "{} column for {} table is not supported by this version of the {} schema: {}";
46
47     private static InstanceIdentifierCodec instanceIdentifierCodec;
48
49     private static ScheduledExecutorService scheduledExecutorService = Executors
50             .newSingleThreadScheduledExecutor(new ThreadFactoryBuilder()
51                     .setNameFormat("hwvteputil-executor-service-%d").build());
52
53     private HwvtepSouthboundUtil() {
54         // Prevent instantiating a utility class
55     }
56
57     public static void setInstanceIdentifierCodec(InstanceIdentifierCodec iidc) {
58         instanceIdentifierCodec = iidc;
59     }
60
61     public static InstanceIdentifierCodec getInstanceIdentifierCodec() {
62         return instanceIdentifierCodec;
63     }
64
65     public static String serializeInstanceIdentifier(InstanceIdentifier<?> iid) {
66         return instanceIdentifierCodec.serialize(iid);
67     }
68
69     public static InstanceIdentifier<?> deserializeInstanceIdentifier(String iidString) {
70         InstanceIdentifier<?> result = null;
71         try {
72             result = instanceIdentifierCodec.bindingDeserializer(iidString);
73         } catch (DeserializationException e) {
74             LOG.warn("Unable to deserialize iidString", e);
75         }
76         return result;
77     }
78
79     public static <D extends org.opendaylight.yangtools.yang.binding.DataObject> Optional<D> readNode(
80             DataBroker db,
81             LogicalDatastoreType logicalDatastoreType, final InstanceIdentifier<D> connectionIid) {
82         if (logicalDatastoreType == LogicalDatastoreType.OPERATIONAL) {
83             Node node = HwvtepOperGlobalListener.getNode((InstanceIdentifier<Node>) connectionIid);
84             if (node != null) {
85                 return Optional.of((D)node);
86             } else {
87                 LOG.debug("Node not available in cache. Read from datastore - {}", connectionIid);
88             }
89         }
90         try (ReadTransaction transaction = db.newReadOnlyTransaction()) {
91             return transaction.read(logicalDatastoreType, connectionIid).get();
92         } catch (InterruptedException | ExecutionException e) {
93             LOG.error("Read failed from datastore for Node : {}",connectionIid,e);
94             throw new RuntimeException(e);
95         }
96     }
97
98     public static <D extends org.opendaylight.yangtools.yang.binding.DataObject> Optional<D> readNode(
99             ReadTransaction transaction,
100             LogicalDatastoreType logicalDatastoreType, final InstanceIdentifier<D> connectionIid) {
101         if (logicalDatastoreType == LogicalDatastoreType.OPERATIONAL) {
102             Node node = HwvtepOperGlobalListener.getNode((InstanceIdentifier<Node>) connectionIid);
103             if (node != null) {
104                 return Optional.of((D)node);
105             } else {
106                 LOG.debug("Node not available in cache. Read from datastore - {}", connectionIid);
107             }
108         }
109         try {
110             return transaction.read(logicalDatastoreType, connectionIid).get();
111         } catch (InterruptedException | ExecutionException e) {
112             LOG.error("Read failed from datastore for Node : {}",connectionIid,e);
113             throw new RuntimeException(e);
114         }
115     }
116
117     public static <D extends org.opendaylight.yangtools.yang.binding.DataObject> Optional<D> readNode(
118             ReadWriteTransaction transaction, final InstanceIdentifier<D> connectionIid) {
119         return readNode(transaction, LogicalDatastoreType.OPERATIONAL, connectionIid);
120     }
121
122     public static <D extends DataObject> Optional<D> readNode(ReadWriteTransaction transaction,
123                                                               LogicalDatastoreType logicalDatastoreType,
124                                                               InstanceIdentifier<D> connectionIid) {
125         if (logicalDatastoreType == LogicalDatastoreType.OPERATIONAL) {
126             Node node = HwvtepOperGlobalListener.getNode((InstanceIdentifier<Node>) connectionIid);
127             if (node != null) {
128                 return Optional.of((D)node);
129             } else {
130                 LOG.debug("Node not available in cache. Read from datastore - {}", connectionIid);
131             }
132         }
133         try {
134             return transaction.read(logicalDatastoreType, connectionIid).get();
135         } catch (InterruptedException | ExecutionException e) {
136             LOG.error("Read failed from datastore for Node : {}",connectionIid,e);
137             throw new RuntimeException(e);
138         }
139     }
140
141     public static Optional<HwvtepGlobalAugmentation> getManagingNode(DataBroker db,
142                     HwvtepPhysicalSwitchAttributes node) {
143         Optional<HwvtepGlobalAugmentation> result = null;
144         HwvtepGlobalRef ref = requireNonNull(node).getManagedBy();
145         if (ref != null && ref.getValue() != null) {
146             result = getManagingNode(db, ref);
147         } else {
148             LOG.warn("Cannot find client for PhysicalSwitch without a specified ManagedBy {}", node);
149             return Optional.empty();
150         }
151         if (!result.isPresent()) {
152             LOG.warn("Failed to find managing node for PhysicalSwitch {}", node);
153         }
154         return result;
155     }
156
157     @SuppressWarnings("checkstyle:IllegalCatch")
158     public static Optional<HwvtepGlobalAugmentation> getManagingNode(DataBroker db, HwvtepGlobalRef ref) {
159         try {
160             @SuppressWarnings("unchecked")
161             // Note: erasure makes this safe in combination with the typecheck
162             // below
163             InstanceIdentifier<Node> path = (InstanceIdentifier<Node>) ref.getValue();
164
165             Optional<Node> optional = new MdsalUtils(db).readOptional(LogicalDatastoreType.OPERATIONAL, path);
166             if (optional != null && optional.isPresent()) {
167                 HwvtepGlobalAugmentation hwvtepNode = null;
168                 Node node = optional.get();
169                 if (node instanceof HwvtepGlobalAugmentation) {
170                     hwvtepNode = (HwvtepGlobalAugmentation) node;
171                 } else if (node != null) {
172                     hwvtepNode = node.augmentation(HwvtepGlobalAugmentation.class);
173                 }
174                 if (hwvtepNode != null) {
175                     return Optional.of(hwvtepNode);
176                 } else {
177                     LOG.warn("Hwvtep switch claims to be managed by {} but " + "that HwvtepNode does not exist",
178                                     ref.getValue());
179                     return Optional.empty();
180                 }
181             } else {
182                 LOG.warn("Mysteriously got back a thing which is *not* a topology Node: {}", optional);
183                 return Optional.empty();
184             }
185         } catch (RuntimeException e) {
186             LOG.warn("Failed to get HwvtepNode {}", ref, e);
187             return Optional.empty();
188         }
189     }
190
191     public static String connectionInfoToString(final ConnectionInfo connectionInfo) {
192         return connectionInfo.getRemoteIp().stringValue() + ":" + connectionInfo.getRemotePort().getValue();
193     }
194
195
196     public static void schemaMismatchLog(String column, String table, SchemaVersionMismatchException ex) {
197         LOG.debug(SCHEMA_VERSION_MISMATCH, column, table, "hw_vtep", ex.getMessage());
198     }
199
200     public static <K, D> void updateData(Map<Class<? extends Identifiable>, Map<K, D>> map,
201             Class<? extends Identifiable> cls, K key, D data) {
202         LOG.debug("Updating data {} {} {}", cls, key, data);
203         if (key == null) {
204             return;
205         }
206         if (!map.containsKey(cls)) {
207             map.put(cls, new ConcurrentHashMap<>());
208         }
209         map.get(cls).put(key, data);
210     }
211
212     public static <K, D> D getData(Map<Class<? extends Identifiable>, Map<K, D>> map,
213             Class<? extends Identifiable> cls, K key) {
214         if (key == null) {
215             return null;
216         }
217         if (map.containsKey(cls)) {
218             return map.get(cls).get(key);
219         }
220         return null;
221     }
222
223     public static <K, D> boolean containsKey(Map<Class<? extends Identifiable>, Map<K, D>> map,
224             Class<? extends Identifiable> cls, K key) {
225         if (key == null) {
226             return false;
227         }
228         if (map.containsKey(cls)) {
229             return map.get(cls).containsKey(key);
230         }
231         return false;
232     }
233
234     public static <K, D> void clearData(Map<Class<? extends Identifiable>, Map<K, D>> map,
235             Class<? extends Identifiable> cls, K key) {
236         LOG.debug("Clearing data {} {}", cls, key);
237         if (key == null) {
238             return;
239         }
240         if (map.containsKey(cls)) {
241             map.get(cls).remove(key);
242         }
243     }
244
245     public static <T> boolean isEmpty(Collection<T> list) {
246         return list == null || list.isEmpty();
247     }
248
249     public static boolean isEmptyMap(Map<?, ?> map) {
250         return map == null || map.isEmpty();
251     }
252
253     public static InstanceIdentifier<Node> getGlobalNodeIid(final InstanceIdentifier<Node> physicalNodeIid) {
254         String nodeId = physicalNodeIid.firstKeyOf(Node.class).getNodeId().getValue();
255         int physicalSwitchIndex = nodeId.indexOf(HwvtepSouthboundConstants.PSWITCH_URI_PREFIX);
256         if (physicalSwitchIndex > 0) {
257             nodeId = nodeId.substring(0, physicalSwitchIndex - 1);
258         } else {
259             return null;
260         }
261         return physicalNodeIid.firstIdentifierOf(Topology.class).child(Node.class , new NodeKey(new NodeId(nodeId)));
262     }
263
264     public static Integer getRemotePort(Node node) {
265         HwvtepGlobalAugmentation augmentation = node.augmentation(HwvtepGlobalAugmentation.class);
266         if (augmentation != null && augmentation.getConnectionInfo() != null) {
267             return augmentation.getConnectionInfo().getRemotePort().getValue().toJava();
268         }
269         return 0;
270     }
271
272     public static ScheduledExecutorService getScheduledExecutorService() {
273         return scheduledExecutorService;
274     }
275 }