aboutsummaryrefslogtreecommitdiffstats
path: root/searchcore/src/vespa/searchcore/proton/server/maintenancejobrunner.cpp
blob: e580066ec172bed613af309443888e333d502b92 (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
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "maintenancejobrunner.h"
#include <vespa/vespalib/util/cpu_usage.h>
#include <vespa/vespalib/util/lambdatask.h>

#include <vespa/log/log.h>
LOG_SETUP(".proton.server.maintenancejobrunner");

using vespalib::CpuUsage;
using vespalib::Executor;
using vespalib::makeLambdaTask;

namespace proton {


void
MaintenanceJobRunner::run()
{
    addExecutorTask();
}

void
MaintenanceJobRunner::stop() {
    {
        Guard guard(_lock);
        _stopped = true;
    }
    _job->stop();
}

void
MaintenanceJobRunner::addExecutorTask()
{
    Guard guard(_lock);
    if (!_stopped && !_job->isBlocked() && !_queued) {
        _queued = true;
        auto task = makeLambdaTask([this]() { runJobInExecutor(); });
        _executor.execute(CpuUsage::wrap(std::move(task), CpuUsage::Category::COMPACT));
    }
}

void
MaintenanceJobRunner::runJobInExecutor()
{
    {
        Guard guard(_lock);
        _queued = false;
        if (_stopped) {
            return;
        }
        _running = true;
    }
    bool finished = _job->run();
    if (LOG_WOULD_LOG(debug)) {
        LOG(debug,
            "runJobInExecutor(): job='%s', task='%p'",
            _job->getName().c_str(), this);
    }
    if (!finished) {
        addExecutorTask();
    }
    {
        Guard guard(_lock);
        _running = false;
    }
}

MaintenanceJobRunner::MaintenanceJobRunner(Executor &executor, IMaintenanceJob::UP job)
    : _executor(executor),
      _job(std::move(job)),
      _stopped(false),
      _queued(false),
      _running(false),
      _lock()
{
    _job->registerRunner(this);
}

bool
MaintenanceJobRunner::isRunnable() const
{
    Guard guard(_lock);
    return _running || _queued;
}

} // namespace proton