summaryrefslogtreecommitdiffstats
path: root/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/SystemStateBroadcaster.java
blob: a40a45fd48aec81115085fd26ee2cf4636041d0c (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
// Copyright 2017 Yahoo Holdings. 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.log.LogLevel;
import com.yahoo.vdslib.state.*;
import com.yahoo.vespa.clustercontroller.core.database.DatabaseHandler;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.logging.Logger;
import java.util.stream.Collectors;

public class SystemStateBroadcaster {

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

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

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

    private final SetClusterStateWaiter setClusterStateWaiter = new SetClusterStateWaiter();

    public SystemStateBroadcaster(Timer timer, Object monitor) {
        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;
    }

    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);
        log.log((nodeOk && !alreadySeen) ? LogLevel.WARNING : LogLevel.DEBUG, message);
        if (!alreadySeen) {
            lastErrorReported.put(info.getNode(), time);
        }
    }

    public boolean processResponses() {
        boolean anyResponsesFound = false;
        synchronized(monitor) {
            for (SetClusterStateRequest req : setClusterStateReplies) {
                anyResponsesFound = true;

                NodeInfo info = req.getNodeInfo();
                boolean nodeOk = info.getReportedState().getState().oneOf("uir");
                int version = req.getClusterStateVersion();

                if (req.getReply().isError()) {
                    info.setSystemStateVersionAcknowledged(version, false);
                    if (req.getReply().getReturnCode() != Communicator.TRANSIENT_ERROR) {
                        if (info.getNewestSystemStateVersionSent() == version) {
                            reportNodeError(nodeOk, info,
                                    "Got error response " + req.getReply().getReturnCode() + ": " + req.getReply().getReturnMessage()
                                            + " from " + info + " setsystemstate request.");
                        }
                    }
                } else {
                    info.setSystemStateVersionAcknowledged(version, true);
                    log.log(LogLevel.DEBUG, "Node " + info + " acked system state version " + version + ".");
                    lastErrorReported.remove(info.getNode());
                }
            }
            setClusterStateReplies.clear();
        }
        return anyResponsesFound;
    }

    private boolean nodeNeedsClusterState(NodeInfo node) {
        if (node.getSystemStateVersionAcknowledged() == clusterStateBundle.getVersion()) {
            return false; // No point in sending if node already has updated system state
        }
        if (node.getRpcAddress() == null || node.isRpcAddressOutdated()) {
            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 List<NodeInfo> resolveStateVersionSendSet(DatabaseHandler.Context dbContext) {
        return dbContext.getCluster().getNodeInfo().stream()
                .filter(this::nodeNeedsClusterState)
                .filter(node -> !newestStateAlreadySentToNode(node))
                .collect(Collectors.toList());
    }

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

    /**
     * Checks if all distributor nodes have ACKed 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.Context dbContext,
                                                     FleetController fleetController) throws InterruptedException {
        if ((clusterStateBundle == null) || (lastClusterStateInSync == clusterStateBundle.getVersion())) {
            return; // Nothing to do for the current state
        }
        final int currentStateVersion = clusterStateBundle.getVersion();
        boolean anyOutdatedDistributorNodes = dbContext.getCluster().getNodeInfo().stream()
                .filter(NodeInfo::isDistributor)
                .anyMatch(this::nodeNeedsClusterState);

        if (!anyOutdatedDistributorNodes && (currentStateVersion > lastClusterStateInSync)) {
            log.log(LogLevel.DEBUG, "All distributors have newest clusterstate, updating start timestamps in zookeeper and clearing them from cluster state");
            lastClusterStateInSync = currentStateVersion;
            fleetController.handleAllDistributorsInSync(database, dbContext);
        }
    }

    public boolean broadcastNewState(DatabaseHandler.Context dbContext, Communicator communicator) {
        if (clusterStateBundle == null) {
            return false;
        }

        ClusterState baselineState = clusterStateBundle.getBaselineClusterState();

        if (!baselineState.isOfficial()) {
            log.log(LogLevel.INFO, String.format("Publishing cluster state version %d", baselineState.getVersion()));
            baselineState.setOfficial(true); // FIXME this violates state bundle immutability
        }

        List<NodeInfo> recipients = resolveStateVersionSendSet(dbContext);
        for (NodeInfo node : recipients) {
            if (nodeNeedsToObserveStartupTimestamps(node)) {
                // TODO this is the same for all nodes, compute only once
                ClusterStateBundle modifiedBundle = clusterStateBundle.cloneWithMapper(state -> buildModifiedClusterState(state, dbContext));
                log.log(LogLevel.DEBUG, "Sending modified cluster state version " + baselineState.getVersion()
                        + " to node " + node + ": " + modifiedBundle);
                communicator.setSystemState(modifiedBundle, node, setClusterStateWaiter);
            } else {
                log.log(LogLevel.DEBUG, "Sending system state version " + baselineState.getVersion() + " to node " + node
                        + ". (went down time " + node.getWentDownWithStartTime() + ", node start time " + node.getStartTimestamp() + ")");
                communicator.setSystemState(clusterStateBundle, node, setClusterStateWaiter);
            }
        }

        return !recipients.isEmpty();
    }

    public int lastClusterStateVersionInSync() { return lastClusterStateInSync; }

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

    private static ClusterState buildModifiedClusterState(ClusterState sourceState, DatabaseHandler.Context dbContext) {
        ClusterState newState = sourceState.clone();
        for (NodeInfo n : dbContext.getCluster().getNodeInfo()) {
            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) {
            // TODO
        }
    }

}