Update MRI projects for Aluminium
[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 com.google.common.base.Preconditions;
11 import com.google.common.util.concurrent.ThreadFactoryBuilder;
12 import java.util.Collection;
13 import java.util.Map;
14 import java.util.Optional;
15 import java.util.concurrent.ConcurrentHashMap;
16 import java.util.concurrent.ExecutionException;
17 import java.util.concurrent.Executors;
18 import java.util.concurrent.ScheduledExecutorService;
19 import org.opendaylight.mdsal.binding.api.DataBroker;
20 import org.opendaylight.mdsal.binding.api.ReadTransaction;
21 import org.opendaylight.mdsal.binding.api.ReadWriteTransaction;
22 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
23 import org.opendaylight.ovsdb.lib.error.SchemaVersionMismatchException;
24 import org.opendaylight.ovsdb.utils.mdsal.utils.ControllerMdsalUtils;
25 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepGlobalAugmentation;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepGlobalRef;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepPhysicalSwitchAttributes;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.global.attributes.ConnectionInfo;
29 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
30 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
31 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
32 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
33 import org.opendaylight.yangtools.yang.binding.DataObject;
34 import org.opendaylight.yangtools.yang.binding.Identifiable;
35 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
36 import org.opendaylight.yangtools.yang.data.impl.codec.DeserializationException;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 public final class HwvtepSouthboundUtil {
41
42     private static final Logger LOG = LoggerFactory.getLogger(HwvtepSouthboundUtil.class);
43     private static final String SCHEMA_VERSION_MISMATCH =
44             "{} column for {} table is not supported by this version of the {} schema: {}";
45
46     private static InstanceIdentifierCodec instanceIdentifierCodec;
47
48     private static ScheduledExecutorService scheduledExecutorService = Executors
49             .newSingleThreadScheduledExecutor(new ThreadFactoryBuilder()
50                     .setNameFormat("hwvteputil-executor-service-%d").build());
51
52     private HwvtepSouthboundUtil() {
53         // Prevent instantiating a utility class
54     }
55
56     public static void setInstanceIdentifierCodec(InstanceIdentifierCodec iidc) {
57         instanceIdentifierCodec = iidc;
58     }
59
60     public static InstanceIdentifierCodec getInstanceIdentifierCodec() {
61         return instanceIdentifierCodec;
62     }
63
64     public static String serializeInstanceIdentifier(InstanceIdentifier<?> iid) {
65         return instanceIdentifierCodec.serialize(iid);
66     }
67
68     public static InstanceIdentifier<?> deserializeInstanceIdentifier(String iidString) {
69         InstanceIdentifier<?> result = null;
70         try {
71             result = instanceIdentifierCodec.bindingDeserializer(iidString);
72         } catch (DeserializationException e) {
73             LOG.warn("Unable to deserialize iidString", e);
74         }
75         return result;
76     }
77
78     public static <D extends org.opendaylight.yangtools.yang.binding.DataObject> Optional<D> readNode(
79             DataBroker db,
80             LogicalDatastoreType logicalDatastoreType, final InstanceIdentifier<D> connectionIid) {
81         if (logicalDatastoreType == LogicalDatastoreType.OPERATIONAL) {
82             Node node = HwvtepOperGlobalListener.getNode((InstanceIdentifier<Node>) connectionIid);
83             if (node != null) {
84                 return Optional.of((D)node);
85             } else {
86                 LOG.debug("Node not available in cache. Read from datastore - {}", connectionIid);
87             }
88         }
89         try (ReadTransaction transaction = db.newReadOnlyTransaction()) {
90             return transaction.read(logicalDatastoreType, connectionIid).get();
91         } catch (InterruptedException | ExecutionException e) {
92             LOG.error("Read failed from datastore for Node : {}",connectionIid,e);
93             throw new RuntimeException(e);
94         }
95     }
96
97     public static <D extends org.opendaylight.yangtools.yang.binding.DataObject> Optional<D> readNode(
98             ReadTransaction transaction,
99             LogicalDatastoreType logicalDatastoreType, final InstanceIdentifier<D> connectionIid) {
100         if (logicalDatastoreType == LogicalDatastoreType.OPERATIONAL) {
101             Node node = HwvtepOperGlobalListener.getNode((InstanceIdentifier<Node>) connectionIid);
102             if (node != null) {
103                 return Optional.of((D)node);
104             } else {
105                 LOG.debug("Node not available in cache. Read from datastore - {}", connectionIid);
106             }
107         }
108         try {
109             return transaction.read(logicalDatastoreType, connectionIid).get();
110         } catch (InterruptedException | ExecutionException e) {
111             LOG.error("Read failed from datastore for Node : {}",connectionIid,e);
112             throw new RuntimeException(e);
113         }
114     }
115
116     public static <D extends org.opendaylight.yangtools.yang.binding.DataObject> Optional<D> readNode(
117             ReadWriteTransaction transaction, final InstanceIdentifier<D> connectionIid) {
118         return readNode(transaction, LogicalDatastoreType.OPERATIONAL, connectionIid);
119     }
120
121     public static <D extends DataObject> Optional<D> readNode(ReadWriteTransaction transaction,
122                                                               LogicalDatastoreType logicalDatastoreType,
123                                                               InstanceIdentifier<D> connectionIid) {
124         if (logicalDatastoreType == LogicalDatastoreType.OPERATIONAL) {
125             Node node = HwvtepOperGlobalListener.getNode((InstanceIdentifier<Node>) connectionIid);
126             if (node != null) {
127                 return Optional.of((D)node);
128             } else {
129                 LOG.debug("Node not available in cache. Read from datastore - {}", connectionIid);
130             }
131         }
132         try {
133             return transaction.read(logicalDatastoreType, connectionIid).get();
134         } catch (InterruptedException | ExecutionException e) {
135             LOG.error("Read failed from datastore for Node : {}",connectionIid,e);
136             throw new RuntimeException(e);
137         }
138     }
139
140     public static Optional<HwvtepGlobalAugmentation> getManagingNode(DataBroker db,
141                     HwvtepPhysicalSwitchAttributes node) {
142         Preconditions.checkNotNull(node);
143         Optional<HwvtepGlobalAugmentation> result = null;
144         HwvtepGlobalRef ref = 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 ControllerMdsalUtils(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 }