aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/clickhouse/src/IO/SchedulerRoot.h
blob: f9af2099b8ccbf1d28aab5da80476ed47212d6c9 (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
#pragma once

#include <base/defines.h>

#include <Common/Stopwatch.h>
#include <Common/ThreadPool.h>

#include <IO/ISchedulerNode.h>
#include <IO/ISchedulerConstraint.h>

#include <Poco/Util/XMLConfiguration.h>

#include <unordered_map>
#include <map>
#include <memory>
#include <atomic>


namespace DB
{

namespace ErrorCodes
{
    extern const int INVALID_SCHEDULER_NODE;
}

/*
 * Resource scheduler root node with a dedicated thread.
 * Immediate children correspond to different resources.
 */
class SchedulerRoot : public ISchedulerNode
{
private:
    struct TResource
    {
        SchedulerNodePtr root;

        // Intrusive cyclic list of active resources
        TResource * next = nullptr;
        TResource * prev = nullptr;

        explicit TResource(const SchedulerNodePtr & root_)
            : root(root_)
        {
            root->info.parent.ptr = this;
        }

        // Get pointer stored by ctor in info
        static TResource * get(SchedulerNodeInfo & info)
        {
            return reinterpret_cast<TResource *>(info.parent.ptr);
        }
    };

public:
    SchedulerRoot()
        : ISchedulerNode(&events)
    {}

    ~SchedulerRoot() override
    {
        stop();
    }

    /// Runs separate scheduler thread
    void start()
    {
        if (!scheduler.joinable())
            scheduler = ThreadFromGlobalPool([this] { schedulerThread(); });
    }

    /// Joins scheduler threads and execute every pending request iff graceful
    void stop(bool graceful = true)
    {
        if (scheduler.joinable())
        {
            stop_flag.store(true);
            events.enqueue([]{}); // just to wake up thread
            scheduler.join();
            if (graceful)
            {
                // Do the same cycle as schedulerThread() but never block, just exit instead
                bool has_work = true;
                while (has_work)
                {
                    auto [request, _] = dequeueRequest();
                    if (request)
                        execute(request);
                    else
                        has_work = false;
                    while (events.tryProcess())
                        has_work = true;
                }
            }
        }
    }

    bool equals(ISchedulerNode * other) override
    {
        if (auto * o = dynamic_cast<SchedulerRoot *>(other))
            return true;
        return false;
    }

    void attachChild(const SchedulerNodePtr & child) override
    {
        // Take ownership
        assert(child->parent == nullptr);
        if (auto [it, inserted] = children.emplace(child.get(), child); !inserted)
            throw Exception(
                ErrorCodes::INVALID_SCHEDULER_NODE,
                "Can't add the same scheduler node twice");

        // Attach
        child->setParent(this);

        // Activate child if required
        if (child->isActive())
            activateChild(child.get());
    }

    void removeChild(ISchedulerNode * child) override
    {
        if (auto iter = children.find(child); iter != children.end())
        {
            SchedulerNodePtr removed = iter->second.root;

            // Deactivate if required
            deactivate(&iter->second);

            // Detach
            removed->setParent(nullptr);

            // Remove ownership
            children.erase(iter);
        }
    }

    ISchedulerNode * getChild(const String &) override
    {
        abort(); // scheduler is allowed to have multiple children with the same name
    }

    std::pair<ResourceRequest *, bool> dequeueRequest() override
    {
        if (current == nullptr) // No active resources
            return {nullptr, false};

        // Dequeue request from current resource
        auto [request, resource_active] = current->root->dequeueRequest();
        assert(request != nullptr);

        // Deactivate resource if required
        if (!resource_active)
            deactivate(current);
        else
            current = current->next; // Just move round-robin pointer

        return {request, current != nullptr};
    }

    bool isActive() override
    {
        return current != nullptr;
    }

    void activateChild(ISchedulerNode * child) override
    {
        activate(TResource::get(child->info));
    }

    void setParent(ISchedulerNode *) override
    {
        abort(); // scheduler must be the root and this function should not be called
    }

private:
    void activate(TResource * value)
    {
        assert(value->next == nullptr && value->prev == nullptr);
        if (current == nullptr) // No active children
        {
            current = value;
            value->prev = value;
            value->next = value;
        }
        else
        {
            current->prev->next = value;
            value->prev = current->prev;
            current->prev = value;
            value->next = current;
        }
    }

    void deactivate(TResource * value)
    {
        if (value->next == nullptr)
            return; // Already deactivated
        assert(current != nullptr);
        if (current == value)
        {
            if (current->next == current) // We are going to remove the last active child
            {
                value->next = nullptr;
                value->prev = nullptr;
                current = nullptr;
                return;
            }
            else // Just move current to next to avoid invalidation
                current = current->next;
        }
        value->prev->next = value->next;
        value->next->prev = value->prev;
        value->prev = nullptr;
        value->next = nullptr;
    }

private:
    void schedulerThread()
    {
        while (!stop_flag.load())
        {
            // Dequeue and execute single request
            auto [request, _] = dequeueRequest();
            if (request)
                execute(request);
            else // No more requests -- block until any event happens
                events.process();

            // Process all events before dequeuing to ensure fair competition
            while (events.tryProcess()) {}
        }
    }

    void execute(ResourceRequest * request)
    {
        request->execute_ns = clock_gettime_ns();
        request->execute();
    }

private:
    TResource * current = nullptr; // round-robin pointer
    std::unordered_map<ISchedulerNode *, TResource> children; // resources by pointer
    std::atomic<bool> stop_flag = false;
    EventQueue events;
    ThreadFromGlobalPool scheduler;
};

}