aboutsummaryrefslogtreecommitdiffstats
path: root/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/JobRunner.java
blob: 0f482b1a015478ee395119a5848c682b8eaf050d (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
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.maintenance;

import ai.vespa.metrics.ControllerMetrics;
import com.yahoo.concurrent.DaemonThreadFactory;
import com.yahoo.jdisc.Metric;
import com.yahoo.vespa.hosted.controller.Controller;
import com.yahoo.vespa.hosted.controller.api.integration.deployment.RunId;
import com.yahoo.vespa.hosted.controller.deployment.InternalStepRunner;
import com.yahoo.vespa.hosted.controller.deployment.JobController;
import com.yahoo.vespa.hosted.controller.deployment.Run;
import com.yahoo.vespa.hosted.controller.deployment.Step;
import com.yahoo.vespa.hosted.controller.deployment.StepRunner;

import java.time.Duration;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Advances the set of {@link Run}s for a {@link JobController}.
 *
 * @author jonmv
 */
public class JobRunner extends ControllerMaintainer {

    public static final Duration jobTimeout = Duration.ofDays(1).plusHours(1);
    private static final Logger log = Logger.getLogger(JobRunner.class.getName());

    private final JobController jobs;
    private final ExecutorService executors;
    private final StepRunner runner;
    private final Metrics metrics;

    public JobRunner(Controller controller, Duration duration) {
        this(controller, duration, Executors.newFixedThreadPool(32, new DaemonThreadFactory("job-runner-")),
             new InternalStepRunner(controller));
    }

    public JobRunner(Controller controller, Duration duration, ExecutorService executors, StepRunner runner) {
        this(controller, duration, executors, runner, new Metrics(controller.metric(), Duration.ofMillis(100)));
    }

    JobRunner(Controller controller, Duration duration, ExecutorService executors, StepRunner runner, Metrics metrics) {
        super(controller, duration);
        this.jobs = controller.jobController();
        this.jobs.setRunner(this::advance);
        this.executors = executors;
        this.runner = runner;
        this.metrics = metrics;
    }

    @Override
    protected double maintain() {
        execute(() -> jobs.active().forEach(this::advance));
        jobs.collectGarbage();
        return 1.0;
    }

    @Override
    public void shutdown() {
        super.shutdown();
        metrics.shutdown();
        executors.shutdown();
    }

    @Override
    public void awaitShutdown() {
        super.awaitShutdown();
        try {
            if ( ! executors.awaitTermination(40, TimeUnit.SECONDS)) {
                executors.shutdownNow();
                if ( ! executors.awaitTermination(10, TimeUnit.SECONDS))
                    throw new IllegalStateException("Failed shutting down " + JobRunner.class.getName());
            }
        }
        catch (InterruptedException e) {
            log.log(Level.WARNING, "Interrupted during shutdown of " + JobRunner.class.getName(), e);
            Thread.currentThread().interrupt();
        }
    }

    public void advance(Run run) {
        if ( ! jobs.isDisabled(run.id().job())) advance(run.id());
    }

    /** Advances each of the ready steps for the given run, or marks it as finished, and stashes it. Public for testing. */
    public void advance(RunId id) {
        jobs.locked(id, run -> {
            if (   ! run.hasFailed()
                &&   controller().clock().instant().isAfter(run.sleepUntil().orElse(run.start()).plus(jobTimeout)))
                execute(() -> {
                    jobs.abort(run.id(), "job timeout of " + jobTimeout + " reached", false);
                    advance(run.id());
                });
            else if (run.readySteps().isEmpty())
                execute(() -> finish(run.id()));
            else if (run.hasFailed() || run.sleepUntil().map(sleepUntil -> ! sleepUntil.isAfter(controller().clock().instant())).orElse(true))
                run.readySteps().forEach(step -> execute(() -> advance(run.id(), step)));

            return null;
        });
    }

    private void finish(RunId id) {
        try {
            jobs.finish(id);
            if ( ! id.type().environment().isManuallyDeployed())
                controller().applications().deploymentTrigger().notifyOfCompletion(id.application());
        }
        catch (TimeoutException e) {
            // One of the steps are still being run — that's ok, we'll try to finish the run again later.
        }
        catch (Exception e) {
            log.log(Level.WARNING, "Exception finishing " + id, e);
        }
    }

    /** Attempts to advance the status of the given step, for the given run. */
    private void advance(RunId id, Step step) {
        try {
            AtomicBoolean changed = new AtomicBoolean(false);
            jobs.locked(id.application(), id.type(), step, lockedStep -> {
                jobs.locked(id, run -> {
                    if ( ! run.readySteps().contains(step)) {
                        changed.set(true);
                        return run; // Someone may have updated the run status, making this step obsolete, so we bail out.
                    }

                    if (run.stepInfo(lockedStep.get()).orElseThrow().startTime().isEmpty())
                        run = run.with(controller().clock().instant(), lockedStep);

                    return run;
                });

                if ( ! changed.get()) {
                    runner.run(lockedStep, id).ifPresent(status -> {
                        jobs.update(id, status, lockedStep);
                        changed.set(true);
                    });
                }
            });
            if (changed.get())
                jobs.active(id).ifPresent(this::advance);
        }
        catch (TimeoutException e) {
            // Something else is already advancing this step, or a prerequisite -- try again later!
        }
        catch (RuntimeException e) {
            log.log(Level.WARNING, "Exception attempting to advance " + step + " of " + id, e);
        }
    }

    private void execute(Runnable task) {
        metrics.queued.incrementAndGet();
        executors.execute(() -> {
            metrics.queued.decrementAndGet();
            metrics.active.incrementAndGet();
            try { task.run(); }
            finally { metrics.active.decrementAndGet(); }
        });
    }

    static class Metrics {

        private final AtomicInteger queued = new AtomicInteger();
        private final AtomicInteger active = new AtomicInteger();
        private final ScheduledExecutorService reporter = Executors.newSingleThreadScheduledExecutor(new DaemonThreadFactory("job-runner-metrics-"));
        private final Metric metric;
        private final Metric.Context context;

        Metrics(Metric metric, Duration interval) {
            this.metric = metric;
            this.context = metric.createContext(Map.of());
            reporter.scheduleAtFixedRate(this::report, interval.toMillis(), interval.toMillis(), TimeUnit.MILLISECONDS);
        }

        void report() {
            metric.set(ControllerMetrics.DEPLOYMENT_JOBS_QUEUED.baseName(), queued.get(), context);
            metric.set(ControllerMetrics.DEPLOYMENT_JOBS_ACTIVE.baseName(), active.get(), context);
        }

        void shutdown() {
            reporter.shutdown();
        }

    }

}