aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/clickhouse/src/Storages/MergeTree/MergeTreeSource.cpp
blob: 69fbdd5a64de1e755e260908edbffe77b5a6f309 (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
#include <Storages/MergeTree/MergeTreeSource.h>
#include <Storages/MergeTree/MergeTreeBaseSelectProcessor.h>
#include <Interpreters/threadPoolCallbackRunner.h>
#include <IO/SharedThreadPools.h>
#include <Common/EventFD.h>

namespace DB
{

#if defined(OS_LINUX)
struct MergeTreeSource::AsyncReadingState
{
    /// NotStarted -> InProgress -> IsFinished -> NotStarted ...
    enum class Stage
    {
        NotStarted,
        InProgress,
        IsFinished,
    };

    struct Control
    {
        /// setResult and setException are the only methods
        /// which can be called from background thread.
        /// Invariant:
        ///   * background thread changes status InProgress -> IsFinished
        ///   * (status == InProgress) => (MergeTreeBaseSelectProcessor is alive)

        void setResult(ChunkAndProgress chunk_)
        {
            chassert(stage == Stage::InProgress);
            chunk = std::move(chunk_);
            finish();
        }

        void setException(std::exception_ptr exception_)
        {
            chassert(stage == Stage::InProgress);
            exception = exception_;
            finish();
        }

    private:

        /// Executor requires file descriptor (which can be polled) to be returned for async execution.
        /// We are using EventFD here.
        /// Thread from background pool writes to fd when task is finished.
        /// Working thread should read from fd when task is finished or canceled to wait for bg thread.
        EventFD event;
        std::atomic<Stage> stage = Stage::NotStarted;

        ChunkAndProgress chunk;
        std::exception_ptr exception;

        void finish()
        {
            stage = Stage::IsFinished;
            event.write();
        }

        ChunkAndProgress getResult()
        {
            chassert(stage == Stage::IsFinished);
            event.read();
            stage = Stage::NotStarted;

            if (exception)
                std::rethrow_exception(exception);

            return std::move(chunk);
        }

        friend struct AsyncReadingState;
    };

    std::shared_ptr<Control> start()
    {
        chassert(control->stage == Stage::NotStarted);
        control->stage = Stage::InProgress;
        return control;
    }

    void schedule(ThreadPool::Job job)
    {
        try
        {
            callback_runner(std::move(job), Priority{});
        }
        catch (...)
        {
            /// Roll back stage in case of exception from ThreadPool::schedule
            control->stage = Stage::NotStarted;
            throw;
        }
    }

    ChunkAndProgress getResult()
    {
        return control->getResult();
    }

    Stage getStage() const { return control->stage; }
    int getFD() const { return control->event.fd; }

    AsyncReadingState()
    {
        control = std::make_shared<Control>();
        callback_runner = threadPoolCallbackRunner<void>(getIOThreadPool().get(), "MergeTreeRead");
    }

    ~AsyncReadingState()
    {
        /// Here we wait for async task if needed.
        /// ~AsyncReadingState and Control::finish can be run concurrently.
        /// It's important to store std::shared_ptr<Control> into bg pool task.
        /// Otherwise following is possible:
        ///
        ///  (executing thread)                         (bg pool thread)
        ///                                             Control::finish()
        ///                                             stage = Stage::IsFinished;
        ///  ~MergeTreeBaseSelectProcessor()
        ///  ~AsyncReadingState()
        ///  control->stage != Stage::InProgress
        ///  ~EventFD()
        ///                                             event.write()
        if (control->stage == Stage::InProgress)
            control->event.read();
    }

private:
    ThreadPoolCallbackRunner<void> callback_runner;
    std::shared_ptr<Control> control;
};
#endif

MergeTreeSource::MergeTreeSource(MergeTreeSelectAlgorithmPtr algorithm_)
    : ISource(algorithm_->getHeader())
    , algorithm(std::move(algorithm_))
{
#if defined(OS_LINUX)
    if (algorithm->getSettings().use_asynchronous_read_from_pool)
        async_reading_state = std::make_unique<AsyncReadingState>();
#endif
}

MergeTreeSource::~MergeTreeSource() = default;

std::string MergeTreeSource::getName() const
{
    return algorithm->getName();
}

void MergeTreeSource::onCancel()
{
    algorithm->cancel();
}

ISource::Status MergeTreeSource::prepare()
{
#if defined(OS_LINUX)
    if (!async_reading_state)
        return ISource::prepare();

    /// Check if query was cancelled before returning Async status. Otherwise it may lead to infinite loop.
    if (isCancelled())
    {
        getPort().finish();
        return ISource::Status::Finished;
    }

    if (async_reading_state && async_reading_state->getStage() == AsyncReadingState::Stage::InProgress)
        return ISource::Status::Async;
#endif

    return ISource::prepare();
}


Chunk MergeTreeSource::processReadResult(ChunkAndProgress chunk)
{
    if (chunk.num_read_rows || chunk.num_read_bytes)
        progress(chunk.num_read_rows, chunk.num_read_bytes);

    finished = chunk.is_finished;

    /// We can return a chunk with no rows even if are not finished.
    /// This allows to report progress when all the rows are filtered out inside MergeTreeBaseSelectProcessor by PREWHERE logic.
    return std::move(chunk.chunk);
}


std::optional<Chunk> MergeTreeSource::tryGenerate()
{
#if defined(OS_LINUX)
    if (async_reading_state)
    {
        if (async_reading_state->getStage() == AsyncReadingState::Stage::IsFinished)
            return processReadResult(async_reading_state->getResult());

        chassert(async_reading_state->getStage() == AsyncReadingState::Stage::NotStarted);

        /// It is important to store control into job.
        /// Otherwise, race between job and ~MergeTreeBaseSelectProcessor is possible.
        auto job = [this, control = async_reading_state->start()]() mutable
        {
            auto holder = std::move(control);

            try
            {
                OpenTelemetry::SpanHolder span{"MergeTreeSource::tryGenerate()"};
                holder->setResult(algorithm->read());
            }
            catch (...)
            {
                holder->setException(std::current_exception());
            }
        };

        async_reading_state->schedule(std::move(job));

        return Chunk();
    }
#endif

    OpenTelemetry::SpanHolder span{"MergeTreeSource::tryGenerate()"};
    return processReadResult(algorithm->read());
}

#if defined(OS_LINUX)
int MergeTreeSource::schedule()
{
    return async_reading_state->getFD();
}
#endif

}