aboutsummaryrefslogtreecommitdiffstats
path: root/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/SystemStateBroadcaster.java
blob: c74a846fe3003ce66db3e61c992b45b0bf30d079 (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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.clustercontroller.core;

import com.yahoo.jrt.ErrorCode;
import com.yahoo.vdslib.state.ClusterState;
import com.yahoo.vdslib.state.Node;
import com.yahoo.vdslib.state.NodeState;
import com.yahoo.vdslib.state.State;
import com.yahoo.vespa.clustercontroller.core.database.DatabaseHandler;

import java.util.logging.Level;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.logging.Logger;

public class SystemStateBroadcaster {

    private static final Logger log = Logger.getLogger(SystemStateBroadcaster.class.getName());

    private final FleetControllerContext context;
    private final Timer timer;
    private final Object monitor;
    private ClusterStateBundle clusterStateBundle;
    private final List<SetClusterStateRequest> setClusterStateReplies = new LinkedList<>();
    private final List<ActivateClusterStateVersionRequest> activateClusterStateVersionReplies = new LinkedList<>();

    private final static long minTimeBetweenNodeErrorLogging = 10 * 60 * 1000;
    private final Map<Node, Long> lastErrorReported = new TreeMap<>();

    private int lastOfficialStateVersion = -1;
    private int lastStateVersionBundleAcked = 0;
    private int lastClusterStateVersionConverged = 0;
    private ClusterStateBundle lastClusterStateBundleConverged;

    private final SetClusterStateWaiter setClusterStateWaiter = new SetClusterStateWaiter();
    private final ActivateClusterStateVersionWaiter activateClusterStateVersionWaiter = new ActivateClusterStateVersionWaiter();

    public SystemStateBroadcaster(FleetControllerContext context, Timer timer, Object monitor) {
        this.context = context;
        this.timer = timer;
        this.monitor = monitor;
    }

    public void handleNewClusterStates(ClusterStateBundle state) {
        clusterStateBundle = state;
    }

    public ClusterState getClusterState() {
        return clusterStateBundle.getBaselineClusterState();
    }

    public boolean hasBroadcastedClusterStateBundle() {
        return clusterStateBundle != null;
    }

    public void resetBroadcastedClusterStateBundle() {
        clusterStateBundle = null;
    }

    public ClusterStateBundle getClusterStateBundle() {
        return clusterStateBundle;
    }

    public ClusterStateBundle getLastClusterStateBundleConverged() {
        return lastClusterStateBundleConverged;
    }

    private void reportNodeError(boolean nodeOk, NodeInfo info, String message) {
        long time = timer.getCurrentTimeInMillis();
        Long lastReported = lastErrorReported.get(info.getNode());
        boolean alreadySeen = (lastReported != null && time - lastReported < minTimeBetweenNodeErrorLogging);
        context.log(log, nodeOk && !alreadySeen ? Level.WARNING : Level.FINE, message);
        if (!alreadySeen) {
            lastErrorReported.put(info.getNode(), time);
        }
    }

    public boolean processResponses() {
        boolean anyResponsesFound = false;
        synchronized(monitor) {
            anyResponsesFound = !setClusterStateReplies.isEmpty() || !activateClusterStateVersionReplies.isEmpty();
            processSetClusterStateResponses();
            processActivateClusterStateVersionResponses();
        }
        return anyResponsesFound;
    }

    private void processActivateClusterStateVersionResponses() {
        for (var req : activateClusterStateVersionReplies) {
            NodeInfo info = req.getNodeInfo();
            int version = req.getClusterStateVersion();
            boolean success = true;
            var reply = req.getReply();
            if (reply.isError()) {
                // NO_SUCH_METHOD implies node is on a version that does not understand explicit activations
                // and it has already merrily started using the state version. Treat as if it had been ACKed.
                if (reply.getReturnCode() != ErrorCode.NO_SUCH_METHOD) {
                    context.log(log,
                                Level.FINE,
                                () -> String.format("Activation NACK for node %s with version %d, message %s",
                                                    info, version, reply.getReturnMessage()));
                    success = false;
                } else {
                    context.log(log,
                                Level.FINE,
                                () -> String.format("Node %s did not understand state activation RPC; " +
                                                    "implicitly treating state %d as activated on node",
                                                    info, version));
                }
            } else if (reply.getActualVersion() != version) {
                boolean nodeOk = nodeReportsSelfAsAvailable(info);
                // Avoid spamming the logs since this will happen on all resends until (presumably) the controller
                // loses election status.
                // TODO this should trigger a loss of current controller's leadership!
                reportNodeError(nodeOk, info, String.format("Activation of version %d did not take effect, node %s " +
                                "reports it has an actual pending version of %d. Racing with another controller?",
                                version, info, reply.getActualVersion()));
                success = false;
            } else {
                context.log(log,
                            Level.FINE,
                            () -> String.format("Node %s reports successful activation of state version %d",
                                                info, version));
            }
            info.setSystemStateVersionActivationAcked(version, success);
            // TODO we currently don't invoke reportNodeError here.. We assume that node errors will be reported
            // as part of processSetClusterStateResponses anyway, but can add it here as well if deemed necessary.
        }
        activateClusterStateVersionReplies.clear();
    }

    private static boolean nodeReportsSelfAsAvailable(NodeInfo info) {
        return info.getReportedState().getState().oneOf("uir");
    }

    private void processSetClusterStateResponses() {
        for (SetClusterStateRequest req : setClusterStateReplies) {
            NodeInfo info = req.getNodeInfo();
            int version = req.getClusterStateVersion();

            if (req.getReply().isError()) {
                info.setClusterStateBundleVersionAcknowledged(version, false);
                if (req.getReply().getReturnCode() != Communicator.TRANSIENT_ERROR) {
                    if (info.getNewestSystemStateVersionSent() == version) {
                        boolean nodeOk = nodeReportsSelfAsAvailable(info);
                        reportNodeError(nodeOk, info,
                                String.format("Got error response %d: %s from %s setdistributionstates request.",
                                        req.getReply().getReturnCode(), req.getReply().getReturnMessage(), info));
                    }
                }
            } else {
                info.setClusterStateBundleVersionAcknowledged(version, true);
                context.log(log, Level.FINE, () -> String.format("Node %s ACKed system state version %d.", info, version));
                lastErrorReported.remove(info.getNode());
            }
        }
        setClusterStateReplies.clear();
    }

    private static boolean nodeIsReachable(NodeInfo node) {
        if (node.getRpcAddress() == null || node.isNotInSlobrok()) {
            return false; // Can't set state on nodes we don't know where are
        }
        if (node.getReportedState().getState() == State.MAINTENANCE ||
            node.getReportedState().getState() == State.DOWN ||
            node.getReportedState().getState() == State.STOPPING)
        {
            return false; // No point in sending system state to nodes that can't receive messages or don't want them
        }
        return true;
    }

    private boolean nodeNeedsClusterStateBundle(NodeInfo node) {
        if (node.getClusterStateVersionBundleAcknowledged() == clusterStateBundle.getVersion()) {
            return false; // No point in sending if node already has updated system state
        }
        return nodeIsReachable(node);
    }

    private boolean nodeNeedsClusterStateActivation(NodeInfo node) {
        if (node.getClusterStateVersionActivationAcked() == clusterStateBundle.getVersion()) {
            return false; // No point in sending if node already has activated cluster state version
        }
        return nodeIsReachable(node);
    }

    private List<NodeInfo> resolveStateVersionSendSet(DatabaseHandler.DatabaseContext dbContext) {
        return dbContext.getCluster().getNodeInfos().stream()
                        .filter(this::nodeNeedsClusterStateBundle)
                        .filter(node -> !newestStateBundleAlreadySentToNode(node))
                        .toList();
    }

    // Precondition: no nodes in the cluster need to receive the current cluster state version bundle
    private List<NodeInfo> resolveStateActivationSendSet(DatabaseHandler.DatabaseContext dbContext) {
        return dbContext.getCluster().getNodeInfos().stream()
                        .filter(this::nodeNeedsClusterStateActivation)
                        .filter(node -> !newestStateActivationAlreadySentToNode(node))
                        .toList();
    }

    private boolean newestStateBundleAlreadySentToNode(NodeInfo node) {
        return (node.getNewestSystemStateVersionSent() == clusterStateBundle.getVersion());
    }

    private boolean newestStateActivationAlreadySentToNode(NodeInfo node) {
        return (node.getClusterStateVersionActivationSent() == clusterStateBundle.getVersion());
    }

    /**
     * Checks if all distributor nodes have ACKed (and activated) the most recent cluster state.
     * Iff this is the case, triggers handleAllDistributorsInSync() on the provided FleetController
     * object and updates the broadcaster's last known in-sync cluster state version.
     */
    void checkIfClusterStateIsAckedByAllDistributors(DatabaseHandler database,
                                                     DatabaseHandler.DatabaseContext dbContext,
                                                     FleetController fleetController) throws InterruptedException {
        if ((clusterStateBundle == null) || currentClusterStateIsConverged()) {
            return; // Nothing to do for the current state
        }
        final int currentStateVersion = clusterStateBundle.getVersion();
        boolean anyDistributorsNeedStateBundle = dbContext.getCluster().getNodeInfos().stream()
                                                          .filter(NodeInfo::isDistributor)
                                                          .anyMatch(this::nodeNeedsClusterStateBundle);

        if (!anyDistributorsNeedStateBundle && (currentStateVersion > lastStateVersionBundleAcked)) {
            markCurrentClusterStateBundleAsReceivedByAllDistributors();
            if (clusterStateBundle.deferredActivation()) {
                context.log(log,
                            Level.FINE,
                            () -> String.format("All distributors have ACKed cluster state " +
                                                "version %d, sending activation", currentStateVersion));
            } else {
                markCurrentClusterStateAsConverged(database, dbContext, fleetController);
            }
            return; // Either converged (no two-phase) or activations must be sent before we can continue.
        }

        if (anyDistributorsNeedStateBundle || !clusterStateBundle.deferredActivation()) {
            return;
        }

        boolean anyDistributorsNeedActivation = dbContext.getCluster().getNodeInfos().stream()
                                                         .filter(NodeInfo::isDistributor)
                                                         .anyMatch(this::nodeNeedsClusterStateActivation);

        if (!anyDistributorsNeedActivation && (currentStateVersion > lastClusterStateVersionConverged)) {
            markCurrentClusterStateAsConverged(database, dbContext, fleetController);
        } else {
            context.log(log,
                        Level.FINE,
                        () -> String.format("distributors still need activation in state %d (last converged: %d)",
                                            currentStateVersion, lastClusterStateVersionConverged));
        }
    }

    private void markCurrentClusterStateBundleAsReceivedByAllDistributors() {
        lastStateVersionBundleAcked = clusterStateBundle.getVersion();
    }

    private void markCurrentClusterStateAsConverged(DatabaseHandler database, DatabaseHandler.DatabaseContext dbContext, FleetController fleetController) {
        context.log(log, Level.FINE, "All distributors have newest clusterstate, updating start timestamps in zookeeper and clearing them from cluster state");
        lastClusterStateVersionConverged = clusterStateBundle.getVersion();
        lastClusterStateBundleConverged = clusterStateBundle;
        fleetController.handleAllDistributorsInSync(database, dbContext);
    }

    private boolean currentClusterStateIsConverged() {
        return lastClusterStateVersionConverged == clusterStateBundle.getVersion();
    }

    private boolean currentBundleVersionIsTaggedOfficial() {
        return clusterStateBundle.getVersion() == lastOfficialStateVersion;
    }

    private void tagCurrentBundleVersionAsOfficial() {
        lastOfficialStateVersion = clusterStateBundle.getVersion();
    }

    public boolean broadcastNewStateBundleIfRequired(DatabaseHandler.DatabaseContext dbContext, Communicator communicator,
                                                     int lastClusterStateVersionWrittenToZooKeeper) {
        if (clusterStateBundle == null || clusterStateBundle.getVersion() == 0) {
            return false;
        }
        if (clusterStateBundle.getVersion() != lastClusterStateVersionWrittenToZooKeeper) {
            return false;
        }

        int baselineStateVersion = clusterStateBundle.getBaselineClusterState().getVersion();

        if (!currentBundleVersionIsTaggedOfficial()) {
            context.log(log, Level.INFO, "Publishing cluster state version " + baselineStateVersion);
            tagCurrentBundleVersionAsOfficial();
        }

        List<NodeInfo> recipients = resolveStateVersionSendSet(dbContext);
        ClusterStateBundle modifiedBundle = clusterStateBundle.cloneWithMapper(state -> buildModifiedClusterState(state, dbContext));
        for (NodeInfo node : recipients) {
            if (nodeNeedsToObserveStartupTimestamps(node)) {
                context.log(log,
                            Level.FINE,
                            () -> "Sending modified cluster state version " + baselineStateVersion +
                                  " to node " + node + ": " + modifiedBundle);
                communicator.setSystemState(modifiedBundle, node, setClusterStateWaiter);
            } else {
                context.log(log,
                            Level.FINE,
                            () -> "Sending system state version " + baselineStateVersion +
                                  " to node " + node + ". (went down time " + node.getWentDownWithStartTime() +
                                  ", node start time " + node.getStartTimestamp() + ")");
                communicator.setSystemState(clusterStateBundle, node, setClusterStateWaiter);
            }
        }

        return !recipients.isEmpty();
    }

    public boolean broadcastStateActivationsIfRequired(DatabaseHandler.DatabaseContext dbContext, Communicator communicator) {
        if (clusterStateBundle == null || clusterStateBundle.getVersion() == 0 || !currentBundleVersionIsTaggedOfficial()) {
            return false;
        }

        if (!clusterStateBundle.deferredActivation() || !allDistributorsHaveAckedSentClusterStateBundle()) {
            return false;
        }

        var recipients = resolveStateActivationSendSet(dbContext);
        for (NodeInfo node : recipients) {
            context.log(log,
                        Level.FINE,
                        () -> "Sending cluster state activation to node " + node + " for version " +
                              clusterStateBundle.getVersion());
            communicator.activateClusterStateVersion(clusterStateBundle.getVersion(), node, activateClusterStateVersionWaiter);
        }

        return !recipients.isEmpty();
    }

    private boolean allDistributorsHaveAckedSentClusterStateBundle() {
        return (lastStateVersionBundleAcked == clusterStateBundle.getVersion());
    }

    public int lastClusterStateVersionInSync() { return lastClusterStateVersionConverged; }

    private static boolean nodeNeedsToObserveStartupTimestamps(NodeInfo node) {
        return node.getStartTimestamp() != 0 && node.getWentDownWithStartTime() == node.getStartTimestamp();
    }

    private static ClusterState buildModifiedClusterState(ClusterState sourceState, DatabaseHandler.DatabaseContext dbContext) {
        ClusterState newState = sourceState.clone();
        for (NodeInfo n : dbContext.getCluster().getNodeInfos()) {
            NodeState ns = newState.getNodeState(n.getNode());
            if (!n.isDistributor() && ns.getStartTimestamp() == 0) {
                ns.setStartTimestamp(n.getStartTimestamp());
                newState.setNodeState(n.getNode(), ns);
            }
        }
        return newState;
    }

    private class SetClusterStateWaiter implements Communicator.Waiter<SetClusterStateRequest> {
        @Override
        public void done(SetClusterStateRequest reply) {
            synchronized (monitor) {
                setClusterStateReplies.add(reply);
            }
        }
    }

    private class ActivateClusterStateVersionWaiter implements Communicator.Waiter<ActivateClusterStateVersionRequest> {
        @Override
        public void done(ActivateClusterStateVersionRequest reply) {
            synchronized (monitor) {
                activateClusterStateVersionReplies.add(reply);
            }
        }
    }

}