c5e565a2d53add51b093741c64ca96342dd92ef4
[ovsdb.git] / southbound / southbound-impl / src / main / java / org / opendaylight / ovsdb / southbound / ovsdb / transact / TransactUtils.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. 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.southbound.ovsdb.transact;
9
10 import static org.opendaylight.ovsdb.lib.operations.Operations.op;
11
12 import java.util.ArrayList;
13 import java.util.Collection;
14 import java.util.HashMap;
15 import java.util.HashSet;
16 import java.util.LinkedList;
17 import java.util.List;
18 import java.util.Map;
19 import java.util.Map.Entry;
20 import java.util.Queue;
21 import java.util.Set;
22
23 import javax.annotation.Nullable;
24
25 import com.google.common.base.Predicate;
26 import org.opendaylight.controller.md.sal.binding.api.DataObjectModification;
27 import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
28 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
29 import org.opendaylight.ovsdb.lib.notation.Mutation;
30 import org.opendaylight.ovsdb.lib.notation.Mutator;
31 import org.opendaylight.ovsdb.lib.notation.OvsdbSet;
32 import org.opendaylight.ovsdb.lib.notation.UUID;
33 import org.opendaylight.ovsdb.lib.operations.Insert;
34 import org.opendaylight.ovsdb.lib.operations.Mutate;
35 import org.opendaylight.ovsdb.lib.operations.Operation;
36 import org.opendaylight.ovsdb.lib.operations.TransactionBuilder;
37 import org.opendaylight.ovsdb.lib.schema.ColumnSchema;
38 import org.opendaylight.ovsdb.lib.schema.GenericTableSchema;
39 import org.opendaylight.ovsdb.lib.schema.TableSchema;
40 import org.opendaylight.ovsdb.southbound.SouthboundConstants;
41 import org.opendaylight.ovsdb.southbound.SouthboundMapper;
42 import org.opendaylight.ovsdb.southbound.SouthboundUtil;
43 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
44
45 import org.opendaylight.yangtools.yang.binding.ChildOf;
46 import org.opendaylight.yangtools.yang.binding.DataObject;
47 import org.opendaylight.yangtools.yang.binding.Identifiable;
48 import org.opendaylight.yangtools.yang.binding.Identifier;
49 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
50 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
51
52 import com.google.common.base.Predicates;
53 import com.google.common.collect.ImmutableMap;
54 import com.google.common.collect.Lists;
55 import com.google.common.collect.Maps;
56 import com.google.common.collect.Sets;
57
58 public class TransactUtils {
59     private static <T extends DataObject> Predicate<DataObjectModification<T>> hasDataBefore() {
60         return new Predicate<DataObjectModification<T>>() {
61             @Override
62             public boolean apply(@Nullable DataObjectModification<T> input) {
63                 return input != null && input.getDataBefore() != null;
64             }
65         };
66     }
67
68     private static <T extends DataObject> Predicate<DataObjectModification<T>> hasDataBeforeAndDataAfter() {
69         return new Predicate<DataObjectModification<T>>() {
70             @Override
71             public boolean apply(@Nullable DataObjectModification<T> input) {
72                 return input != null && input.getDataBefore() != null && input.getDataAfter() != null;
73             }
74         };
75     }
76
77     private static <T extends DataObject> Predicate<DataObjectModification<T>> hasNoDataBefore() {
78         return new Predicate<DataObjectModification<T>>() {
79             @Override
80             public boolean apply(@Nullable DataObjectModification<T> input) {
81                 return input != null && input.getDataBefore() == null;
82             }
83         };
84     }
85
86     private static <T extends DataObject> Predicate<DataObjectModification<T>> hasDataAfterAndMatchesFilter(
87             final Predicate<DataObjectModification<T>> filter) {
88         return new Predicate<DataObjectModification<T>>() {
89             @Override
90             public boolean apply(@Nullable DataObjectModification<T> input) {
91                 return input != null && input.getDataAfter() != null && filter.apply(input);
92             }
93         };
94     }
95
96     private static <T extends DataObject> Predicate<DataObjectModification<T>> matchesEverything() {
97         return new Predicate<DataObjectModification<T>>() {
98             @Override
99             public boolean apply(@Nullable DataObjectModification<T> input) {
100                 return true;
101             }
102         };
103     }
104
105     private static <T extends DataObject> Predicate<DataObjectModification<T>> modificationIsDeletion() {
106         return new Predicate<DataObjectModification<T>>() {
107             @Override
108             public boolean apply(@Nullable DataObjectModification<T> input) {
109                 return input != null && input.getModificationType() == DataObjectModification
110                         .ModificationType.DELETE;
111             }
112         };
113     }
114
115     private static <T extends DataObject> Predicate<DataObjectModification<T>> modificationIsDeletionAndHasDataBefore
116             () {
117         return new Predicate<DataObjectModification<T>>() {
118             @Override
119             public boolean apply(@Nullable DataObjectModification<T> input) {
120                 return input != null && input.getModificationType() == DataObjectModification
121                         .ModificationType.DELETE && input.getDataBefore() != null;
122             }
123         };
124     }
125
126     public static Map<InstanceIdentifier<Node>,Node> extractNode(
127             Map<InstanceIdentifier<?>, DataObject> changes) {
128         Map<InstanceIdentifier<Node>,Node> result
129             = new HashMap<>();
130         if (changes != null) {
131             for (Entry<InstanceIdentifier<?>, DataObject> created : changes.entrySet()) {
132                 if (created.getValue() instanceof Node) {
133                     Node value = (Node) created.getValue();
134                     Class<?> type = created.getKey().getTargetType();
135                     if (type.equals(Node.class)) {
136                         @SuppressWarnings("unchecked") // Actually checked above
137                         InstanceIdentifier<Node> iid = (InstanceIdentifier<Node>) created.getKey();
138                         result.put(iid, value);
139                     }
140                 }
141             }
142         }
143         return result;
144     }
145
146     public static <T extends DataObject> Map<InstanceIdentifier<T>,T> extractCreated(
147             AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes,Class<T> klazz) {
148         return extract(changes.getCreatedData(),klazz);
149     }
150
151     /**
152      * Extract all the instances of {@code clazz} which were created in the given set of modifications.
153      *
154      * @param changes The changes to process.
155      * @param clazz The class we're interested in.
156      * @param <T> The type of changes we're interested in.
157      * @param <U> The type of changes to process.
158      * @return The created instances, mapped by instance identifier.
159      */
160     public static <T extends DataObject, U extends DataObject> Map<InstanceIdentifier<T>, T> extractCreated(
161             Collection<DataTreeModification<U>> changes, Class<T> clazz) {
162         return extractCreatedOrUpdated(changes, clazz, hasNoDataBefore());
163     }
164
165     /**
166      * Extract all the instance of {@code clazz} which were created or updated in the given set of modifications, and
167      * which satisfy the given filter.
168      *
169      * @param changes The changes to process.
170      * @param clazz The class we're interested in.
171      * @param filter The filter the changes must satisfy.
172      * @param <T> The type of changes we're interested in.
173      * @param <U> The type of changes to process.
174      * @return The created or updated instances which satisfy the filter, mapped by instance identifier.
175      */
176     public static <T extends DataObject, U extends DataObject> Map<InstanceIdentifier<T>, T> extractCreatedOrUpdated(
177             Collection<DataTreeModification<U>> changes, Class<T> clazz,
178             Predicate<DataObjectModification<T>> filter) {
179         Map<InstanceIdentifier<T>, T> result = new HashMap<>();
180         for (Map.Entry<InstanceIdentifier<T>, DataObjectModification<T>> entry : extractDataObjectModifications(changes,
181                 clazz, hasDataAfterAndMatchesFilter(filter)).entrySet()) {
182             result.put(entry.getKey(), entry.getValue().getDataAfter());
183         }
184         return result;
185     }
186
187     public static <T extends DataObject> Map<InstanceIdentifier<T>,T> extractUpdated(
188             AsyncDataChangeEvent<InstanceIdentifier<?>,DataObject> changes,Class<T> klazz) {
189         return extract(changes.getUpdatedData(),klazz);
190     }
191
192     /**
193      * Extract all the instances of {@code clazz} which were updated in the given set of modifications.
194      *
195      * @param changes The changes to process.
196      * @param clazz The class we're interested in.
197      * @param <T> The type of changes we're interested in.
198      * @param <U> The type of changes to process.
199      * @return The updated instances, mapped by instance identifier.
200      */
201     public static <T extends DataObject, U extends DataObject> Map<InstanceIdentifier<T>, T> extractUpdated(
202             Collection<DataTreeModification<U>> changes, Class<T> clazz) {
203         return extractCreatedOrUpdated(changes, clazz, hasDataBeforeAndDataAfter());
204     }
205
206     public static <T extends DataObject> Map<InstanceIdentifier<T>,T> extractCreatedOrUpdated(
207             AsyncDataChangeEvent<InstanceIdentifier<?>,DataObject> changes,Class<T> klazz) {
208         Map<InstanceIdentifier<T>,T> result = extractUpdated(changes,klazz);
209         result.putAll(extractCreated(changes,klazz));
210         return result;
211     }
212
213     /**
214      * Extract all the instances of {@code clazz} which were created or updated in the given set of modifications.
215      *
216      * @param changes The changes to process.
217      * @param clazz The class we're interested in.
218      * @param <T> The type of changes we're interested in.
219      * @param <U> The type of changes to process.
220      * @return The created or updated instances, mapped by instance identifier.
221      */
222     public static <T extends DataObject, U extends DataObject> Map<InstanceIdentifier<T>, T> extractCreatedOrUpdated(
223             Collection<DataTreeModification<U>> changes, Class<T> clazz) {
224         return extractCreatedOrUpdated(changes, clazz, matchesEverything());
225     }
226
227     public static <T extends DataObject> Map<InstanceIdentifier<T>, T> extractCreatedOrUpdatedOrRemoved(
228             AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes,
229             Class<T> klazz) {
230         Map<InstanceIdentifier<T>,T> result = extractCreatedOrUpdated(changes,klazz);
231         result.putAll(extractRemovedObjects(changes, klazz));
232         return result;
233     }
234
235     /**
236      * Extract all the instances of {@code clazz} which were created, updated, or removed in the given set of
237      * modifications. For instances which were created or updated, the new instances are returned; for instances
238      * which were removed, the old instances are returned.
239      *
240      * @param changes The changes to process.
241      * @param clazz The class we're interested in.
242      * @param <T> The type of changes we're interested in.
243      * @param <U> The type of changes to process.
244      * @return The created, updated or removed instances, mapped by instance identifier.
245      */
246     public static <T extends DataObject, U extends DataObject> Map<InstanceIdentifier<T>, T>
247     extractCreatedOrUpdatedOrRemoved(
248             Collection<DataTreeModification<U>> changes, Class<T> clazz) {
249         Map<InstanceIdentifier<T>, T> result = extractCreatedOrUpdated(changes, clazz);
250         result.putAll(extractRemovedObjects(changes, clazz));
251         return result;
252     }
253
254     public static <T extends DataObject> Map<InstanceIdentifier<T>,T> extractOriginal(
255             AsyncDataChangeEvent<InstanceIdentifier<?>,DataObject> changes,Class<T> klazz) {
256         return extract(changes.getOriginalData(),klazz);
257     }
258
259     /**
260      * Extract the original instances of class {@code clazz} in the given set of modifications.
261      *
262      * @param changes The changes to process.
263      * @param clazz The class we're interested in.
264      * @param <T> The type of changes we're interested in.
265      * @param <U> The type of changes to process.
266      * @return The original instances, mapped by instance identifier.
267      */
268     public static <T extends DataObject, U extends DataObject> Map<InstanceIdentifier<T>, T> extractOriginal(
269             Collection<DataTreeModification<U>> changes, Class<T> clazz) {
270         Map<InstanceIdentifier<T>, T> result = new HashMap<>();
271         for (Map.Entry<InstanceIdentifier<T>, DataObjectModification<T>> entry :
272                 extractDataObjectModifications(changes, clazz, hasDataBefore()).entrySet()) {
273             result.put(entry.getKey(), entry.getValue().getDataBefore());
274         }
275         return result;
276     }
277
278     public static <T extends DataObject> Set<InstanceIdentifier<T>> extractRemoved(
279             AsyncDataChangeEvent<InstanceIdentifier<?>,DataObject> changes,Class<T> klazz) {
280         Set<InstanceIdentifier<T>> result = new HashSet<>();
281         if (changes != null && changes.getRemovedPaths() != null) {
282             for (InstanceIdentifier<?> iid : changes.getRemovedPaths()) {
283                 if (iid.getTargetType().equals(klazz)) {
284                     @SuppressWarnings("unchecked") // Actually checked above
285                     InstanceIdentifier<T> iidn = (InstanceIdentifier<T>)iid;
286                     result.add(iidn);
287                 }
288             }
289         }
290         return result;
291     }
292
293     /**
294      * Extract the instance identifier of removed instances of {@code clazz} from the given set of modifications.
295      *
296      * @param changes The changes to process.
297      * @param clazz The class we're interested in.
298      * @param <T> The type of changes we're interested in.
299      * @param <U> The type of changes to process.
300      * @return The instance identifiers of removed instances.
301      */
302     public static <T extends DataObject, U extends DataObject> Set<InstanceIdentifier<T>> extractRemoved(
303             Collection<DataTreeModification<U>> changes, Class<T> clazz) {
304         return extractDataObjectModifications(changes, clazz, modificationIsDeletion()).keySet();
305     }
306
307     /**
308      * Extract all the modifications affecting instances of {@code clazz} which are present in the given set of
309      * modifications and satisfy the given filter.
310      *
311      * @param changes The changes to process.
312      * @param clazz The class we're interested in.
313      * @param filter The filter the changes must satisfy.
314      * @param <T> The type of changes we're interested in.
315      * @param <U> The type of changes to process.
316      * @return The modifications, mapped by instance identifier.
317      */
318     private static <T extends DataObject, U extends DataObject> Map<InstanceIdentifier<T>, DataObjectModification<T>>
319     extractDataObjectModifications(
320             Collection<DataTreeModification<U>> changes, Class<T> clazz,
321             Predicate<DataObjectModification<T>> filter) {
322         List<DataObjectModification<? extends DataObject>> dataObjectModifications = new ArrayList<>();
323         List<InstanceIdentifier<? extends DataObject>> paths = new ArrayList<>();
324         if (changes != null) {
325             for (DataTreeModification<? extends DataObject> change : changes) {
326                 dataObjectModifications.add(change.getRootNode());
327                 paths.add(change.getRootPath().getRootIdentifier());
328             }
329         }
330         return extractDataObjectModifications(dataObjectModifications, paths, clazz, filter);
331     }
332
333     /**
334      * Extract all the modifications affecting instances of {@code clazz} which are present in the given set of
335      * modifications and satisfy the given filter.
336      *
337      * @param changes The changes to process.
338      * @param paths The paths of the changes.
339      * @param clazz The class we're interested in.
340      * @param filter The filter the changes must satisfy.
341      * @param <T> The type of changes we're interested in.
342      * @return The modifications, mapped by instance identifier.
343      */
344     private static <T extends DataObject> Map<InstanceIdentifier<T>, DataObjectModification<T>>
345     extractDataObjectModifications(
346             Collection<DataObjectModification<? extends DataObject>> changes,
347             Collection<InstanceIdentifier<? extends DataObject>> paths, Class<T> clazz,
348             Predicate<DataObjectModification<T>> filter) {
349         Map<InstanceIdentifier<T>, DataObjectModification<T>> result = new HashMap<>();
350         Queue<DataObjectModification<? extends DataObject>> remainingChanges = new LinkedList<>(changes);
351         Queue<InstanceIdentifier<? extends DataObject>> remainingPaths = new LinkedList<>(paths);
352         while (!remainingChanges.isEmpty()) {
353             DataObjectModification<? extends DataObject> change = remainingChanges.remove();
354             InstanceIdentifier<? extends DataObject> path = remainingPaths.remove();
355             // Is the change relevant?
356             if (clazz.isAssignableFrom(change.getDataType()) && filter.apply((DataObjectModification<T>) change)) {
357                 result.put((InstanceIdentifier<T>) path, (DataObjectModification<T>) change);
358             }
359             // Add any children to the queue
360             for (DataObjectModification<? extends DataObject> child : change.getModifiedChildren()) {
361                 remainingChanges.add(child);
362                 remainingPaths.add(extendPath(path, child));
363             }
364         }
365         return result;
366     }
367
368     /**
369      * Extends the given instance identifier path to include the given child. Augmentations are treated in the same way
370      * as children; keyed children are handled correctly.
371      *
372      * @param path The current path.
373      * @param child The child modification to include.
374      * @return The extended path.
375      */
376     private static <N extends Identifiable<K> & ChildOf<? super T>, K extends Identifier<N>, T extends DataObject>
377     InstanceIdentifier<? extends DataObject> extendPath(
378             InstanceIdentifier path,
379             DataObjectModification child) {
380         Class<N> item = (Class<N>) child.getDataType();
381         if (child.getIdentifier() instanceof InstanceIdentifier.IdentifiableItem) {
382             K key = (K) ((InstanceIdentifier.IdentifiableItem) child.getIdentifier()).getKey();
383             KeyedInstanceIdentifier<N, K> extendedPath = path.child(item, key);
384             return extendedPath;
385         } else {
386             InstanceIdentifier<N> extendedPath = path.child(item);
387             return extendedPath;
388         }
389     }
390
391     public static <T extends DataObject> Map<InstanceIdentifier<T>, T> extractRemovedObjects(
392             AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes,
393             Class<T> klazz) {
394         Set<InstanceIdentifier<T>> iids = extractRemoved(changes, klazz);
395         return Maps.filterKeys(extractOriginal(changes, klazz),Predicates.in(iids));
396     }
397
398     /**
399      * Extract the removed instances of {@code clazz} from the given set of modifications.
400      *
401      * @param changes The changes to process.
402      * @param clazz The class we're interested in.
403      * @param <T> The type of changes we're interested in.
404      * @param <U> The type of changes to process.
405      * @return The removed instances, keyed by instance identifier.
406      */
407     public static <T extends DataObject, U extends DataObject> Map<InstanceIdentifier<T>, T> extractRemovedObjects(
408             Collection<DataTreeModification<U>> changes, Class<T> clazz) {
409         Map<InstanceIdentifier<T>, T> result = new HashMap<>();
410         for (Map.Entry<InstanceIdentifier<T>, DataObjectModification<T>> entry :
411                 extractDataObjectModifications(changes, clazz, modificationIsDeletionAndHasDataBefore()).entrySet()) {
412             result.put(entry.getKey(), entry.getValue().getDataBefore());
413         }
414         return result;
415     }
416
417     public static <T extends DataObject> Map<InstanceIdentifier<T>,T> extract(
418             Map<InstanceIdentifier<?>, DataObject> changes, Class<T> klazz) {
419         Map<InstanceIdentifier<T>,T> result = new HashMap<>();
420         if (changes != null) {
421             for (Entry<InstanceIdentifier<?>, DataObject> created : changes.entrySet()) {
422                 if (klazz.isInstance(created.getValue())) {
423                     @SuppressWarnings("unchecked")
424                     T value = (T) created.getValue();
425                     Class<?> type = created.getKey().getTargetType();
426                     if (type.equals(klazz)) {
427                         @SuppressWarnings("unchecked") // Actually checked above
428                         InstanceIdentifier<T> iid = (InstanceIdentifier<T>) created.getKey();
429                         result.put(iid, value);
430                     }
431                 }
432             }
433         }
434         return result;
435     }
436
437     public static List<Insert> extractInsert(TransactionBuilder transaction, GenericTableSchema schema) {
438         List<Operation> operations = transaction.getOperations();
439         List<Insert> inserts = new ArrayList<>();
440         for (Operation operation : operations) {
441             if (operation instanceof Insert && operation.getTableSchema().equals(schema)) {
442                 inserts.add((Insert) operation);
443             }
444         }
445         return inserts;
446     }
447
448     /**
449      * Extract the NamedUuid from the Insert.
450      * If the Insert does not have a NamedUuid set, a random one will be
451      * generated, set, and returned.
452      *
453      * @param insert - Insert from which to extract the NamedUuid
454      * @return UUID - NamedUUID of the Insert
455      */
456     public static UUID extractNamedUuid(Insert insert) {
457         String uuidString = insert.getUuidName() != null
458                 ? insert.getUuidName() : SouthboundMapper.getRandomUUID();
459         insert.setUuidName(uuidString);
460         return new UUID(uuidString);
461     }
462
463     public static <T  extends TableSchema<T>> void stampInstanceIdentifier(TransactionBuilder transaction,
464             InstanceIdentifier<?> iid, TableSchema<T> tableSchema,
465             ColumnSchema<T, Map<String,String>> columnSchema) {
466         transaction.add(stampInstanceIdentifierMutation(transaction,iid,
467                 tableSchema,columnSchema));
468     }
469
470     public static <T  extends TableSchema<T>> Mutate<T> stampInstanceIdentifierMutation(TransactionBuilder transaction,
471             InstanceIdentifier<?> iid, TableSchema<T> tableSchema,
472             ColumnSchema<T, Map<String,String>> columnSchema) {
473         Map<String,String> externalIdsMap = ImmutableMap.of(SouthboundConstants.IID_EXTERNAL_ID_KEY,
474                 SouthboundUtil.serializeInstanceIdentifier(iid));
475         Mutate<T> mutate = op.mutate(tableSchema)
476                 .addMutation(columnSchema,
477                     Mutator.INSERT,
478                     externalIdsMap);
479         Mutation deleteIidMutation = new Mutation(columnSchema.getName(),
480                 Mutator.DELETE,
481                 OvsdbSet.fromSet(Sets.newHashSet(SouthboundConstants.IID_EXTERNAL_ID_KEY)));
482         List<Mutation> mutations = Lists.newArrayList(Sets.newHashSet(deleteIidMutation));
483         mutations.addAll(mutate.getMutations());
484         mutate.setMutations(mutations);
485         return mutate;
486     }
487
488     /**
489      * This method builds a string by concatenating the 2 character
490      * hexadecimal representation of each byte from the input byte array.
491      *
492      * For example: an input byte array containing:
493      *   bytes[0] = 'a'
494      *   bytes[1] = 'b'
495      *   bytes[2] = 'c'
496      *   bytes[3] = '-'
497      *   bytes[4] = '1'
498      *   bytes[5] = '2'
499      *   bytes[6] = '3'
500      * returns the string "6162632d313233"
501      *
502      * @param bytes
503      *            The byte array to convert to string
504      * @return The hexadecimal representation of the byte array. If bytes is
505      *         null, the string "" is returned
506      */
507     public static String bytesToHexString(byte[] bytes) {
508
509         if (bytes == null) {
510             return "";
511         }
512
513         StringBuffer buf = new StringBuffer();
514         for (int i = 0; i < bytes.length; i++) {
515             short u8byte = (short) (bytes[i] & 0xff);
516             String tmp = Integer.toHexString(u8byte);
517             if (tmp.length() == 1) {
518                 buf.append("0");
519             }
520             buf.append(tmp);
521         }
522         return buf.toString();
523     }
524 }