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