executeDDLQueryOnCluster.cpp 15.2 KB
Newer Older
A
Alexander Tokmakov 已提交
1 2 3 4
#include <Interpreters/executeDDLQueryOnCluster.h>
#include <Interpreters/DDLWorker.h>
#include <Interpreters/DDLTask.h>
#include <Interpreters/AddDefaultDatabaseVisitor.h>
5
#include <Interpreters/Context.h>
A
Alexander Tokmakov 已提交
6 7 8 9 10 11 12 13 14 15
#include <Parsers/ASTQueryWithOutput.h>
#include <Parsers/ASTQueryWithOnCluster.h>
#include <Parsers/ASTAlterQuery.h>
#include <Parsers/queryToString.h>
#include <Access/AccessRightsElement.h>
#include <Access/ContextAccess.h>
#include <Common/Macros.h>
#include <Common/ZooKeeper/ZooKeeper.h>
#include <DataTypes/DataTypesNumber.h>
#include <DataTypes/DataTypeString.h>
16 17 18
#include <DataTypes/DataTypeNullable.h>
#include <DataStreams/NullBlockOutputStream.h>
#include <DataStreams/copyData.h>
19
#include <filesystem>
A
Alexander Tokmakov 已提交
20

21
namespace fs = std::filesystem;
A
Alexander Tokmakov 已提交
22 23 24 25 26 27 28 29 30 31

namespace DB
{

namespace ErrorCodes
{
    extern const int NOT_IMPLEMENTED;
    extern const int TIMEOUT_EXCEEDED;
    extern const int UNFINISHED;
    extern const int QUERY_IS_PROHIBITED;
A
Alexander Tokmakov 已提交
32
    extern const int LOGICAL_ERROR;
A
Alexander Tokmakov 已提交
33 34
}

35
bool isSupportedAlterType(int type)
A
Alexander Tokmakov 已提交
36
{
A
fix  
Alexander Tokmakov 已提交
37
    assert(type != ASTAlterCommand::NO_TYPE);
A
Alexander Tokmakov 已提交
38
    static const std::unordered_set<int> unsupported_alter_types{
A
fix  
Alexander Tokmakov 已提交
39
        /// It's dangerous, because it may duplicate data if executed on multiple replicas. We can allow it after #18978
A
Alexander Tokmakov 已提交
40
        ASTAlterCommand::ATTACH_PARTITION,
A
fix  
Alexander Tokmakov 已提交
41
        /// Usually followed by ATTACH PARTITION
A
Alexander Tokmakov 已提交
42
        ASTAlterCommand::FETCH_PARTITION,
A
fix  
Alexander Tokmakov 已提交
43
        /// Logical error
A
Alexander Tokmakov 已提交
44 45 46 47 48 49 50 51 52 53 54 55
        ASTAlterCommand::NO_TYPE,
    };

    return unsupported_alter_types.count(type) == 0;
}


BlockIO executeDDLQueryOnCluster(const ASTPtr & query_ptr_, const Context & context)
{
    return executeDDLQueryOnCluster(query_ptr_, context, {});
}

56
BlockIO executeDDLQueryOnCluster(const ASTPtr & query_ptr, const Context & context, const AccessRightsElements & query_requires_access)
A
Alexander Tokmakov 已提交
57
{
58
    return executeDDLQueryOnCluster(query_ptr, context, AccessRightsElements{query_requires_access});
A
Alexander Tokmakov 已提交
59 60
}

61
BlockIO executeDDLQueryOnCluster(const ASTPtr & query_ptr_, const Context & context, AccessRightsElements && query_requires_access)
A
Alexander Tokmakov 已提交
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
{
    /// Remove FORMAT <fmt> and INTO OUTFILE <file> if exists
    ASTPtr query_ptr = query_ptr_->clone();
    ASTQueryWithOutput::resetOutputASTIfExist(*query_ptr);

    // XXX: serious design flaw since `ASTQueryWithOnCluster` is not inherited from `IAST`!
    auto * query = dynamic_cast<ASTQueryWithOnCluster *>(query_ptr.get());
    if (!query)
    {
        throw Exception("Distributed execution is not supported for such DDL queries", ErrorCodes::NOT_IMPLEMENTED);
    }

    if (!context.getSettingsRef().allow_distributed_ddl)
        throw Exception("Distributed DDL queries are prohibited for the user", ErrorCodes::QUERY_IS_PROHIBITED);

    if (const auto * query_alter = query_ptr->as<ASTAlterQuery>())
    {
79
        for (const auto & command : query_alter->command_list->children)
A
Alexander Tokmakov 已提交
80
        {
81
            if (!isSupportedAlterType(command->as<ASTAlterCommand&>().type))
A
Alexander Tokmakov 已提交
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
                throw Exception("Unsupported type of ALTER query", ErrorCodes::NOT_IMPLEMENTED);
        }
    }

    query->cluster = context.getMacros()->expand(query->cluster);
    ClusterPtr cluster = context.getCluster(query->cluster);
    DDLWorker & ddl_worker = context.getDDLWorker();

    /// Enumerate hosts which will be used to send query.
    Cluster::AddressesWithFailover shards = cluster->getShardsAddresses();
    std::vector<HostID> hosts;
    for (const auto & shard : shards)
    {
        for (const auto & addr : shard)
            hosts.emplace_back(addr);
    }

    if (hosts.empty())
        throw Exception("No hosts defined to execute distributed DDL query", ErrorCodes::LOGICAL_ERROR);

    /// The current database in a distributed query need to be replaced with either
    /// the local current database or a shard's default database.
    bool need_replace_current_database
        = (std::find_if(
            query_requires_access.begin(),
            query_requires_access.end(),
            [](const AccessRightsElement & elem) { return elem.isEmptyDatabase(); })
           != query_requires_access.end());

    bool use_local_default_database = false;
    const String & current_database = context.getCurrentDatabase();

    if (need_replace_current_database)
    {
        Strings shard_default_databases;
        for (const auto & shard : shards)
        {
            for (const auto & addr : shard)
            {
                if (!addr.default_database.empty())
                    shard_default_databases.push_back(addr.default_database);
                else
                    use_local_default_database = true;
            }
        }
        std::sort(shard_default_databases.begin(), shard_default_databases.end());
        shard_default_databases.erase(std::unique(shard_default_databases.begin(), shard_default_databases.end()), shard_default_databases.end());
        assert(use_local_default_database || !shard_default_databases.empty());

        if (use_local_default_database && !shard_default_databases.empty())
            throw Exception("Mixed local default DB and shard default DB in DDL query", ErrorCodes::NOT_IMPLEMENTED);

        if (use_local_default_database)
        {
            query_requires_access.replaceEmptyDatabase(current_database);
        }
        else
        {
            for (size_t i = 0; i != query_requires_access.size();)
            {
                auto & element = query_requires_access[i];
                if (element.isEmptyDatabase())
                {
                    query_requires_access.insert(query_requires_access.begin() + i + 1, shard_default_databases.size() - 1, element);
                    for (size_t j = 0; j != shard_default_databases.size(); ++j)
                        query_requires_access[i + j].replaceEmptyDatabase(shard_default_databases[j]);
                    i += shard_default_databases.size();
                }
                else
                    ++i;
            }
        }
    }

    AddDefaultDatabaseVisitor visitor(current_database, !use_local_default_database);
    visitor.visitDDL(query_ptr);

    /// Check access rights, assume that all servers have the same users config
160
    context.checkAccess(query_requires_access);
A
Alexander Tokmakov 已提交
161 162 163 164 165

    DDLLogEntry entry;
    entry.hosts = std::move(hosts);
    entry.query = queryToString(query_ptr);
    entry.initiator = ddl_worker.getCommonHostID();
166
    entry.setSettingsIfRequired(context);
A
Alexander Tokmakov 已提交
167 168
    String node_path = ddl_worker.enqueueQuery(entry);

169 170 171 172 173
    return getDistributedDDLStatus(node_path, entry, context);
}

BlockIO getDistributedDDLStatus(const String & node_path, const DDLLogEntry & entry, const Context & context, const std::optional<Strings> & hosts_to_wait)
{
A
Alexander Tokmakov 已提交
174 175 176 177
    BlockIO io;
    if (context.getSettingsRef().distributed_ddl_task_timeout == 0)
        return io;

178 179 180 181 182 183 184 185 186 187 188
    auto stream = std::make_shared<DDLQueryStatusInputStream>(node_path, entry, context, hosts_to_wait);
    if (context.getSettingsRef().distributed_ddl_output_mode == DistributedDDLOutputMode::NONE)
    {
        /// Wait for query to finish, but ignore output
        NullBlockOutputStream output{Block{}};
        copyData(*stream, output);
    }
    else
    {
        io.in = std::move(stream);
    }
A
Alexander Tokmakov 已提交
189 190 191
    return io;
}

192 193
DDLQueryStatusInputStream::DDLQueryStatusInputStream(const String & zk_node_path, const DDLLogEntry & entry, const Context & context_,
                                                     const std::optional<Strings> & hosts_to_wait)
A
Alexander Tokmakov 已提交
194 195 196 197 198
    : node_path(zk_node_path)
    , context(context_)
    , watch(CLOCK_MONOTONIC_COARSE)
    , log(&Poco::Logger::get("DDLQueryStatusInputStream"))
{
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
    if (context.getSettingsRef().distributed_ddl_output_mode == DistributedDDLOutputMode::THROW ||
        context.getSettingsRef().distributed_ddl_output_mode == DistributedDDLOutputMode::NONE)
        throw_on_timeout = true;
    else if (context.getSettingsRef().distributed_ddl_output_mode == DistributedDDLOutputMode::NULL_STATUS_ON_TIMEOUT ||
             context.getSettingsRef().distributed_ddl_output_mode == DistributedDDLOutputMode::NEVER_THROW)
        throw_on_timeout = false;
    else
        throw Exception(ErrorCodes::LOGICAL_ERROR, "Unknown output mode");

    auto maybe_make_nullable = [&](const DataTypePtr & type) -> DataTypePtr
    {
        if (throw_on_timeout)
            return type;
        return std::make_shared<DataTypeNullable>(type);
    };

A
Alexander Tokmakov 已提交
215
    sample = Block{
216 217 218 219 220 221
        {std::make_shared<DataTypeString>(),                         "host"},
        {std::make_shared<DataTypeUInt16>(),                         "port"},
        {maybe_make_nullable(std::make_shared<DataTypeInt64>()),     "status"},
        {maybe_make_nullable(std::make_shared<DataTypeString>()),    "error"},
        {std::make_shared<DataTypeUInt64>(),                         "num_hosts_remaining"},
        {std::make_shared<DataTypeUInt64>(),                         "num_hosts_active"},
A
Alexander Tokmakov 已提交
222 223
    };

224 225 226
    if (hosts_to_wait)
    {
        waiting_hosts = NameSet(hosts_to_wait->begin(), hosts_to_wait->end());
A
Alexander Tokmakov 已提交
227
        by_hostname = false;
A
fix  
Alexander Tokmakov 已提交
228
        sample.erase("port");
229 230 231 232 233 234
    }
    else
    {
        for (const HostID & host : entry.hosts)
            waiting_hosts.emplace(host.toString());
    }
A
Alexander Tokmakov 已提交
235

236
    addTotalRowsApprox(waiting_hosts.size());
A
Alexander Tokmakov 已提交
237 238

    timeout_seconds = context.getSettingsRef().distributed_ddl_task_timeout;
239 240 241 242 243 244 245 246 247 248 249 250 251
}

std::pair<String, UInt16> DDLQueryStatusInputStream::parseHostAndPort(const String & host_id) const
{
    String host = host_id;
    UInt16 port = 0;
    if (by_hostname)
    {
        auto host_and_port = Cluster::Address::fromString(host_id);
        host = host_and_port.first;
        port = host_and_port.second;
    }
    return {host, port};
A
Alexander Tokmakov 已提交
252 253 254 255 256
}

Block DDLQueryStatusInputStream::readImpl()
{
    Block res;
257 258 259 260
    bool all_hosts_finished = num_hosts_finished >= waiting_hosts.size();
    /// Seems like num_hosts_finished cannot be strictly greater than waiting_hosts.size()
    assert(num_hosts_finished <= waiting_hosts.size());
    if (all_hosts_finished || timeout_exceeded)
A
Alexander Tokmakov 已提交
261
    {
262 263
        bool throw_if_error_on_host = context.getSettingsRef().distributed_ddl_output_mode != DistributedDDLOutputMode::NEVER_THROW;
        if (first_exception && throw_if_error_on_host)
A
Alexander Tokmakov 已提交
264 265 266 267 268 269 270 271 272 273 274 275
            throw Exception(*first_exception);

        return res;
    }

    auto zookeeper = context.getZooKeeper();
    size_t try_number = 0;

    while (res.rows() == 0)
    {
        if (isCancelled())
        {
276 277
            bool throw_if_error_on_host = context.getSettingsRef().distributed_ddl_output_mode != DistributedDDLOutputMode::NEVER_THROW;
            if (first_exception && throw_if_error_on_host)
A
Alexander Tokmakov 已提交
278 279 280 281 282
                throw Exception(*first_exception);

            return res;
        }

283
        if (timeout_seconds >= 0 && watch.elapsedSeconds() > timeout_seconds)
A
Alexander Tokmakov 已提交
284 285 286 287
        {
            size_t num_unfinished_hosts = waiting_hosts.size() - num_hosts_finished;
            size_t num_active_hosts = current_active_hosts.size();

288 289 290 291 292 293 294 295 296
            constexpr const char * msg_format = "Watching task {} is executing longer than distributed_ddl_task_timeout (={}) seconds. "
                                                "There are {} unfinished hosts ({} of them are currently active), "
                                                "they are going to execute the query in background";
            if (throw_on_timeout)
                throw Exception(ErrorCodes::TIMEOUT_EXCEEDED, msg_format,
                                node_path, timeout_seconds, num_unfinished_hosts, num_active_hosts);

            timeout_exceeded = true;
            LOG_INFO(log, msg_format, node_path, timeout_seconds, num_unfinished_hosts, num_active_hosts);
A
Alexander Tokmakov 已提交
297

298 299 300 301 302 303 304 305 306
            NameSet unfinished_hosts = waiting_hosts;
            for (const auto & host_id : finished_hosts)
                unfinished_hosts.erase(host_id);

            /// Query is not finished on the rest hosts, so fill the corresponding rows with NULLs.
            MutableColumns columns = sample.cloneEmptyColumns();
            for (const String & host_id : unfinished_hosts)
            {
                auto [host, port] = parseHostAndPort(host_id);
A
fix  
Alexander Tokmakov 已提交
307 308 309 310 311 312 313 314
                size_t num = 0;
                columns[num++]->insert(host);
                if (by_hostname)
                    columns[num++]->insert(port);
                columns[num++]->insert(Field{});
                columns[num++]->insert(Field{});
                columns[num++]->insert(num_unfinished_hosts);
                columns[num++]->insert(num_active_hosts);
315 316 317
            }
            res = sample.cloneWithColumns(std::move(columns));
            return res;
A
Alexander Tokmakov 已提交
318 319 320 321 322 323 324 325 326 327 328 329 330 331
        }

        if (num_hosts_finished != 0 || try_number != 0)
        {
            sleepForMilliseconds(std::min<size_t>(1000, 50 * (try_number + 1)));
        }

        if (!zookeeper->exists(node_path))
        {
            throw Exception(ErrorCodes::UNFINISHED,
                            "Cannot provide query execution status. The query's node {} has been deleted by the cleaner since it was finished (or its lifetime is expired)",
                            node_path);
        }

332
        Strings new_hosts = getNewAndUpdate(getChildrenAllowNoNode(zookeeper, fs::path(node_path) / "finished"));
A
Alexander Tokmakov 已提交
333 334 335 336
        ++try_number;
        if (new_hosts.empty())
            continue;

337
        current_active_hosts = getChildrenAllowNoNode(zookeeper, fs::path(node_path) / "active");
A
Alexander Tokmakov 已提交
338 339 340 341 342 343 344

        MutableColumns columns = sample.cloneEmptyColumns();
        for (const String & host_id : new_hosts)
        {
            ExecutionStatus status(-1, "Cannot obtain error message");
            {
                String status_data;
345
                if (zookeeper->tryGet(fs::path(node_path) / "finished" / host_id, status_data))
A
Alexander Tokmakov 已提交
346 347 348
                    status.tryDeserializeText(status_data);
            }

349
            auto [host, port] = parseHostAndPort(host_id);
A
Alexander Tokmakov 已提交
350 351 352 353 354 355

            if (status.code != 0 && first_exception == nullptr)
                first_exception = std::make_unique<Exception>(status.code, "There was an error on [{}:{}]: {}", host, port, status.message);

            ++num_hosts_finished;

A
fix  
Alexander Tokmakov 已提交
356 357 358 359 360 361 362 363
            size_t num = 0;
            columns[num++]->insert(host);
            if (by_hostname)
                columns[num++]->insert(port);
            columns[num++]->insert(status.code);
            columns[num++]->insert(status.message);
            columns[num++]->insert(waiting_hosts.size() - num_hosts_finished);
            columns[num++]->insert(current_active_hosts.size());
A
Alexander Tokmakov 已提交
364 365 366 367
        }
        res = sample.cloneWithColumns(std::move(columns));
    }

A
Alexander Tokmakov 已提交
368
    return res;
A
Alexander Tokmakov 已提交
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
}

Strings DDLQueryStatusInputStream::getChildrenAllowNoNode(const std::shared_ptr<zkutil::ZooKeeper> & zookeeper, const String & node_path)
{
    Strings res;
    Coordination::Error code = zookeeper->tryGetChildren(node_path, res);
    if (code != Coordination::Error::ZOK && code != Coordination::Error::ZNONODE)
        throw Coordination::Exception(code, node_path);
    return res;
}

Strings DDLQueryStatusInputStream::getNewAndUpdate(const Strings & current_list_of_finished_hosts)
{
    Strings diff;
    for (const String & host : current_list_of_finished_hosts)
    {
        if (!waiting_hosts.count(host))
        {
            if (!ignoring_hosts.count(host))
            {
                ignoring_hosts.emplace(host);
                LOG_INFO(log, "Unexpected host {} appeared  in task {}", host, node_path);
            }
            continue;
        }

        if (!finished_hosts.count(host))
        {
            diff.emplace_back(host);
            finished_hosts.emplace(host);
        }
    }

    return diff;
}


}