Turn ShardContainer into a record
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / utils / RootScatterGather.java
1 /*
2  * Copyright (c) 2022 PANTHEON.tech, s.r.o. 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.controller.cluster.datastore.utils;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Verify.verifyNotNull;
12 import static java.util.Objects.requireNonNull;
13
14 import com.google.common.base.MoreObjects;
15 import com.google.common.collect.ImmutableList;
16 import com.google.common.util.concurrent.FluentFuture;
17 import com.google.common.util.concurrent.Futures;
18 import com.google.common.util.concurrent.MoreExecutors;
19 import java.util.HashMap;
20 import java.util.Map;
21 import java.util.Optional;
22 import java.util.function.Function;
23 import java.util.stream.Collectors;
24 import java.util.stream.Stream;
25 import org.eclipse.jdt.annotation.NonNull;
26 import org.eclipse.jdt.annotation.NonNullByDefault;
27 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
30 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
31 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
32 import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
33 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
34 import org.opendaylight.yangtools.yang.data.tree.api.DataValidationFailedException;
35
36 /**
37  * Utility methods for dealing with datastore root {@link ContainerNode} with respect to module shards.
38  */
39 public final class RootScatterGather {
40     @NonNullByDefault
41     public record ShardContainer<T>(T shard, ContainerNode container) {
42         public ShardContainer {
43             requireNonNull(shard);
44             requireNonNull(container);
45         }
46
47         @Override
48         public String toString() {
49             return MoreObjects.toStringHelper(this).add("shard", shard).toString();
50         }
51     }
52
53     private RootScatterGather() {
54         // Hidden on purpose
55     }
56
57     /**
58      * Check whether a {@link NormalizedNode} represents a root container and return it cast to {@link ContainerNode}.
59      *
60      * @param node a normalized node
61      * @return {@code node} cast to ContainerNode
62      * @throws NullPointerException if {@code node} is null
63      * @throws IllegalArgumentException if {@code node} is not a {@link ContainerNode}
64      */
65     public static @NonNull ContainerNode castRootNode(final NormalizedNode node) {
66         final var nonnull = requireNonNull(node);
67         checkArgument(nonnull instanceof ContainerNode, "Invalid root data %s", nonnull);
68         return (ContainerNode) nonnull;
69     }
70
71     /**
72      * Reconstruct root container from a set of constituents.
73      *
74      * @param actorUtils {@link ActorUtils} reference
75      * @param readFutures Consitutent read futures
76      * @return A composite future
77      */
78     public static @NonNull FluentFuture<Optional<NormalizedNode>> gather(final ActorUtils actorUtils,
79             final Stream<FluentFuture<Optional<NormalizedNode>>> readFutures) {
80         return FluentFuture.from(Futures.transform(
81             Futures.allAsList(readFutures.collect(ImmutableList.toImmutableList())), input -> {
82                 try {
83                     return NormalizedNodeAggregator.aggregate(YangInstanceIdentifier.of(), input,
84                         actorUtils.getSchemaContext(), actorUtils.getDatastoreContext().getLogicalStoreType());
85                 } catch (DataValidationFailedException e) {
86                     throw new IllegalArgumentException("Failed to aggregate", e);
87                 }
88             }, MoreExecutors.directExecutor()));
89     }
90
91     public static <T> @NonNull Stream<ShardContainer<T>> scatterAll(final ContainerNode rootNode,
92             final Function<PathArgument, T> childToShard, final Stream<T> allShards) {
93         final var builders = allShards
94             .collect(Collectors.toUnmodifiableMap(Function.identity(), unused -> Builders.containerBuilder()));
95         for (var child : rootNode.body()) {
96             final var shard = childToShard.apply(child.name());
97             verifyNotNull(builders.get(shard), "Failed to find builder for %s", shard).addChild(child);
98         }
99         return streamContainers(rootNode.name(), builders);
100     }
101
102     /**
103      * Split root container into per-shard root containers.
104      *
105      * @param <T> Shard reference type
106      * @param rootNode Root container to be split up
107      * @param childToShard Mapping function from child {@link PathArgument} to shard reference
108      * @return Stream of {@link ShardContainer}s, one for each touched shard
109      */
110     public static <T> @NonNull Stream<ShardContainer<T>> scatterTouched(final ContainerNode rootNode,
111             final Function<PathArgument, T> childToShard) {
112         final var builders = new HashMap<T, DataContainerNodeBuilder<NodeIdentifier, ContainerNode>>();
113         for (var child : rootNode.body()) {
114             builders.computeIfAbsent(childToShard.apply(child.name()), unused -> Builders.containerBuilder())
115                 .addChild(child);
116         }
117         return streamContainers(rootNode.name(), builders);
118     }
119
120     private static <T> @NonNull Stream<ShardContainer<T>> streamContainers(final NodeIdentifier rootId,
121             final Map<T, DataContainerNodeBuilder<NodeIdentifier, ContainerNode>> builders) {
122         return builders.entrySet().stream()
123             .map(entry -> new ShardContainer<>(entry.getKey(), entry.getValue().withNodeIdentifier(rootId).build()));
124     }
125 }