aboutsummaryrefslogtreecommitdiffstats
path: root/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/provisioning/NodeIndices.java
blob: 49eaedaa4ec95b64634a63058ffd4871fa069a36 (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 Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.provision.provisioning;

import com.yahoo.config.provision.ClusterSpec;
import com.yahoo.vespa.hosted.provision.NodeList;

import java.util.List;

/**
 * Tracks indices of a node cluster, and proposes the index of the next allocation.
 *
 * @author jonmv
 */
class NodeIndices {

    private final List<Integer> used;

    private int last;
    private int probe;

    /** Pass the list of current indices in the cluster. */
    NodeIndices(ClusterSpec.Id cluster, NodeList allNodes) {
        this(allNodes.cluster(cluster).mapToList(node -> node.allocation().get().membership().index()));
    }

    NodeIndices(List<Integer> used) {
        this.used = used;
        this.last = -1;
        this.probe = last;
    }

    /** Returns the next available index and commits to using it. Throws if a probe is ongoing. */
    int next() {
        if (probe != last)
            throw new IllegalStateException("Must commit ongoing probe before calling 'next'");

        probeNext();
        commitProbe();
        return last;
    }

    /** Returns the next available index, without committing to using it. Yields increasing indices when called multiple times. */
    int probeNext() {
        while (used.contains(++probe));
        return probe;
    }

    /** Commits to using all indices returned by an ongoing probe. */
    void commitProbe() {
        last = probe;
    }

    /** Resets any probed state to what's currently committed. */
    void resetProbe() {
        probe = last;
    }

}