summaryrefslogtreecommitdiffstats
path: root/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/NodeAdminStateUpdaterImpl.java
blob: b91fc1b4df9789b6f0a0e85430112118ee561600 (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
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.admin.nodeadmin;

import com.yahoo.concurrent.ThreadFactoryFactory;
import com.yahoo.concurrent.classlock.ClassLock;
import com.yahoo.concurrent.classlock.ClassLocking;
import com.yahoo.concurrent.classlock.LockInterruptException;
import com.yahoo.log.LogLevel;
import com.yahoo.vespa.hosted.node.admin.configserver.noderepository.NodeSpec;
import com.yahoo.vespa.hosted.node.admin.configserver.noderepository.NodeRepository;
import com.yahoo.vespa.hosted.node.admin.configserver.orchestrator.Orchestrator;
import com.yahoo.vespa.hosted.node.admin.maintenance.StorageMaintainer;
import com.yahoo.vespa.hosted.node.admin.configserver.noderepository.NodeAttributes;
import com.yahoo.vespa.hosted.node.admin.configserver.orchestrator.OrchestratorException;
import com.yahoo.vespa.hosted.node.admin.provider.NodeAdminStateUpdater;
import com.yahoo.vespa.hosted.node.admin.configserver.HttpException;
import com.yahoo.vespa.hosted.provision.Node;

import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;

import static com.yahoo.vespa.hosted.node.admin.provider.NodeAdminStateUpdater.State.RESUMED;
import static com.yahoo.vespa.hosted.node.admin.provider.NodeAdminStateUpdater.State.SUSPENDED_NODE_ADMIN;
import static com.yahoo.vespa.hosted.node.admin.provider.NodeAdminStateUpdater.State.TRANSITIONING;

/**
 * Pulls information from node repository and forwards containers to run to node admin.
 *
 * @author dybis, stiankri
 */
public class NodeAdminStateUpdaterImpl implements NodeAdminStateUpdater {
    static final Duration FREEZE_CONVERGENCE_TIMEOUT = Duration.ofMinutes(5);

    private final AtomicBoolean terminated = new AtomicBoolean(false);
    private State currentState = SUSPENDED_NODE_ADMIN;
    private State wantedState = RESUMED;
    private boolean workToDoNow = true;

    private final Object monitor = new Object();

    private final Logger log = Logger.getLogger(NodeAdminStateUpdater.class.getName());
    private final ScheduledExecutorService specVerifierScheduler =
            Executors.newScheduledThreadPool(1, ThreadFactoryFactory.getDaemonThreadFactory("specverifier"));
    private final Thread loopThread;

    private final NodeRepository nodeRepository;
    private final Orchestrator orchestrator;
    private final NodeAdmin nodeAdmin;
    private final Clock clock;
    private final String dockerHostHostName;
    private final Duration nodeAdminConvergeStateInterval;

    private final Optional<ClassLocking> classLocking;
    private Optional<ClassLock> classLock = Optional.empty();
    private Instant lastTick;

    public NodeAdminStateUpdaterImpl(
            NodeRepository nodeRepository,
            Orchestrator orchestrator,
            StorageMaintainer storageMaintainer,
            NodeAdmin nodeAdmin,
            String dockerHostHostName,
            Clock clock,
            Duration nodeAdminConvergeStateInterval,
            Optional<ClassLocking> classLocking) {
        log.info(objectToString() + ": Creating object");
        this.nodeRepository = nodeRepository;
        this.orchestrator = orchestrator;
        this.nodeAdmin = nodeAdmin;
        this.dockerHostHostName = dockerHostHostName;
        this.clock = clock;
        this.nodeAdminConvergeStateInterval = nodeAdminConvergeStateInterval;
        this.classLocking = classLocking;
        this.lastTick = clock.instant();

        this.loopThread = new Thread(() -> {
            if (classLocking.isPresent()) {
                log.info(objectToString() + ": Acquiring lock");
                try {
                    classLock = Optional.of(classLocking.get().lockWhile(NodeAdminStateUpdater.class, () -> !terminated.get()));
                } catch (LockInterruptException e) {
                    classLock = Optional.empty();
                    return;
                }
            }

            log.info(objectToString() + ": Starting threads and schedulers");
            nodeAdmin.start();
            specVerifierScheduler.scheduleWithFixedDelay(() ->
                    updateHardwareDivergence(storageMaintainer), 5, 60, TimeUnit.MINUTES);

            while (! terminated.get()) {
                tick();
            }
        });
        this.loopThread.setName("tick-NodeAdminStateUpdater");
    }

    private String objectToString() {
        return this.getClass().getSimpleName() + "@" + Integer.toString(System.identityHashCode(this));
    }

    @Override
    public Map<String, Object> getDebugPage() {
        Map<String, Object> debug = new LinkedHashMap<>();
        synchronized (monitor) {
            debug.put("dockerHostHostName", dockerHostHostName);
            debug.put("wantedState", wantedState);
            debug.put("currentState", currentState);
            debug.put("NodeAdmin", nodeAdmin.debugInfo());
        }
        return debug;
    }

    private void updateHardwareDivergence(StorageMaintainer maintainer) {
        if (currentState != RESUMED) return;

        try {
            NodeSpec node = nodeRepository.getNode(dockerHostHostName)
                    .orElseThrow(() -> new RuntimeException("Failed to get host's node spec from node-repo"));
            String hardwareDivergence = maintainer.getHardwareDivergence(node);

            // Only update hardware divergence if there is a change.
            if (!node.hardwareDivergence.orElse("null").equals(hardwareDivergence)) {
                NodeAttributes nodeAttributes = new NodeAttributes().withHardwareDivergence(hardwareDivergence);
                nodeRepository.updateNodeAttributes(dockerHostHostName, nodeAttributes);
            }
        } catch (RuntimeException e) {
            log.log(Level.WARNING, "Failed to report hardware divergence", e);
        }
    }

    @Override
    public boolean setResumeStateAndCheckIfResumed(State wantedState) {
        synchronized (monitor) {
            if (this.wantedState != wantedState) {
                log.info("Wanted state change: " + this.wantedState + " -> " + wantedState);
                this.wantedState = wantedState;
                signalWorkToBeDone();
            }

            return currentState == wantedState;
        }
    }

    void signalWorkToBeDone() {
        synchronized (monitor) {
            if (! workToDoNow) {
                workToDoNow = true;
                monitor.notifyAll();
            }
        }
    }

    void tick() {
        State wantedStateCopy;
        synchronized (monitor) {
            while (! workToDoNow) {
                Duration timeSinceLastConverge = Duration.between(lastTick, clock.instant());
                long remainder = nodeAdminConvergeStateInterval.minus(timeSinceLastConverge).toMillis();
                if (remainder > 0) {
                    try {
                        monitor.wait(remainder);
                    } catch (InterruptedException e) {
                        log.info("Interrupted, but ignoring this: NodeAdminStateUpdater");
                    }
                } else break;
            }
            lastTick = clock.instant();
            workToDoNow = false;

            // wantedState may change asynchronously, so we grab a copy of it here
            wantedStateCopy = this.wantedState;
        }

        try {
            convergeState(wantedStateCopy);
        } catch (OrchestratorException | ConvergenceException | HttpException e) {
            log.info("Unable to converge to " + wantedStateCopy + ": " + e.getMessage());
        } catch (Exception e) {
            log.log(LogLevel.ERROR, "Error while trying to converge to " + wantedStateCopy, e);
        }

        if (wantedStateCopy != RESUMED && currentState == TRANSITIONING) {
            Duration subsystemFreezeDuration = nodeAdmin.subsystemFreezeDuration();
            if (subsystemFreezeDuration.compareTo(FREEZE_CONVERGENCE_TIMEOUT) > 0) {
                // We have spent too much time trying to freeze and node admin is still not frozen.
                // To avoid node agents stalling for too long, we'll force unfrozen ticks now.
                log.info("Timed out trying to freeze, will force unfreezed ticks");
                nodeAdmin.setFrozen(false);
            }
        }

        fetchContainersToRunFromNodeRepository();
    }

    /**
     * This method attempts to converge node-admin w/agents to a {@link State}
     * with respect to: freeze, Orchestrator, and services running.
     */
    private void convergeState(State wantedState) {
        if (currentState == wantedState) return;
        synchronized (monitor) {
            currentState = TRANSITIONING;
        }

        boolean wantFrozen = wantedState != RESUMED;
        if (!nodeAdmin.setFrozen(wantFrozen)) {
            throw new ConvergenceException("NodeAdmin is not yet " + (wantFrozen ? "frozen" : "unfrozen"));
        }

        switch (wantedState) {
            case RESUMED:
                orchestrator.resume(dockerHostHostName);
                break;
            case SUSPENDED_NODE_ADMIN:
                orchestrator.suspend(dockerHostHostName);
                break;
            case SUSPENDED:
                // Fetch active nodes from node repo before suspending nodes.
                // It is only possible to suspend active nodes,
                // the orchestrator will fail if trying to suspend nodes in other states.
                // Even though state is frozen we need to interact with node repo, but
                // the data from node repo should not be used for anything else.
                // We should also suspend host's hostname to suspend node-admin
                List<String> nodesInActiveState = getNodesInActiveState();

                List<String> nodesToSuspend = new ArrayList<>();
                nodesToSuspend.addAll(nodesInActiveState);
                nodesToSuspend.add(dockerHostHostName);
                orchestrator.suspend(dockerHostHostName, nodesToSuspend);
                log.info("Orchestrator allows suspension of " + nodesToSuspend);

                // The node agent services are stopped by this thread, which is OK only
                // because the node agents are frozen (see above).
                nodeAdmin.stopNodeAgentServices(nodesInActiveState);
                break;
            default:
                throw new IllegalStateException("Unknown wanted state " + wantedState);
        }

        log.info("State changed from " + currentState + " to " + wantedState);
        synchronized (monitor) {
            // Writes to currentState must be synchronized. Reads doesn't have to since this thread
            // is the only one modifying it.
            currentState = wantedState;
        }
    }

    private void fetchContainersToRunFromNodeRepository() {
        synchronized (monitor) {
            // Refresh containers to run even if we would like to suspend but have failed to do so yet,
            // because it may take a long time to get permission to suspend.
            if (currentState != RESUMED) {
                log.info("Frozen, skipping fetching info from node repository");
                return;
            }

            try {
                final List<NodeSpec> containersToRun = nodeRepository.getNodes(dockerHostHostName);
                nodeAdmin.refreshContainersToRun(containersToRun);
            } catch (Exception e) {
                log.log(LogLevel.WARNING, "Failed to update which containers should be running", e);
            }
        }
    }

    private List<String> getNodesInActiveState() {
        return nodeRepository.getNodes(dockerHostHostName)
                             .stream()
                             .filter(node -> node.nodeState == Node.State.active)
                             .map(node -> node.hostname)
                             .collect(Collectors.toList());
    }

    public void start() {
        loopThread.start();
    }

    public void stop() {
        log.info(objectToString() + ": Stop called");
        if (!terminated.compareAndSet(false, true)) {
            throw new RuntimeException("Can not re-stop a node agent.");
        }

        classLocking.ifPresent(ClassLocking::interrupt);

        // First we need to stop NodeAdminStateUpdaterImpl thread to make sure no new NodeAgents are spawned
        signalWorkToBeDone();
        specVerifierScheduler.shutdown();

        do {
            try {
                loopThread.join();
                specVerifierScheduler.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
            } catch (InterruptedException e1) {
                log.info("Interrupted while waiting for NodeAdminStateUpdater thread and specVerfierScheduler to shutdown");
            }
        } while (loopThread.isAlive() || !specVerifierScheduler.isTerminated());

        // Finally, stop NodeAdmin and all the NodeAgents
        nodeAdmin.stop();

        classLock.ifPresent(lock -> {
            log.info(objectToString() + ": Releasing lock");
            lock.close();
        });
        log.info(objectToString() + ": Stop complete");
    }
}