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