Improve segmented journal actor metrics
[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.spi.node.ImmutableNodes;
33 import org.opendaylight.yangtools.yang.data.tree.api.DataValidationFailedException;
34
35 /**
36  * Utility methods for dealing with datastore root {@link ContainerNode} with respect to module shards.
37  */
38 public final class RootScatterGather {
39     @NonNullByDefault
40     public record ShardContainer<T>(T shard, ContainerNode container) {
41         public ShardContainer {
42             requireNonNull(shard);
43             requireNonNull(container);
44         }
45
46         @Override
47         public String toString() {
48             return MoreObjects.toStringHelper(this).add("shard", shard).toString();
49         }
50     }
51
52     private RootScatterGather() {
53         // Hidden on purpose
54     }
55
56     /**
57      * Check whether a {@link NormalizedNode} represents a root container and return it cast to {@link ContainerNode}.
58      *
59      * @param node a normalized node
60      * @return {@code node} cast to ContainerNode
61      * @throws NullPointerException if {@code node} is null
62      * @throws IllegalArgumentException if {@code node} is not a {@link ContainerNode}
63      */
64     public static @NonNull ContainerNode castRootNode(final NormalizedNode node) {
65         final var nonnull = requireNonNull(node);
66         checkArgument(nonnull instanceof ContainerNode, "Invalid root data %s", nonnull);
67         return (ContainerNode) nonnull;
68     }
69
70     /**
71      * Reconstruct root container from a set of constituents.
72      *
73      * @param actorUtils {@link ActorUtils} reference
74      * @param readFutures Consitutent read futures
75      * @return A composite future
76      */
77     public static @NonNull FluentFuture<Optional<NormalizedNode>> gather(final ActorUtils actorUtils,
78             final Stream<FluentFuture<Optional<NormalizedNode>>> readFutures) {
79         return FluentFuture.from(Futures.transform(
80             Futures.allAsList(readFutures.collect(ImmutableList.toImmutableList())), input -> {
81                 try {
82                     return NormalizedNodeAggregator.aggregate(YangInstanceIdentifier.of(), input,
83                         actorUtils.getSchemaContext(), actorUtils.getDatastoreContext().getLogicalStoreType());
84                 } catch (DataValidationFailedException e) {
85                     throw new IllegalArgumentException("Failed to aggregate", e);
86                 }
87             }, MoreExecutors.directExecutor()));
88     }
89
90     public static <T> @NonNull Stream<ShardContainer<T>> scatterAll(final ContainerNode rootNode,
91             final Function<PathArgument, T> childToShard, final Stream<T> allShards) {
92         final var builders = allShards
93             .collect(Collectors.toUnmodifiableMap(Function.identity(), unused -> ImmutableNodes.newContainerBuilder()));
94         for (var child : rootNode.body()) {
95             final var shard = childToShard.apply(child.name());
96             verifyNotNull(builders.get(shard), "Failed to find builder for %s", shard).addChild(child);
97         }
98         return streamContainers(rootNode.name(), builders);
99     }
100
101     /**
102      * Split root container into per-shard root containers.
103      *
104      * @param <T> Shard reference type
105      * @param rootNode Root container to be split up
106      * @param childToShard Mapping function from child {@link PathArgument} to shard reference
107      * @return Stream of {@link ShardContainer}s, one for each touched shard
108      */
109     public static <T> @NonNull Stream<ShardContainer<T>> scatterTouched(final ContainerNode rootNode,
110             final Function<PathArgument, T> childToShard) {
111         final var builders = new HashMap<T, ContainerNode.Builder>();
112         for (var child : rootNode.body()) {
113             builders.computeIfAbsent(childToShard.apply(child.name()), unused -> ImmutableNodes.newContainerBuilder())
114                 .addChild(child);
115         }
116         return streamContainers(rootNode.name(), builders);
117     }
118
119     private static <T> @NonNull Stream<ShardContainer<T>> streamContainers(final NodeIdentifier rootId,
120             final Map<T, ContainerNode.Builder> builders) {
121         return builders.entrySet().stream()
122             .map(entry -> new ShardContainer<>(entry.getKey(), entry.getValue().withNodeIdentifier(rootId).build()));
123     }
124 }