aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/clickhouse/src/IO/Resource/DynamicResourceManager.cpp
blob: df0de6575f469ffe8646ed1d1b63e62dbfb80c16 (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
#include <IO/Resource/DynamicResourceManager.h>

#include <IO/SchedulerNodeFactory.h>
#include <IO/ResourceManagerFactory.h>
#include <IO/ISchedulerQueue.h>

#include <Common/Exception.h>
#include <Common/StringUtils/StringUtils.h>

#include <map>
#include <tuple>

namespace DB
{

namespace ErrorCodes
{
    extern const int RESOURCE_ACCESS_DENIED;
    extern const int RESOURCE_NOT_FOUND;
    extern const int INVALID_SCHEDULER_NODE;
}

DynamicResourceManager::State::State(EventQueue * event_queue, const Poco::Util::AbstractConfiguration & config)
    : classifiers(config)
{
    Poco::Util::AbstractConfiguration::Keys keys;
    const String config_prefix = "resources";
    config.keys(config_prefix, keys);

    // Create resource for every element under <resources> tag
    for (const auto & key : keys)
    {
        resources.emplace(key, std::make_shared<Resource>(key, event_queue, config, config_prefix + "." + key));
    }
}

DynamicResourceManager::State::Resource::Resource(
    const String & name,
    EventQueue * event_queue,
    const Poco::Util::AbstractConfiguration & config,
    const std::string & config_prefix)
{
    Poco::Util::AbstractConfiguration::Keys keys;
    config.keys(config_prefix, keys);

    // Sort nodes by path to create parents before children
    std::map<String, String> path2key;
    for (const auto & key : keys)
    {
        if (!startsWith(key, "node"))
            continue;
        String path = config.getString(config_prefix + "." + key + "[@path]", "");
        if (path.empty())
            throw Exception(ErrorCodes::INVALID_SCHEDULER_NODE, "Attribute 'path' must be specified in all nodes for resource '{}'", name);
        if (path[0] != '/')
            throw Exception(ErrorCodes::INVALID_SCHEDULER_NODE, "Path must start with '/' for resource '{}'", name);
        if (auto [_, inserted] = path2key.emplace(path, key); !inserted)
            throw Exception(ErrorCodes::INVALID_SCHEDULER_NODE, "Duplicate path '{}' for resource '{}'", path, name);
    }

    // Create nodes
    bool has_root = false;
    for (auto [path, key] : path2key)
    {
        // Validate path
        size_t slash = path.rfind('/');
        if (slash == String::npos)
            throw Exception(ErrorCodes::INVALID_SCHEDULER_NODE, "Invalid scheduler node path '{}' for resource '{}'", path, name);

        // Create node
        String basename = path.substr(slash + 1); // root name is empty string
        auto [iter, _] = nodes.emplace(path, Node(basename, event_queue, config, config_prefix + "." + key));
        if (path == "/")
        {
            has_root = true;
            continue;
        }

        // Attach created node to parent (if not root)
        // NOTE: resource root is attached to the scheduler using event queue for thread-safety
        String parent_path = path.substr(0, slash);
        if (parent_path.empty())
            parent_path = "/";
        if (auto parent = nodes.find(parent_path); parent != nodes.end())
            parent->second.ptr->attachChild(iter->second.ptr);
        else
            throw Exception(ErrorCodes::INVALID_SCHEDULER_NODE, "Parent node doesn't exist for path '{}' for resource '{}'", path, name);
    }

    if (!has_root)
        throw Exception(ErrorCodes::INVALID_SCHEDULER_NODE, "undefined root node path '/' for resource '{}'", name);
}

DynamicResourceManager::State::Resource::~Resource()
{
    // NOTE: we should rely on `attached_to` and cannot use `parent`,
    // NOTE: because `parent` can be `nullptr` in case attachment is still in event queue
    if (attached_to != nullptr)
    {
        ISchedulerNode * root = nodes.find("/")->second.ptr.get();
        attached_to->event_queue->enqueue([my_scheduler = attached_to, root]
        {
            my_scheduler->removeChild(root);
        });
    }
}

DynamicResourceManager::State::Node::Node(const String & name, EventQueue * event_queue, const Poco::Util::AbstractConfiguration & config, const std::string & config_prefix)
    : type(config.getString(config_prefix + ".type", "fifo"))
    , ptr(SchedulerNodeFactory::instance().get(type, event_queue, config, config_prefix))
{
    ptr->basename = name;
}

bool DynamicResourceManager::State::Resource::equals(const DynamicResourceManager::State::Resource & o) const
{
    if (nodes.size() != o.nodes.size())
        return false;

    for (const auto & [path, o_node] : o.nodes)
    {
        auto iter = nodes.find(path);
        if (iter == nodes.end())
            return false;
        if (!iter->second.equals(o_node))
            return false;
    }

    return true;
}

bool DynamicResourceManager::State::Node::equals(const DynamicResourceManager::State::Node & o) const
{
    if (type != o.type)
        return false;
    return ptr->equals(o.ptr.get());
}

DynamicResourceManager::Classifier::Classifier(const DynamicResourceManager::StatePtr & state_, const String & classifier_name)
    : state(state_)
{
    // State is immutable, but nodes are mutable and thread-safe
    // So it's safe to obtain node pointers w/o lock
    for (auto [resource_name, path] : state->classifiers.get(classifier_name))
    {
        if (auto resource_iter = state->resources.find(resource_name); resource_iter != state->resources.end())
        {
            const auto & resource = resource_iter->second;
            if (auto node_iter = resource->nodes.find(path); node_iter != resource->nodes.end())
            {
                if (auto * queue = dynamic_cast<ISchedulerQueue *>(node_iter->second.ptr.get()))
                    resources.emplace(resource_name, ResourceLink{.queue = queue});
                else
                    throw Exception(ErrorCodes::RESOURCE_NOT_FOUND, "Unable to access non-queue node at path '{}' for resource '{}'", path, resource_name);
            }
            else
                throw Exception(ErrorCodes::RESOURCE_NOT_FOUND, "Path '{}' for resource '{}' does not exist", path, resource_name);
        }
        else
            resources.emplace(resource_name, ResourceLink{}); // resource not configured yet - use unlimited resource
    }
}

ResourceLink DynamicResourceManager::Classifier::get(const String & resource_name)
{
    if (auto iter = resources.find(resource_name); iter != resources.end())
        return iter->second;
    else
        throw Exception(ErrorCodes::RESOURCE_ACCESS_DENIED, "Access denied to resource '{}'", resource_name);
}

DynamicResourceManager::DynamicResourceManager()
    : state(new State())
{
    scheduler.start();
}

void DynamicResourceManager::updateConfiguration(const Poco::Util::AbstractConfiguration & config)
{
    StatePtr new_state = std::make_shared<State>(scheduler.event_queue, config);

    std::lock_guard lock{mutex};

    // Resource update leads to loss of runtime data of nodes and may lead to temporary violation of constraints (e.g. limits)
    // Try to minimise this by reusing "equal" resources (initialized with the same configuration).
    for (auto & [name, new_resource] : new_state->resources)
    {
        if (auto iter = state->resources.find(name); iter != state->resources.end()) // Resource update
        {
            State::ResourcePtr old_resource = iter->second;
            if (old_resource->equals(*new_resource))
                new_resource = old_resource; // Rewrite with older version to avoid loss of runtime data
        }
    }

    // Commit new state
    // NOTE: dtor will detach from scheduler old resources that are not in use currently
    state = new_state;

    // Attach new and updated resources to the scheduler
    for (auto & [name, resource] : new_state->resources)
    {
        const SchedulerNodePtr & root = resource->nodes.find("/")->second.ptr;
        if (root->parent == nullptr)
        {
            resource->attached_to = &scheduler;
            scheduler.event_queue->enqueue([this, root]
            {
                scheduler.attachChild(root);
            });
        }
    }

    // NOTE: after mutex unlock `state` became available for Classifier(s) and must be immutable
}

ClassifierPtr DynamicResourceManager::acquire(const String & classifier_name)
{
    // Acquire a reference to the current state
    StatePtr state_;
    {
        std::lock_guard lock{mutex};
        state_ = state;
    }

    return std::make_shared<Classifier>(state_, classifier_name);
}

void registerDynamicResourceManager(ResourceManagerFactory & factory)
{
    factory.registerMethod<DynamicResourceManager>("dynamic");
}

}