summaryrefslogtreecommitdiffstats
path: root/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/NodesAndHosts.java
blob: dd9c7021b9ec551a8202f04cbd30b5c642faa177 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.provision;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Wraps a NodeList and builds a host -> children mapping for faster access
 * as that is done very frequently.
 *
 * @author baldersheim
 */
public class NodesAndHosts<NL extends NodeList> {
    private final NL nodes;
    private final Map<String, HostAndNodes> host2Nodes;

    public static <L extends NodeList> NodesAndHosts<L> create(L nodes) {
        return new NodesAndHosts<L>(nodes);
    }

    private NodesAndHosts(NL nodes) {
        this.nodes = nodes;
        host2Nodes = new HashMap<>();
        nodes.forEach(node -> {
            node.parentHostname().ifPresentOrElse(
                    parent -> host2Nodes.computeIfAbsent(parent, key -> new HostAndNodes()).add(node),
                    () -> host2Nodes.computeIfAbsent(node.hostname(), key -> new HostAndNodes()).setHost(node));
        });
    }

    /// Return the NodeList used for construction
    public NL nodes() { return nodes; }

    public NodeList childrenOf(Node host) {
        HostAndNodes hostAndNodes = host2Nodes.get(host.hostname());
        return hostAndNodes != null ? NodeList.copyOf(hostAndNodes.children) : NodeList.of();
    }

    public Node parentOf(Node node) {
        if (node.parentHostname().isEmpty()) return null;

        HostAndNodes hostAndNodes = host2Nodes.get(node.parentHostname().get());
        return hostAndNodes != null ? hostAndNodes.host : null;
    }

    private static class HostAndNodes {
        private Node host;
        private final List<Node> children;
        HostAndNodes() {
            this.host = null;
            children = new ArrayList<>();
        }
        void setHost(Node host) { this.host = host; }
        void add(Node child) { children.add(child); }
    }
}