aboutsummaryrefslogtreecommitdiffstats
path: root/vdslib/src/main/java/com/yahoo/vdslib/state/NodeState.java
blob: 1326a3fa1deb1ee2a7136d5c59a7ea60fb404e96 (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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vdslib.state;

import com.yahoo.text.StringUtilities;

import java.text.ParseException;
import java.util.Locale;
import java.util.StringTokenizer;

/**
 * The state of a single node in the cluster state
 * TODO: The config aspects of this should move to ConfiguredNode
 * TODO: The type should be removed, as it is part of the owner.
 * TODO: Monitoring aspects should move to NodeInfo
 */
public class NodeState implements Cloneable {

    public static final String ORCHESTRATOR_RESERVED_DESCRIPTION = "Orchestrator";

    private final NodeType type;
    private State state;
    private String description = "";
    private float capacity = 1.0f;
    private float initProgress = 1.0f;
    private int minUsedBits = 16;
    private long startTimestamp = 0;

    public static float getListingBucketsInitProgressLimit() { return 0.01f; }

    public NodeState(NodeType type, State state) {
        this.type = type;
        this.state = state;
    }

    public NodeState clone() {
        try{
            return (NodeState) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new RuntimeException("Does not happen");
        }
    }

    /**
     * A state can not be forced to be in a state above its reported state.
     * For instance, a node being down cannot be forced to up, but a node being down can be forced to maintenance.
     */
    public boolean above(NodeState other) {
        return (state.ordinal() > other.state.ordinal());
    }

    public boolean equals(Object o) {
        if (!(o instanceof NodeState ns)) { return false; }
        // Note that 'description' is not considered as it carries semantics.
        if (state != ns.state
            || Math.abs(capacity - ns.capacity)         > 0.0000000001
            || Math.abs(initProgress - ns.initProgress) > 0.0000000001
            || startTimestamp != ns.startTimestamp
            || minUsedBits != ns.minUsedBits)
        {
            return false;
        }
        return true;
    }
    public int hashCode() {
        return state.hashCode() ^ Double.valueOf(capacity).hashCode();
    }

    /**
     * States are similar if the cluster state doesn't need to be updated due to a change.
     * Note that min dist bits may need to alter cluster state, but as we don't know at this point, we ignore it.
     * Cluster state will check for that.
     */
    public boolean similarTo(Object o) {
        if (!(o instanceof NodeState)) {
            return false;
        }
        return similarToImpl((NodeState)o, true);
    }

    public boolean similarToIgnoringInitProgress(final NodeState other) {
        return similarToImpl(other, false);
    }

    private boolean similarToImpl(final NodeState other, boolean considerInitProgress) {
        if (state != other.state) return false;
        if (Math.abs(capacity - other.capacity) > 0.0000000001) return false;
        if (startTimestamp != other.startTimestamp) return false;

        // Init progress on different sides of the init progress limit boundary is not similar.
        if (considerInitProgress
            && type.equals(NodeType.STORAGE)
            && (initProgress < getListingBucketsInitProgressLimit()
                ^ other.initProgress < getListingBucketsInitProgressLimit()))
        {
            return false;
        }
        return true;
    }

    public Diff getDiff(NodeState other) {
        Diff diff = new Diff();
        if (!state.equals(other.state)) {
            diff.add(new Diff.Entry("", state, other.state).bold());
        }
        if (Math.abs(capacity - other.capacity) > 0.000000001) {
            diff.add(new Diff.Entry("capacity", capacity, other.capacity));
        }
        if (minUsedBits != other.minUsedBits) {
            diff.add(new Diff.Entry("minUsedBits", minUsedBits, other.minUsedBits));
        }
        if (Math.abs(initProgress - other.initProgress) > 0.000000001 && state.equals(State.INITIALIZING) && other.state.equals(State.INITIALIZING)) {
            diff.add(new Diff.Entry("initProgress", initProgress, other.initProgress));
        }
        if (startTimestamp != other.startTimestamp) {
            diff.add(new Diff.Entry("startTimestamp", startTimestamp, other.startTimestamp));
        }
        if (!description.equals(other.description)) {
            diff.add(new Diff.Entry("description", description, other.description));
        }
        return diff;
    }

    public String getTextualDifference(NodeState other) {
        return getDiff(other).toString();
    }

    /** Capacity is set by deserializing a node state. This seems odd, as it is config */
    public NodeState setCapacity(float c) { this.capacity = c; return this; }

    public NodeState setInitProgress(float p) { this.initProgress = p; return this; }
    public NodeState setDescription(String desc) { this.description = desc; return this; }
    public NodeState setMinUsedBits(int u) { this.minUsedBits = u; return this; }
    public NodeState setState(State state) { this.state = state; return this; }
    public NodeState setStartTimestamp(long ts) { this.startTimestamp = ts; return this; }

    public double getCapacity() { return this.capacity; }
    public double getInitProgress() { return this.initProgress; }
    public boolean hasDescription() { return (description.length() > 0); }
    public String getDescription() { return description; }
    public State getState() { return this.state; }
    public int getMinUsedBits() { return minUsedBits; }
    public long getStartTimestamp() { return startTimestamp; }

    public String toString() { return toString(false); }

    public String toString(boolean compact) {
        StringBuilder sb = new StringBuilder();
        if (compact) {
            sb.append(state.serialize().toUpperCase());
        } else {
            sb.append(state);
        }
        if (Math.abs(capacity - 1.0) > 0.000000001) {
            sb.append(compact ? ", c " : ", capacity ").append(compact ? String.format(Locale.ENGLISH, "%.3g", capacity) : capacity);
        }
        if (state.equals(State.INITIALIZING)) {
            sb.append(compact ? ", i " : ", init progress ").append(compact ? String.format(Locale.ENGLISH, "%.3g", initProgress) : initProgress);
            if (type.equals(NodeType.STORAGE)) {
                if (initProgress < getListingBucketsInitProgressLimit()) {
                    sb.append(compact ? " (ls)" : " (listing files)");
                } else {
                    sb.append(compact ? " (read)" : " (reading file headers)");
                }
            }
        }
        if (startTimestamp > 0) {
            sb.append(compact ? ", t " : ", start timestamp ").append(startTimestamp);
        }
        if (minUsedBits != 16) {
            sb.append(compact ? ", b " : ", minimum used bits ").append(minUsedBits);
        }
        if (description.length() > 0) {
            sb.append(": ").append(description);
        }
        return sb.toString();
    }

    public String serialize() { return serialize(-1, false); }
    public String serialize(boolean verbose) { return serialize(-1, verbose); }
    public String serialize(int nodeIdx, boolean verbose) {
        boolean empty = true;
        StringBuilder sb = new StringBuilder();
        String prefix = (nodeIdx == -1 ? "" : "." + nodeIdx + ".");
        if (state != State.UP){
            empty = false;
            sb.append(prefix).append("s:").append(state.serialize());
        }
        if (Math.abs(capacity - 1.0) > 0.000000001) {
            if (empty) { empty = false; } else { sb.append(' '); }
            sb.append(prefix).append("c:").append(capacity);
        }
        if (state == State.INITIALIZING) {
            sb.append(' ');
            sb.append(prefix).append("i:").append(initProgress);
        }
        if (startTimestamp != 0) {
            if (empty) { empty = false; } else { sb.append(' '); }
            sb.append(prefix).append("t:").append(startTimestamp);
        }
        if (nodeIdx == -1 && minUsedBits != 16) {
            if (empty) { empty = false; } else { sb.append(' '); }
            sb.append(prefix).append("b:").append(minUsedBits);
        }

        if ((verbose || nodeIdx == -1) && description.length() > 0) {
            if (!empty) { sb.append(' '); }
            sb.append(prefix).append("m:").append(StringUtilities.escape(description, ' '));
        }
        return sb.toString();
    }

    /** Creates an instance from the serialized form produced by serialize */
    public static NodeState deserialize(NodeType type, String serialized) throws ParseException {
        NodeState newState = new NodeState(type, State.UP);
        StringTokenizer st = new StringTokenizer(serialized, " \t\r\f\n", false);
        while (st.hasMoreTokens()) {
            String token = st.nextToken();
            int index = token.indexOf(':');
            if (index < 0) {
                throw new ParseException("Token " + token + " does not contain ':': " + serialized, 0);
            }
            String key = token.substring(0, index);
            String value = token.substring(index + 1);
            if (key.length() > 0) switch (key.charAt(0)) {
            case 's':
                if (key.length() > 1) break;
                newState.setState(State.get(value));
                continue;
            case 'b':
                if (key.length() > 1) break;
                newState.setMinUsedBits(Integer.parseInt(value));
                continue;
            case 'c':
                if (key.length() > 1) break;
                if (type != null && !type.equals(NodeType.STORAGE)) break;
                try{
                    newState.setCapacity(Float.parseFloat(value));
                } catch (Exception e) {
                    throw new ParseException("Illegal capacity '" + value + "'. Capacity must be a positive floating point number", 0);
                }
                continue;
            case 'i':
                if (key.length() > 1) break;
                try{
                    newState.setInitProgress(Float.parseFloat(value));
                } catch (Exception e) {
                    throw new ParseException("Illegal init progress '" + value + "'. Init progress must be a floating point number from 0.0 to 1.0", 0);
                }
                continue;
            case 't':
                if (key.length() > 1) break;
                try{
                    newState.setStartTimestamp(Long.parseLong(value));
                    if (newState.getStartTimestamp() < 0) throw new Exception();
                } catch (Exception e) {
                    throw new ParseException("Illegal start timestamp " + value + ". Start timestamp must be 0 or a positive long.", 0);
                }
                continue;
            case 'm':
                if (key.length() > 1) break;
                newState.setDescription(StringUtilities.unescape(value));
                continue;
            case 'd':
                if (type != null && !type.equals(NodeType.STORAGE)) break;
                int size = 0;
                if (key.length() == 1) {
                    try {
                        size = Integer.parseInt(value);
                    } catch (Exception e) {
                        throw new ParseException("Invalid disk count '" + value + "'. Need a positive integer value", 0);
                    }
                    continue;
                }
                if (key.charAt(1) != '.') break;
                int diskIndex;
                int endp = key.indexOf('.', 2);
                String indexStr = (endp < 0 ? key.substring(2) : key.substring(2, endp));
                try{
                    diskIndex = Integer.parseInt(indexStr);
                } catch (Exception e) {
                    throw new ParseException("Invalid disk index '" + indexStr + "'. need a positive integer value", 0);
                }
                if (diskIndex >= size) {
                    throw new ParseException("Cannot index disk " + diskIndex + " of " + size, 0);
                }
                continue;
            default:
                break;
            }
            // Ignore unknown tokens
        }
        return newState;
    }

    public void verifyValidInSystemState(NodeType type) {
        if (!state.validCurrentNodeState(type)) {
            throw new IllegalArgumentException("State " + state + " cannot fit in system state for node of type: " + type);
        }
        if (type.equals(NodeType.DISTRIBUTOR) && Math.abs(capacity - 1.0) > 0.000000001) {
            throw new IllegalArgumentException("Capacity should not be set for a distributor node");
        }
    }

}