Coverage Report

Created: 2025-04-29 17:56

/root/doris/be/src/runtime/fragment_mgr.cpp
Line
Count
Source (jump to first uncovered line)
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "runtime/fragment_mgr.h"
19
20
#include <brpc/controller.h>
21
#include <bvar/latency_recorder.h>
22
#include <exprs/runtime_filter.h>
23
#include <fmt/format.h>
24
#include <gen_cpp/DorisExternalService_types.h>
25
#include <gen_cpp/FrontendService.h>
26
#include <gen_cpp/FrontendService_types.h>
27
#include <gen_cpp/HeartbeatService_types.h>
28
#include <gen_cpp/Metrics_types.h>
29
#include <gen_cpp/PaloInternalService_types.h>
30
#include <gen_cpp/PlanNodes_types.h>
31
#include <gen_cpp/Planner_types.h>
32
#include <gen_cpp/QueryPlanExtra_types.h>
33
#include <gen_cpp/Types_types.h>
34
#include <gen_cpp/internal_service.pb.h>
35
#include <gen_cpp/types.pb.h>
36
#include <pthread.h>
37
#include <stddef.h>
38
#include <sys/time.h>
39
#include <thrift/TApplicationException.h>
40
#include <thrift/Thrift.h>
41
#include <thrift/protocol/TDebugProtocol.h>
42
#include <thrift/transport/TTransportException.h>
43
#include <time.h>
44
45
#include <algorithm>
46
#include <atomic>
47
48
#include "common/status.h"
49
#include "pipeline/pipeline_x/pipeline_x_fragment_context.h"
50
// IWYU pragma: no_include <bits/chrono.h>
51
#include <chrono> // IWYU pragma: keep
52
#include <cstdint>
53
#include <map>
54
#include <memory>
55
#include <mutex>
56
#include <sstream>
57
#include <unordered_map>
58
#include <unordered_set>
59
#include <utility>
60
61
#include "common/config.h"
62
#include "common/logging.h"
63
#include "common/object_pool.h"
64
#include "common/utils.h"
65
#include "gutil/strings/substitute.h"
66
#include "io/fs/stream_load_pipe.h"
67
#include "pipeline/pipeline_fragment_context.h"
68
#include "runtime/client_cache.h"
69
#include "runtime/descriptors.h"
70
#include "runtime/exec_env.h"
71
#include "runtime/frontend_info.h"
72
#include "runtime/memory/mem_tracker_limiter.h"
73
#include "runtime/plan_fragment_executor.h"
74
#include "runtime/primitive_type.h"
75
#include "runtime/query_context.h"
76
#include "runtime/runtime_filter_mgr.h"
77
#include "runtime/runtime_query_statistics_mgr.h"
78
#include "runtime/runtime_state.h"
79
#include "runtime/stream_load/new_load_stream_mgr.h"
80
#include "runtime/stream_load/stream_load_context.h"
81
#include "runtime/stream_load/stream_load_executor.h"
82
#include "runtime/thread_context.h"
83
#include "runtime/types.h"
84
#include "runtime/workload_group/workload_group.h"
85
#include "runtime/workload_group/workload_group_manager.h"
86
#include "runtime/workload_management/workload_query_info.h"
87
#include "service/backend_options.h"
88
#include "util/brpc_client_cache.h"
89
#include "util/debug_points.h"
90
#include "util/debug_util.h"
91
#include "util/doris_metrics.h"
92
#include "util/hash_util.hpp"
93
#include "util/mem_info.h"
94
#include "util/network_util.h"
95
#include "util/pretty_printer.h"
96
#include "util/runtime_profile.h"
97
#include "util/thread.h"
98
#include "util/threadpool.h"
99
#include "util/thrift_util.h"
100
#include "util/uid_util.h"
101
#include "util/url_coding.h"
102
#include "vec/runtime/shared_hash_table_controller.h"
103
#include "vec/runtime/vdatetime_value.h"
104
105
namespace doris {
106
107
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(fragment_instance_count, MetricUnit::NOUNIT);
108
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(timeout_canceled_fragment_count, MetricUnit::NOUNIT);
109
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(fragment_thread_pool_queue_size, MetricUnit::NOUNIT);
110
bvar::LatencyRecorder g_fragmentmgr_prepare_latency("doris_FragmentMgr", "prepare");
111
bvar::Adder<int64_t> g_pipeline_fragment_instances_count("doris_pipeline_fragment_instances_count");
112
113
0
std::string to_load_error_http_path(const std::string& file_name) {
114
0
    if (file_name.empty()) {
115
0
        return "";
116
0
    }
117
0
    std::stringstream url;
118
0
    url << "http://" << get_host_port(BackendOptions::get_localhost(), config::webserver_port)
119
0
        << "/api/_load_error_log?"
120
0
        << "file=" << file_name;
121
0
    return url.str();
122
0
}
123
124
using apache::thrift::TException;
125
using apache::thrift::transport::TTransportException;
126
127
static Status _do_fetch_running_queries_rpc(const FrontendInfo& fe_info,
128
0
                                            std::unordered_set<TUniqueId>& query_set) {
129
0
    TFetchRunningQueriesResult rpc_result;
130
0
    TFetchRunningQueriesRequest rpc_request;
131
132
0
    Status client_status;
133
0
    const int32 timeout_ms = 3 * 1000;
134
0
    FrontendServiceConnection rpc_client(ExecEnv::GetInstance()->frontend_client_cache(),
135
0
                                         fe_info.info.coordinator_address, timeout_ms,
136
0
                                         &client_status);
137
    // Abort this fe.
138
0
    if (!client_status.ok()) {
139
0
        LOG_WARNING("Failed to get client for {}, reason is {}",
140
0
                    PrintThriftNetworkAddress(fe_info.info.coordinator_address),
141
0
                    client_status.to_string());
142
0
        return Status::InternalError("Failed to get client for {}, reason is {}",
143
0
                                     PrintThriftNetworkAddress(fe_info.info.coordinator_address),
144
0
                                     client_status.to_string());
145
0
    }
146
147
    // do rpc
148
0
    try {
149
0
        try {
150
0
            rpc_client->fetchRunningQueries(rpc_result, rpc_request);
151
0
        } catch (const apache::thrift::transport::TTransportException& e) {
152
0
            LOG_WARNING("Transport exception reason: {}, reopening", e.what());
153
0
            client_status = rpc_client.reopen(config::thrift_rpc_timeout_ms);
154
0
            if (!client_status.ok()) {
155
0
                LOG_WARNING("Reopen failed, reason: {}", client_status.to_string_no_stack());
156
0
                return Status::InternalError("Reopen failed, reason: {}",
157
0
                                             client_status.to_string_no_stack());
158
0
            }
159
160
0
            rpc_client->fetchRunningQueries(rpc_result, rpc_request);
161
0
        }
162
0
    } catch (apache::thrift::TException& e) {
163
        // During upgrading cluster or meet any other network error.
164
0
        LOG_WARNING("Failed to fetch running queries from {}, reason: {}",
165
0
                    PrintThriftNetworkAddress(fe_info.info.coordinator_address), e.what());
166
0
        return Status::InternalError("Failed to fetch running queries from {}, reason: {}",
167
0
                                     PrintThriftNetworkAddress(fe_info.info.coordinator_address),
168
0
                                     e.what());
169
0
    }
170
171
    // Avoid logic error in frontend.
172
0
    if (rpc_result.__isset.status == false || rpc_result.status.status_code != TStatusCode::OK) {
173
0
        LOG_WARNING("Failed to fetch running queries from {}, reason: {}",
174
0
                    PrintThriftNetworkAddress(fe_info.info.coordinator_address),
175
0
                    doris::to_string(rpc_result.status.status_code));
176
0
        return Status::InternalError("Failed to fetch running queries from {}, reason: {}",
177
0
                                     PrintThriftNetworkAddress(fe_info.info.coordinator_address),
178
0
                                     doris::to_string(rpc_result.status.status_code));
179
0
    }
180
181
0
    if (rpc_result.__isset.running_queries == false) {
182
0
        return Status::InternalError("Failed to fetch running queries from {}, reason: {}",
183
0
                                     PrintThriftNetworkAddress(fe_info.info.coordinator_address),
184
0
                                     "running_queries is not set");
185
0
    }
186
187
0
    query_set = std::unordered_set<TUniqueId>(rpc_result.running_queries.begin(),
188
0
                                              rpc_result.running_queries.end());
189
190
0
    return Status::OK();
191
0
};
192
193
0
static std::map<int64_t, std::unordered_set<TUniqueId>> _get_all_running_queries_from_fe() {
194
0
    const std::map<TNetworkAddress, FrontendInfo>& running_fes =
195
0
            ExecEnv::GetInstance()->get_running_frontends();
196
197
0
    std::map<int64_t, std::unordered_set<TUniqueId>> result;
198
0
    std::vector<FrontendInfo> qualified_fes;
199
200
0
    for (const auto& fe : running_fes) {
201
        // Only consider normal frontend.
202
0
        if (fe.first.port != 0 && fe.second.info.process_uuid != 0) {
203
0
            qualified_fes.push_back(fe.second);
204
0
        } else {
205
0
            return {};
206
0
        }
207
0
    }
208
209
0
    for (const auto& fe_addr : qualified_fes) {
210
0
        const int64_t process_uuid = fe_addr.info.process_uuid;
211
0
        std::unordered_set<TUniqueId> query_set;
212
0
        Status st = _do_fetch_running_queries_rpc(fe_addr, query_set);
213
0
        if (!st.ok()) {
214
            // Empty result, cancel worker will not do anything
215
0
            return {};
216
0
        }
217
218
        // frontend_info and process_uuid has been checked in rpc threads.
219
0
        result[process_uuid] = query_set;
220
0
    }
221
222
0
    return result;
223
0
}
224
225
2
inline uint32_t get_map_id(const TUniqueId& query_id, size_t capacity) {
226
2
    uint32_t value = HashUtil::hash(&query_id.lo, 8, 0);
227
2
    value = HashUtil::hash(&query_id.hi, 8, value);
228
2
    return value % capacity;
229
2
}
230
231
0
inline uint32_t get_map_id(std::pair<TUniqueId, int> key, size_t capacity) {
232
0
    uint32_t value = HashUtil::hash(&key.first.lo, 8, 0);
233
0
    value = HashUtil::hash(&key.first.hi, 8, value);
234
0
    return value % capacity;
235
0
}
236
237
template <typename Key, typename Value, typename ValueType>
238
12
ConcurrentContextMap<Key, Value, ValueType>::ConcurrentContextMap() {
239
12
    _internal_map.resize(config::num_query_ctx_map_partitions);
240
1.54k
    for (size_t i = 0; i < config::num_query_ctx_map_partitions; i++) {
241
1.53k
        _internal_map[i] = {std::make_unique<std::shared_mutex>(),
242
1.53k
                            phmap::flat_hash_map<Key, Value>()};
243
1.53k
    }
244
12
}
_ZN5doris20ConcurrentContextMapINS_9TUniqueIdESt10shared_ptrINS_20PlanFragmentExecutorEES3_EC2Ev
Line
Count
Source
238
4
ConcurrentContextMap<Key, Value, ValueType>::ConcurrentContextMap() {
239
4
    _internal_map.resize(config::num_query_ctx_map_partitions);
240
516
    for (size_t i = 0; i < config::num_query_ctx_map_partitions; i++) {
241
512
        _internal_map[i] = {std::make_unique<std::shared_mutex>(),
242
512
                            phmap::flat_hash_map<Key, Value>()};
243
512
    }
244
4
}
_ZN5doris20ConcurrentContextMapINS_9TUniqueIdESt10shared_ptrINS_8pipeline23PipelineFragmentContextEES4_EC2Ev
Line
Count
Source
238
4
ConcurrentContextMap<Key, Value, ValueType>::ConcurrentContextMap() {
239
4
    _internal_map.resize(config::num_query_ctx_map_partitions);
240
516
    for (size_t i = 0; i < config::num_query_ctx_map_partitions; i++) {
241
512
        _internal_map[i] = {std::make_unique<std::shared_mutex>(),
242
512
                            phmap::flat_hash_map<Key, Value>()};
243
512
    }
244
4
}
_ZN5doris20ConcurrentContextMapINS_9TUniqueIdESt10shared_ptrINS_12QueryContextEES3_EC2Ev
Line
Count
Source
238
4
ConcurrentContextMap<Key, Value, ValueType>::ConcurrentContextMap() {
239
4
    _internal_map.resize(config::num_query_ctx_map_partitions);
240
516
    for (size_t i = 0; i < config::num_query_ctx_map_partitions; i++) {
241
512
        _internal_map[i] = {std::make_unique<std::shared_mutex>(),
242
512
                            phmap::flat_hash_map<Key, Value>()};
243
512
    }
244
4
}
245
246
template <typename Key, typename Value, typename ValueType>
247
2
Value ConcurrentContextMap<Key, Value, ValueType>::find(const Key& query_id) {
248
2
    auto id = get_map_id(query_id, _internal_map.size());
249
2
    {
250
2
        std::shared_lock lock(*_internal_map[id].first);
251
2
        auto& map = _internal_map[id].second;
252
2
        auto search = map.find(query_id);
253
2
        if (search != map.end()) {
254
0
            return search->second;
255
0
        }
256
2
        return std::shared_ptr<ValueType>(nullptr);
257
2
    }
258
2
}
Unexecuted instantiation: _ZN5doris20ConcurrentContextMapINS_9TUniqueIdESt10shared_ptrINS_12QueryContextEES3_E4findERKS1_
_ZN5doris20ConcurrentContextMapINS_9TUniqueIdESt10shared_ptrINS_20PlanFragmentExecutorEES3_E4findERKS1_
Line
Count
Source
247
1
Value ConcurrentContextMap<Key, Value, ValueType>::find(const Key& query_id) {
248
1
    auto id = get_map_id(query_id, _internal_map.size());
249
1
    {
250
1
        std::shared_lock lock(*_internal_map[id].first);
251
1
        auto& map = _internal_map[id].second;
252
1
        auto search = map.find(query_id);
253
1
        if (search != map.end()) {
254
0
            return search->second;
255
0
        }
256
1
        return std::shared_ptr<ValueType>(nullptr);
257
1
    }
258
1
}
_ZN5doris20ConcurrentContextMapINS_9TUniqueIdESt10shared_ptrINS_8pipeline23PipelineFragmentContextEES4_E4findERKS1_
Line
Count
Source
247
1
Value ConcurrentContextMap<Key, Value, ValueType>::find(const Key& query_id) {
248
1
    auto id = get_map_id(query_id, _internal_map.size());
249
1
    {
250
1
        std::shared_lock lock(*_internal_map[id].first);
251
1
        auto& map = _internal_map[id].second;
252
1
        auto search = map.find(query_id);
253
1
        if (search != map.end()) {
254
0
            return search->second;
255
0
        }
256
1
        return std::shared_ptr<ValueType>(nullptr);
257
1
    }
258
1
}
259
260
template <typename Key, typename Value, typename ValueType>
261
Status ConcurrentContextMap<Key, Value, ValueType>::apply_if_not_exists(
262
0
        const Key& query_id, std::shared_ptr<ValueType>& query_ctx, ApplyFunction&& function) {
263
0
    auto id = get_map_id(query_id, _internal_map.size());
264
0
    {
265
0
        std::unique_lock lock(*_internal_map[id].first);
266
0
        auto& map = _internal_map[id].second;
267
0
        auto search = map.find(query_id);
268
0
        if (search != map.end()) {
269
0
            query_ctx = search->second;
270
0
        }
271
0
        if (!query_ctx) {
272
0
            return function(map);
273
0
        }
274
0
        return Status::OK();
275
0
    }
276
0
}
277
278
template <typename Key, typename Value, typename ValueType>
279
0
void ConcurrentContextMap<Key, Value, ValueType>::erase(const Key& query_id) {
280
0
    auto id = get_map_id(query_id, _internal_map.size());
281
0
    {
282
0
        std::unique_lock lock(*_internal_map[id].first);
283
0
        auto& map = _internal_map[id].second;
284
0
        map.erase(query_id);
285
0
    }
286
0
}
Unexecuted instantiation: _ZN5doris20ConcurrentContextMapINS_9TUniqueIdESt10shared_ptrINS_20PlanFragmentExecutorEES3_E5eraseERKS1_
Unexecuted instantiation: _ZN5doris20ConcurrentContextMapINS_9TUniqueIdESt10shared_ptrINS_12QueryContextEES3_E5eraseERKS1_
Unexecuted instantiation: _ZN5doris20ConcurrentContextMapINS_9TUniqueIdESt10shared_ptrINS_8pipeline23PipelineFragmentContextEES4_E5eraseERKS1_
287
288
template <typename Key, typename Value, typename ValueType>
289
void ConcurrentContextMap<Key, Value, ValueType>::insert(const Key& query_id,
290
0
                                                         std::shared_ptr<ValueType> query_ctx) {
291
0
    auto id = get_map_id(query_id, _internal_map.size());
292
0
    {
293
0
        std::unique_lock lock(*_internal_map[id].first);
294
0
        auto& map = _internal_map[id].second;
295
0
        map.insert({query_id, query_ctx});
296
0
    }
297
0
}
Unexecuted instantiation: _ZN5doris20ConcurrentContextMapINS_9TUniqueIdESt10shared_ptrINS_20PlanFragmentExecutorEES3_E6insertERKS1_S4_
Unexecuted instantiation: _ZN5doris20ConcurrentContextMapINS_9TUniqueIdESt10shared_ptrINS_8pipeline23PipelineFragmentContextEES4_E6insertERKS1_S5_
298
299
template <typename Key, typename Value, typename ValueType>
300
12
void ConcurrentContextMap<Key, Value, ValueType>::clear() {
301
1.53k
    for (auto& pair : _internal_map) {
302
1.53k
        std::unique_lock lock(*pair.first);
303
1.53k
        auto& map = pair.second;
304
1.53k
        map.clear();
305
1.53k
    }
306
12
}
_ZN5doris20ConcurrentContextMapINS_9TUniqueIdESt10shared_ptrINS_20PlanFragmentExecutorEES3_E5clearEv
Line
Count
Source
300
4
void ConcurrentContextMap<Key, Value, ValueType>::clear() {
301
512
    for (auto& pair : _internal_map) {
302
512
        std::unique_lock lock(*pair.first);
303
512
        auto& map = pair.second;
304
512
        map.clear();
305
512
    }
306
4
}
_ZN5doris20ConcurrentContextMapINS_9TUniqueIdESt10shared_ptrINS_8pipeline23PipelineFragmentContextEES4_E5clearEv
Line
Count
Source
300
4
void ConcurrentContextMap<Key, Value, ValueType>::clear() {
301
512
    for (auto& pair : _internal_map) {
302
512
        std::unique_lock lock(*pair.first);
303
512
        auto& map = pair.second;
304
512
        map.clear();
305
512
    }
306
4
}
_ZN5doris20ConcurrentContextMapINS_9TUniqueIdESt10shared_ptrINS_12QueryContextEES3_E5clearEv
Line
Count
Source
300
4
void ConcurrentContextMap<Key, Value, ValueType>::clear() {
301
512
    for (auto& pair : _internal_map) {
302
512
        std::unique_lock lock(*pair.first);
303
512
        auto& map = pair.second;
304
512
        map.clear();
305
512
    }
306
4
}
307
308
FragmentMgr::FragmentMgr(ExecEnv* exec_env)
309
4
        : _exec_env(exec_env), _stop_background_threads_latch(1) {
310
4
    _entity = DorisMetrics::instance()->metric_registry()->register_entity("FragmentMgr");
311
4
    INT_UGAUGE_METRIC_REGISTER(_entity, timeout_canceled_fragment_count);
312
4
    REGISTER_HOOK_METRIC(fragment_instance_count,
313
4
                         [this]() { return _fragment_instance_map.num_items(); });
314
315
4
    auto s = Thread::create(
316
4
            "FragmentMgr", "cancel_timeout_plan_fragment", [this]() { this->cancel_worker(); },
317
4
            &_cancel_thread);
318
4
    CHECK(s.ok()) << s.to_string();
319
320
    // TODO(zc): we need a better thread-pool
321
    // now one user can use all the thread pool, others have no resource.
322
4
    s = ThreadPoolBuilder("FragmentMgrThreadPool")
323
4
                .set_min_threads(config::fragment_pool_thread_num_min)
324
4
                .set_max_threads(config::fragment_pool_thread_num_max)
325
4
                .set_max_queue_size(config::fragment_pool_queue_size)
326
4
                .build(&_thread_pool);
327
328
4
    REGISTER_HOOK_METRIC(fragment_thread_pool_queue_size,
329
4
                         [this]() { return _thread_pool->get_queue_size(); });
330
4
    CHECK(s.ok()) << s.to_string();
331
332
4
    s = ThreadPoolBuilder("FragmentInstanceReportThreadPool")
333
4
                .set_min_threads(48)
334
4
                .set_max_threads(512)
335
4
                .set_max_queue_size(102400)
336
4
                .build(&_async_report_thread_pool);
337
4
    CHECK(s.ok()) << s.to_string();
338
4
}
339
340
4
FragmentMgr::~FragmentMgr() = default;
341
342
4
void FragmentMgr::stop() {
343
4
    DEREGISTER_HOOK_METRIC(fragment_instance_count);
344
4
    DEREGISTER_HOOK_METRIC(fragment_thread_pool_queue_size);
345
4
    _stop_background_threads_latch.count_down();
346
4
    if (_cancel_thread) {
347
4
        _cancel_thread->join();
348
4
    }
349
    // Stop all the worker, should wait for a while?
350
    // _thread_pool->wait_for();
351
4
    _thread_pool->shutdown();
352
353
    // Only me can delete
354
4
    _fragment_instance_map.clear();
355
4
    _pipeline_map.apply(
356
4
            [&](phmap::flat_hash_map<TUniqueId, std::shared_ptr<pipeline::PipelineFragmentContext>>&
357
512
                        map) -> Status {
358
512
                for (auto& pipeline : map) {
359
0
                    pipeline.second->close_sink();
360
0
                }
361
512
                return Status::OK();
362
512
            });
363
4
    _pipeline_map.clear();
364
4
    _query_ctx_map.clear();
365
4
    _async_report_thread_pool->shutdown();
366
4
}
367
368
0
std::string FragmentMgr::to_http_path(const std::string& file_name) {
369
0
    std::stringstream url;
370
0
    url << "http://" << BackendOptions::get_localhost() << ":" << config::webserver_port
371
0
        << "/api/_download_load?"
372
0
        << "token=" << _exec_env->token() << "&file=" << file_name;
373
0
    return url.str();
374
0
}
375
376
Status FragmentMgr::trigger_pipeline_context_report(
377
0
        const ReportStatusRequest req, std::shared_ptr<pipeline::PipelineFragmentContext>&& ctx) {
378
0
    return _async_report_thread_pool->submit_func([this, req, ctx]() {
379
0
        SCOPED_ATTACH_TASK(ctx->get_query_ctx()->query_mem_tracker);
380
0
        coordinator_callback(req);
381
0
        if (!req.done) {
382
0
            ctx->refresh_next_report_time();
383
0
        }
384
0
    });
385
0
}
386
387
// There can only be one of these callbacks in-flight at any moment, because
388
// it is only invoked from the executor's reporting thread.
389
// Also, the reported status will always reflect the most recent execution status,
390
// including the final status when execution finishes.
391
0
void FragmentMgr::coordinator_callback(const ReportStatusRequest& req) {
392
0
    DCHECK(req.status.ok() || req.done); // if !status.ok() => done
393
0
    Status exec_status = req.update_fn(req.status);
394
0
    Status coord_status;
395
0
    FrontendServiceConnection coord(_exec_env->frontend_client_cache(), req.coord_addr,
396
0
                                    &coord_status);
397
0
    if (!coord_status.ok()) {
398
0
        std::stringstream ss;
399
0
        UniqueId uid(req.query_id.hi, req.query_id.lo);
400
0
        static_cast<void>(req.update_fn(Status::InternalError(
401
0
                "query_id: {}, couldn't get a client for {}, reason is {}", uid.to_string(),
402
0
                PrintThriftNetworkAddress(req.coord_addr), coord_status.to_string())));
403
0
        return;
404
0
    }
405
406
0
    TReportExecStatusParams params;
407
0
    params.protocol_version = FrontendServiceVersion::V1;
408
0
    params.__set_query_id(req.query_id);
409
0
    params.__set_backend_num(req.backend_num);
410
0
    params.__set_fragment_instance_id(req.fragment_instance_id);
411
0
    params.__set_fragment_id(req.fragment_id);
412
0
    params.__set_status(exec_status.to_thrift());
413
0
    params.__set_done(req.done);
414
0
    params.__set_query_type(req.runtime_state->query_type());
415
416
0
    DCHECK(req.runtime_state != nullptr);
417
418
0
    if (req.runtime_state->query_type() == TQueryType::LOAD && !req.done && req.status.ok()) {
419
        // this is a load plan, and load is not finished, just make a brief report
420
0
        params.__set_loaded_rows(req.runtime_state->num_rows_load_total());
421
0
        params.__set_loaded_bytes(req.runtime_state->num_bytes_load_total());
422
0
    } else {
423
0
        if (req.runtime_state->query_type() == TQueryType::LOAD) {
424
0
            params.__set_loaded_rows(req.runtime_state->num_rows_load_total());
425
0
            params.__set_loaded_bytes(req.runtime_state->num_bytes_load_total());
426
0
        }
427
0
        if (req.is_pipeline_x) {
428
0
            params.__isset.detailed_report = true;
429
0
            DCHECK(!req.runtime_states.empty());
430
0
            const bool enable_profile = (*req.runtime_states.begin())->enable_profile();
431
0
            if (enable_profile) {
432
0
                params.__isset.profile = true;
433
0
                params.__isset.loadChannelProfile = false;
434
0
                for (auto* rs : req.runtime_states) {
435
0
                    DCHECK(req.load_channel_profile);
436
0
                    TDetailedReportParams detailed_param;
437
0
                    rs->load_channel_profile()->to_thrift(&detailed_param.loadChannelProfile);
438
                    // merge all runtime_states.loadChannelProfile to req.load_channel_profile
439
0
                    req.load_channel_profile->update(detailed_param.loadChannelProfile);
440
0
                }
441
0
                req.load_channel_profile->to_thrift(&params.loadChannelProfile);
442
0
            } else {
443
0
                params.__isset.profile = false;
444
0
            }
445
446
0
            if (enable_profile) {
447
0
                DCHECK(req.profile != nullptr);
448
0
                TDetailedReportParams detailed_param;
449
0
                detailed_param.__isset.fragment_instance_id = false;
450
0
                detailed_param.__isset.profile = true;
451
0
                detailed_param.__isset.loadChannelProfile = false;
452
0
                detailed_param.__set_is_fragment_level(true);
453
0
                req.profile->to_thrift(&detailed_param.profile);
454
0
                params.detailed_report.push_back(detailed_param);
455
0
                for (auto& pipeline_profile : req.runtime_state->pipeline_id_to_profile()) {
456
0
                    TDetailedReportParams detailed_param;
457
0
                    detailed_param.__isset.fragment_instance_id = false;
458
0
                    detailed_param.__isset.profile = true;
459
0
                    detailed_param.__isset.loadChannelProfile = false;
460
0
                    pipeline_profile->to_thrift(&detailed_param.profile);
461
0
                    params.detailed_report.push_back(detailed_param);
462
0
                }
463
0
            }
464
0
        } else {
465
0
            if (req.profile != nullptr) {
466
0
                req.profile->to_thrift(&params.profile);
467
0
                if (req.load_channel_profile) {
468
0
                    req.load_channel_profile->to_thrift(&params.loadChannelProfile);
469
0
                }
470
0
                params.__isset.profile = true;
471
0
                params.__isset.loadChannelProfile = true;
472
0
            } else {
473
0
                params.__isset.profile = false;
474
0
            }
475
0
        }
476
477
0
        if (!req.runtime_state->output_files().empty()) {
478
0
            params.__isset.delta_urls = true;
479
0
            for (auto& it : req.runtime_state->output_files()) {
480
0
                params.delta_urls.push_back(to_http_path(it));
481
0
            }
482
0
        } else if (!req.runtime_states.empty()) {
483
0
            for (auto* rs : req.runtime_states) {
484
0
                for (auto& it : rs->output_files()) {
485
0
                    params.delta_urls.push_back(to_http_path(it));
486
0
                }
487
0
            }
488
0
            if (!params.delta_urls.empty()) {
489
0
                params.__isset.delta_urls = true;
490
0
            }
491
0
        }
492
493
        // load rows
494
0
        static std::string s_dpp_normal_all = "dpp.norm.ALL";
495
0
        static std::string s_dpp_abnormal_all = "dpp.abnorm.ALL";
496
0
        static std::string s_unselected_rows = "unselected.rows";
497
0
        int64_t num_rows_load_success = 0;
498
0
        int64_t num_rows_load_filtered = 0;
499
0
        int64_t num_rows_load_unselected = 0;
500
0
        if (req.runtime_state->num_rows_load_total() > 0 ||
501
0
            req.runtime_state->num_rows_load_filtered() > 0 ||
502
0
            req.runtime_state->num_finished_range() > 0) {
503
0
            params.__isset.load_counters = true;
504
505
0
            num_rows_load_success = req.runtime_state->num_rows_load_success();
506
0
            num_rows_load_filtered = req.runtime_state->num_rows_load_filtered();
507
0
            num_rows_load_unselected = req.runtime_state->num_rows_load_unselected();
508
0
            params.__isset.fragment_instance_reports = true;
509
0
            TFragmentInstanceReport t;
510
0
            t.__set_fragment_instance_id(req.runtime_state->fragment_instance_id());
511
0
            t.__set_num_finished_range(req.runtime_state->num_finished_range());
512
0
            t.__set_loaded_rows(req.runtime_state->num_rows_load_total());
513
0
            t.__set_loaded_bytes(req.runtime_state->num_bytes_load_total());
514
0
            params.fragment_instance_reports.push_back(t);
515
0
        } else if (!req.runtime_states.empty()) {
516
0
            for (auto* rs : req.runtime_states) {
517
0
                if (rs->num_rows_load_total() > 0 || rs->num_rows_load_filtered() > 0 ||
518
0
                    req.runtime_state->num_finished_range() > 0) {
519
0
                    params.__isset.load_counters = true;
520
0
                    num_rows_load_success += rs->num_rows_load_success();
521
0
                    num_rows_load_filtered += rs->num_rows_load_filtered();
522
0
                    num_rows_load_unselected += rs->num_rows_load_unselected();
523
0
                    params.__isset.fragment_instance_reports = true;
524
0
                    TFragmentInstanceReport t;
525
0
                    t.__set_fragment_instance_id(rs->fragment_instance_id());
526
0
                    t.__set_num_finished_range(rs->num_finished_range());
527
0
                    t.__set_loaded_rows(rs->num_rows_load_total());
528
0
                    t.__set_loaded_bytes(rs->num_bytes_load_total());
529
0
                    params.fragment_instance_reports.push_back(t);
530
0
                }
531
0
            }
532
0
        }
533
0
        params.load_counters.emplace(s_dpp_normal_all, std::to_string(num_rows_load_success));
534
0
        params.load_counters.emplace(s_dpp_abnormal_all, std::to_string(num_rows_load_filtered));
535
0
        params.load_counters.emplace(s_unselected_rows, std::to_string(num_rows_load_unselected));
536
537
0
        if (!req.runtime_state->get_error_log_file_path().empty()) {
538
0
            params.__set_tracking_url(
539
0
                    to_load_error_http_path(req.runtime_state->get_error_log_file_path()));
540
0
        } else if (!req.runtime_states.empty()) {
541
0
            for (auto* rs : req.runtime_states) {
542
0
                if (!rs->get_error_log_file_path().empty()) {
543
0
                    params.__set_tracking_url(
544
0
                            to_load_error_http_path(rs->get_error_log_file_path()));
545
0
                }
546
0
            }
547
0
        }
548
0
        if (!req.runtime_state->export_output_files().empty()) {
549
0
            params.__isset.export_files = true;
550
0
            params.export_files = req.runtime_state->export_output_files();
551
0
        } else if (!req.runtime_states.empty()) {
552
0
            for (auto* rs : req.runtime_states) {
553
0
                if (!rs->export_output_files().empty()) {
554
0
                    params.__isset.export_files = true;
555
0
                    params.export_files.insert(params.export_files.end(),
556
0
                                               rs->export_output_files().begin(),
557
0
                                               rs->export_output_files().end());
558
0
                }
559
0
            }
560
0
        }
561
0
        if (auto tci = req.runtime_state->tablet_commit_infos(); !tci.empty()) {
562
0
            params.__isset.commitInfos = true;
563
0
            params.commitInfos.insert(params.commitInfos.end(), tci.begin(), tci.end());
564
0
        } else if (!req.runtime_states.empty()) {
565
0
            for (auto* rs : req.runtime_states) {
566
0
                if (auto rs_tci = rs->tablet_commit_infos(); !rs_tci.empty()) {
567
0
                    params.__isset.commitInfos = true;
568
0
                    params.commitInfos.insert(params.commitInfos.end(), rs_tci.begin(),
569
0
                                              rs_tci.end());
570
0
                }
571
0
            }
572
0
        }
573
0
        if (auto eti = req.runtime_state->error_tablet_infos(); !eti.empty()) {
574
0
            params.__isset.errorTabletInfos = true;
575
0
            params.errorTabletInfos.insert(params.errorTabletInfos.end(), eti.begin(), eti.end());
576
0
        } else if (!req.runtime_states.empty()) {
577
0
            for (auto* rs : req.runtime_states) {
578
0
                if (auto rs_eti = rs->error_tablet_infos(); !rs_eti.empty()) {
579
0
                    params.__isset.errorTabletInfos = true;
580
0
                    params.errorTabletInfos.insert(params.errorTabletInfos.end(), rs_eti.begin(),
581
0
                                                   rs_eti.end());
582
0
                }
583
0
            }
584
0
        }
585
586
0
        if (auto hpu = req.runtime_state->hive_partition_updates(); !hpu.empty()) {
587
0
            params.__isset.hive_partition_updates = true;
588
0
            params.hive_partition_updates.insert(params.hive_partition_updates.end(), hpu.begin(),
589
0
                                                 hpu.end());
590
0
        } else if (!req.runtime_states.empty()) {
591
0
            for (auto* rs : req.runtime_states) {
592
0
                if (auto rs_hpu = rs->hive_partition_updates(); !rs_hpu.empty()) {
593
0
                    params.__isset.hive_partition_updates = true;
594
0
                    params.hive_partition_updates.insert(params.hive_partition_updates.end(),
595
0
                                                         rs_hpu.begin(), rs_hpu.end());
596
0
                }
597
0
            }
598
0
        }
599
0
        if (auto icd = req.runtime_state->iceberg_commit_datas(); !icd.empty()) {
600
0
            params.__isset.iceberg_commit_datas = true;
601
0
            params.iceberg_commit_datas.insert(params.iceberg_commit_datas.end(), icd.begin(),
602
0
                                               icd.end());
603
0
        } else if (!req.runtime_states.empty()) {
604
0
            for (auto* rs : req.runtime_states) {
605
0
                if (auto rs_icd = rs->iceberg_commit_datas(); !rs_icd.empty()) {
606
0
                    params.__isset.iceberg_commit_datas = true;
607
0
                    params.iceberg_commit_datas.insert(params.iceberg_commit_datas.end(),
608
0
                                                       rs_icd.begin(), rs_icd.end());
609
0
                }
610
0
            }
611
0
        }
612
613
        // Send new errors to coordinator
614
0
        req.runtime_state->get_unreported_errors(&(params.error_log));
615
0
        params.__isset.error_log = (params.error_log.size() > 0);
616
0
    }
617
618
0
    if (_exec_env->master_info()->__isset.backend_id) {
619
0
        params.__set_backend_id(_exec_env->master_info()->backend_id);
620
0
    }
621
622
0
    TReportExecStatusResult res;
623
0
    Status rpc_status;
624
625
0
    VLOG_DEBUG << "reportExecStatus params is "
626
0
               << apache::thrift::ThriftDebugString(params).c_str();
627
0
    if (!exec_status.ok()) {
628
0
        LOG(WARNING) << "report error status: " << exec_status.msg()
629
0
                     << " to coordinator: " << req.coord_addr
630
0
                     << ", query id: " << print_id(req.query_id)
631
0
                     << ", instance id: " << print_id(req.fragment_instance_id);
632
0
    }
633
0
    try {
634
0
        try {
635
0
            coord->reportExecStatus(res, params);
636
0
        } catch ([[maybe_unused]] TTransportException& e) {
637
#ifndef ADDRESS_SANITIZER
638
            LOG(WARNING) << "Retrying ReportExecStatus. query id: " << print_id(req.query_id)
639
                         << ", instance id: " << print_id(req.fragment_instance_id) << " to "
640
                         << req.coord_addr << ", err: " << e.what();
641
#endif
642
0
            rpc_status = coord.reopen();
643
644
0
            if (!rpc_status.ok()) {
645
                // we need to cancel the execution of this fragment
646
0
                static_cast<void>(req.update_fn(rpc_status));
647
0
                req.cancel_fn(PPlanFragmentCancelReason::INTERNAL_ERROR, "report rpc fail");
648
0
                return;
649
0
            }
650
0
            coord->reportExecStatus(res, params);
651
0
        }
652
653
0
        rpc_status = Status::create<false>(res.status);
654
0
    } catch (TException& e) {
655
0
        rpc_status = Status::InternalError("ReportExecStatus() to {} failed: {}",
656
0
                                           PrintThriftNetworkAddress(req.coord_addr), e.what());
657
0
    }
658
659
0
    if (!rpc_status.ok()) {
660
0
        LOG_INFO("Going to cancel instance {} since report exec status got rpc failed: {}",
661
0
                 print_id(req.fragment_instance_id), rpc_status.to_string());
662
        // we need to cancel the execution of this fragment
663
0
        static_cast<void>(req.update_fn(rpc_status));
664
0
        req.cancel_fn(PPlanFragmentCancelReason::INTERNAL_ERROR, rpc_status.msg());
665
0
    }
666
0
}
667
668
0
static void empty_function(RuntimeState*, Status*) {}
669
670
void FragmentMgr::_exec_actual(std::shared_ptr<PlanFragmentExecutor> fragment_executor,
671
0
                               const FinishCallback& cb) {
672
0
    VLOG_DEBUG << fmt::format("Instance {}|{} executing", print_id(fragment_executor->query_id()),
673
0
                              print_id(fragment_executor->fragment_instance_id()));
674
675
0
    Status st = fragment_executor->execute();
676
0
    if (!st.ok()) {
677
0
        fragment_executor->cancel(PPlanFragmentCancelReason::INTERNAL_ERROR,
678
0
                                  "fragment_executor execute failed");
679
0
    }
680
681
0
    std::shared_ptr<QueryContext> query_ctx = fragment_executor->get_query_ctx();
682
0
    bool all_done = false;
683
0
    if (query_ctx != nullptr) {
684
        // decrease the number of unfinished fragments
685
0
        all_done = query_ctx->countdown(1);
686
0
    }
687
688
    // remove exec state after this fragment finished
689
0
    {
690
0
        _fragment_instance_map.erase(fragment_executor->fragment_instance_id());
691
0
        VLOG(10) << fmt::format("Instance {} finished, all_done: {}",
692
0
                                print_id(fragment_executor->fragment_instance_id()), all_done);
693
0
    }
694
0
    if (all_done && query_ctx) {
695
0
        _query_ctx_map.erase(query_ctx->query_id());
696
0
    }
697
698
    // Callback after remove from this id
699
0
    auto status = fragment_executor->status();
700
0
    cb(fragment_executor->runtime_state(), &status);
701
0
}
702
703
Status FragmentMgr::exec_plan_fragment(const TExecPlanFragmentParams& params,
704
0
                                       const QuerySource query_source) {
705
0
    if (params.txn_conf.need_txn) {
706
0
        std::shared_ptr<StreamLoadContext> stream_load_ctx =
707
0
                std::make_shared<StreamLoadContext>(_exec_env);
708
0
        stream_load_ctx->db = params.txn_conf.db;
709
0
        stream_load_ctx->db_id = params.txn_conf.db_id;
710
0
        stream_load_ctx->table = params.txn_conf.tbl;
711
0
        stream_load_ctx->txn_id = params.txn_conf.txn_id;
712
0
        stream_load_ctx->id = UniqueId(params.params.query_id);
713
0
        stream_load_ctx->put_result.params = params;
714
0
        stream_load_ctx->put_result.__isset.params = true;
715
0
        stream_load_ctx->use_streaming = true;
716
0
        stream_load_ctx->load_type = TLoadType::MANUL_LOAD;
717
0
        stream_load_ctx->load_src_type = TLoadSourceType::RAW;
718
0
        stream_load_ctx->label = params.import_label;
719
0
        stream_load_ctx->format = TFileFormatType::FORMAT_CSV_PLAIN;
720
0
        stream_load_ctx->timeout_second = 3600;
721
0
        stream_load_ctx->auth.token = params.txn_conf.token;
722
0
        stream_load_ctx->need_commit_self = true;
723
0
        stream_load_ctx->need_rollback = true;
724
0
        auto pipe = std::make_shared<io::StreamLoadPipe>(
725
0
                io::kMaxPipeBufferedBytes /* max_buffered_bytes */, 64 * 1024 /* min_chunk_size */,
726
0
                -1 /* total_length */, true /* use_proto */);
727
0
        stream_load_ctx->body_sink = pipe;
728
0
        stream_load_ctx->pipe = pipe;
729
0
        stream_load_ctx->max_filter_ratio = params.txn_conf.max_filter_ratio;
730
731
0
        RETURN_IF_ERROR(
732
0
                _exec_env->new_load_stream_mgr()->put(stream_load_ctx->id, stream_load_ctx));
733
734
0
        RETURN_IF_ERROR(_exec_env->stream_load_executor()->execute_plan_fragment(stream_load_ctx));
735
0
        return Status::OK();
736
0
    } else {
737
0
        return exec_plan_fragment(params, query_source, empty_function);
738
0
    }
739
0
}
740
741
Status FragmentMgr::exec_plan_fragment(const TPipelineFragmentParams& params,
742
0
                                       const QuerySource query_source) {
743
0
    if (params.txn_conf.need_txn) {
744
0
        std::shared_ptr<StreamLoadContext> stream_load_ctx =
745
0
                std::make_shared<StreamLoadContext>(_exec_env);
746
0
        stream_load_ctx->db = params.txn_conf.db;
747
0
        stream_load_ctx->db_id = params.txn_conf.db_id;
748
0
        stream_load_ctx->table = params.txn_conf.tbl;
749
0
        stream_load_ctx->txn_id = params.txn_conf.txn_id;
750
0
        stream_load_ctx->id = UniqueId(params.query_id);
751
0
        stream_load_ctx->put_result.pipeline_params = params;
752
0
        stream_load_ctx->use_streaming = true;
753
0
        stream_load_ctx->load_type = TLoadType::MANUL_LOAD;
754
0
        stream_load_ctx->load_src_type = TLoadSourceType::RAW;
755
0
        stream_load_ctx->label = params.import_label;
756
0
        stream_load_ctx->format = TFileFormatType::FORMAT_CSV_PLAIN;
757
0
        stream_load_ctx->timeout_second = 3600;
758
0
        stream_load_ctx->auth.token = params.txn_conf.token;
759
0
        stream_load_ctx->need_commit_self = true;
760
0
        stream_load_ctx->need_rollback = true;
761
0
        auto pipe = std::make_shared<io::StreamLoadPipe>(
762
0
                io::kMaxPipeBufferedBytes /* max_buffered_bytes */, 64 * 1024 /* min_chunk_size */,
763
0
                -1 /* total_length */, true /* use_proto */);
764
0
        stream_load_ctx->body_sink = pipe;
765
0
        stream_load_ctx->pipe = pipe;
766
0
        stream_load_ctx->max_filter_ratio = params.txn_conf.max_filter_ratio;
767
768
0
        RETURN_IF_ERROR(
769
0
                _exec_env->new_load_stream_mgr()->put(stream_load_ctx->id, stream_load_ctx));
770
771
0
        RETURN_IF_ERROR(_exec_env->stream_load_executor()->execute_plan_fragment(stream_load_ctx));
772
0
        return Status::OK();
773
0
    } else {
774
0
        return exec_plan_fragment(params, query_source, empty_function);
775
0
    }
776
0
}
777
778
0
Status FragmentMgr::start_query_execution(const PExecPlanFragmentStartRequest* request) {
779
0
    TUniqueId query_id;
780
0
    query_id.__set_hi(request->query_id().hi());
781
0
    query_id.__set_lo(request->query_id().lo());
782
0
    std::shared_ptr<QueryContext> q_ctx = nullptr;
783
0
    {
784
0
        TUniqueId query_id;
785
0
        query_id.__set_hi(request->query_id().hi());
786
0
        query_id.__set_lo(request->query_id().lo());
787
0
        q_ctx = _query_ctx_map.find(query_id);
788
0
        if (q_ctx == nullptr) {
789
0
            return Status::InternalError(
790
0
                    "Failed to get query fragments context. Query may be "
791
0
                    "timeout or be cancelled. host: {}",
792
0
                    BackendOptions::get_localhost());
793
0
        }
794
0
    }
795
0
    q_ctx->set_ready_to_execute(false);
796
0
    LOG(INFO) << fmt::format("Query {} start execution", print_id(query_id));
797
0
    return Status::OK();
798
0
}
799
800
void FragmentMgr::remove_pipeline_context(
801
0
        std::shared_ptr<pipeline::PipelineFragmentContext> f_context) {
802
0
    auto* q_context = f_context->get_query_ctx();
803
0
    bool all_done = false;
804
0
    TUniqueId query_id = f_context->get_query_id();
805
0
    {
806
0
        std::vector<TUniqueId> ins_ids;
807
0
        f_context->instance_ids(ins_ids);
808
0
        all_done = q_context->countdown(ins_ids.size());
809
0
        for (const auto& ins_id : ins_ids) {
810
0
            VLOG(10) << fmt::format("Removing query {} instance {}, all done? {}",
811
0
                                    print_id(query_id), print_id(ins_id), all_done);
812
0
            _pipeline_map.erase(ins_id);
813
0
            g_pipeline_fragment_instances_count << -1;
814
0
        }
815
0
    }
816
0
    if (all_done) {
817
0
        _query_ctx_map.erase(query_id);
818
0
    }
819
0
}
820
821
template <typename Params>
822
Status FragmentMgr::_get_query_ctx(const Params& params, TUniqueId query_id, bool pipeline,
823
                                   QuerySource query_source,
824
0
                                   std::shared_ptr<QueryContext>& query_ctx) {
825
0
    DBUG_EXECUTE_IF("FragmentMgr._get_query_ctx.failed",
826
0
                    { return Status::InternalError("FragmentMgr._get_query_ctx.failed"); });
827
0
    if (params.is_simplified_param) {
828
        // Get common components from _query_ctx_map
829
0
        query_ctx = _query_ctx_map.find(query_id);
830
0
        if (query_ctx == nullptr) {
831
0
            return Status::InternalError(
832
0
                    "Failed to get query fragments context. Query may be "
833
0
                    "timeout or be cancelled. host: {}",
834
0
                    BackendOptions::get_localhost());
835
0
        }
836
0
    } else {
837
        // Find _query_ctx_map, in case some other request has already
838
        // create the query fragments context.
839
0
        RETURN_IF_ERROR(_query_ctx_map.apply_if_not_exists(
840
0
                query_id, query_ctx,
841
0
                [&](phmap::flat_hash_map<TUniqueId, std::shared_ptr<QueryContext>>& map) -> Status {
842
0
                    TNetworkAddress current_connect_fe_addr;
843
                    // for gray upragde between 2.1 version, fe may not set current_connect_fe,
844
                    // then use coord addr instead
845
0
                    if (params.__isset.current_connect_fe) {
846
0
                        current_connect_fe_addr = params.current_connect_fe;
847
0
                    } else {
848
0
                        current_connect_fe_addr = params.coord;
849
0
                    }
850
851
                    // This may be a first fragment request of the query.
852
                    // Create the query fragments context.
853
0
                    query_ctx = QueryContext::create_shared(
854
0
                            query_id, params.fragment_num_on_host, _exec_env, params.query_options,
855
0
                            params.coord, pipeline, params.is_nereids, current_connect_fe_addr,
856
0
                            query_source);
857
0
                    VLOG(10) << "query_id: " << print_id(query_id)
858
0
                             << ", coord_addr: " << params.coord
859
0
                             << ", total fragment num on current host: "
860
0
                             << params.fragment_num_on_host
861
0
                             << ", fe process uuid: " << params.query_options.fe_process_uuid
862
0
                             << ", query type: " << params.query_options.query_type
863
0
                             << ", report audit fe:" << current_connect_fe_addr << ", limit: "
864
0
                             << PrettyPrinter::print(query_ctx->mem_limit(), TUnit::BYTES);
865
0
                    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(query_ctx->query_mem_tracker);
866
0
                    RETURN_IF_ERROR(DescriptorTbl::create(&(query_ctx->obj_pool), params.desc_tbl,
867
0
                                                          &(query_ctx->desc_tbl)));
868
                    // set file scan range params
869
0
                    if (params.__isset.file_scan_params) {
870
0
                        query_ctx->file_scan_range_params_map = params.file_scan_params;
871
0
                    }
872
873
0
                    query_ctx->query_globals = params.query_globals;
874
875
0
                    if (params.__isset.resource_info) {
876
0
                        query_ctx->user = params.resource_info.user;
877
0
                        query_ctx->group = params.resource_info.group;
878
0
                        query_ctx->set_rsc_info = true;
879
0
                    }
880
881
0
                    query_ctx->get_shared_hash_table_controller()->set_pipeline_engine_enabled(
882
0
                            pipeline);
883
0
                    _set_scan_concurrency(params, query_ctx.get());
884
0
                    const bool is_pipeline = std::is_same_v<TPipelineFragmentParams, Params>;
885
886
0
                    if (params.__isset.workload_groups && !params.workload_groups.empty()) {
887
0
                        uint64_t tg_id = params.workload_groups[0].id;
888
0
                        WorkloadGroupPtr workload_group_ptr =
889
0
                                _exec_env->workload_group_mgr()->get_task_group_by_id(tg_id);
890
0
                        if (workload_group_ptr != nullptr) {
891
0
                            RETURN_IF_ERROR(workload_group_ptr->add_query(query_id, query_ctx));
892
0
                            RETURN_IF_ERROR(query_ctx->set_workload_group(workload_group_ptr));
893
0
                            _exec_env->runtime_query_statistics_mgr()->set_workload_group_id(
894
0
                                    print_id(query_id), tg_id);
895
896
0
                            VLOG(10) << "Query/load id: " << print_id(query_ctx->query_id())
897
0
                                     << ", use workload group: "
898
0
                                     << workload_group_ptr->debug_string()
899
0
                                     << ", is pipeline: " << ((int)is_pipeline);
900
0
                        } else {
901
0
                            VLOG(10) << "Query/load id: " << print_id(query_ctx->query_id())
902
0
                                     << " carried group info but can not find group in be";
903
0
                        }
904
0
                    }
905
                    // There is some logic in query ctx's dctor, we could not check if exists and delete the
906
                    // temp query ctx now. For example, the query id maybe removed from workload group's queryset.
907
0
                    map.insert({query_id, query_ctx});
908
0
                    return Status::OK();
909
0
                }));
910
0
    }
911
0
    return Status::OK();
912
0
}
Unexecuted instantiation: _ZN5doris11FragmentMgr14_get_query_ctxINS_23TExecPlanFragmentParamsEEENS_6StatusERKT_NS_9TUniqueIdEbNS_11QuerySourceERSt10shared_ptrINS_12QueryContextEE
Unexecuted instantiation: _ZN5doris11FragmentMgr14_get_query_ctxINS_23TPipelineFragmentParamsEEENS_6StatusERKT_NS_9TUniqueIdEbNS_11QuerySourceERSt10shared_ptrINS_12QueryContextEE
913
914
Status FragmentMgr::exec_plan_fragment(const TExecPlanFragmentParams& params,
915
0
                                       QuerySource query_source, const FinishCallback& cb) {
916
0
    VLOG_ROW << "exec_plan_fragment params is "
917
0
             << apache::thrift::ThriftDebugString(params).c_str();
918
    // sometimes TExecPlanFragmentParams debug string is too long and glog
919
    // will truncate the log line, so print query options seperately for debuggin purpose
920
0
    VLOG_ROW << "query options is "
921
0
             << apache::thrift::ThriftDebugString(params.query_options).c_str();
922
0
    const TUniqueId& fragment_instance_id = params.params.fragment_instance_id;
923
0
    {
924
0
        auto iter = _fragment_instance_map.find(fragment_instance_id);
925
0
        if (iter != nullptr) {
926
            // Duplicated
927
0
            LOG(WARNING) << "duplicate fragment instance id: " << print_id(fragment_instance_id);
928
0
            return Status::OK();
929
0
        }
930
0
    }
931
932
0
    std::shared_ptr<QueryContext> query_ctx;
933
0
    bool pipeline_engine_enabled = params.query_options.__isset.enable_pipeline_engine &&
934
0
                                   params.query_options.enable_pipeline_engine;
935
936
0
    RETURN_IF_ERROR(_get_query_ctx(params, params.params.query_id, pipeline_engine_enabled,
937
0
                                   query_source, query_ctx));
938
0
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(query_ctx->query_mem_tracker);
939
0
    {
940
        // Need lock here, because it will modify fragment ids and std::vector may resize and reallocate
941
        // memory, but query_is_canncelled will traverse the vector, it will core.
942
        // query_is_cancelled is called in allocator, we has to avoid dead lock.
943
0
        query_ctx->push_instance_ids(fragment_instance_id);
944
0
    }
945
946
0
    auto fragment_executor = std::make_shared<PlanFragmentExecutor>(
947
0
            _exec_env, query_ctx, params.params.fragment_instance_id, -1, params.backend_num,
948
0
            std::bind<void>(std::mem_fn(&FragmentMgr::coordinator_callback), this,
949
0
                            std::placeholders::_1));
950
0
    if (params.__isset.need_wait_execution_trigger && params.need_wait_execution_trigger) {
951
        // set need_wait_execution_trigger means this instance will not actually being executed
952
        // until the execPlanFragmentStart RPC trigger to start it.
953
0
        fragment_executor->set_need_wait_execution_trigger();
954
0
    }
955
956
0
    int64_t duration_ns = 0;
957
0
    DCHECK(!pipeline_engine_enabled);
958
0
    {
959
0
        SCOPED_RAW_TIMER(&duration_ns);
960
0
        RETURN_IF_ERROR(fragment_executor->prepare(params));
961
0
    }
962
0
    g_fragmentmgr_prepare_latency << (duration_ns / 1000);
963
0
    std::shared_ptr<RuntimeFilterMergeControllerEntity> handler;
964
    // TODO need check the status, but when I add return_if_error the P0 will not pass
965
0
    static_cast<void>(_runtimefilter_controller.add_entity(
966
0
            params.params, params.params.query_id, params.query_options, &handler,
967
0
            RuntimeFilterParamsContext::create(fragment_executor->runtime_state())));
968
0
    {
969
0
        if (handler) {
970
0
            query_ctx->set_merge_controller_handler(handler);
971
0
        }
972
0
        _fragment_instance_map.insert(params.params.fragment_instance_id, fragment_executor);
973
0
    }
974
975
0
    auto st = _thread_pool->submit_func([this, fragment_executor, cb]() {
976
#ifndef BE_TEST
977
        SCOPED_ATTACH_TASK(fragment_executor->runtime_state());
978
#endif
979
0
        _exec_actual(fragment_executor, cb);
980
0
    });
981
0
    if (!st.ok()) {
982
0
        {
983
            // Remove the exec state added
984
0
            _fragment_instance_map.erase(params.params.fragment_instance_id);
985
0
        }
986
0
        fragment_executor->cancel(PPlanFragmentCancelReason::INTERNAL_ERROR,
987
0
                                  "push plan fragment to thread pool failed");
988
0
        return Status::InternalError(
989
0
                strings::Substitute("push plan fragment $0 to thread pool failed. err = $1, BE: $2",
990
0
                                    print_id(params.params.fragment_instance_id), st.to_string(),
991
0
                                    BackendOptions::get_localhost()));
992
0
    }
993
994
0
    return Status::OK();
995
0
}
996
997
0
std::string FragmentMgr::dump_pipeline_tasks(int64_t duration) {
998
0
    fmt::memory_buffer debug_string_buffer;
999
0
    auto t = MonotonicNanos();
1000
0
    size_t i = 0;
1001
0
    {
1002
0
        fmt::format_to(debug_string_buffer,
1003
0
                       "{} pipeline fragment contexts are still running! duration_limit={}\n",
1004
0
                       _pipeline_map.num_items(), duration);
1005
1006
0
        timespec now;
1007
0
        clock_gettime(CLOCK_MONOTONIC, &now);
1008
0
        _pipeline_map.apply(
1009
0
                [&](phmap::flat_hash_map<TUniqueId,
1010
0
                                         std::shared_ptr<pipeline::PipelineFragmentContext>>& map)
1011
0
                        -> Status {
1012
0
                    for (auto& it : map) {
1013
0
                        auto elapsed = (t - it.second->create_time()) / 1000000000.0;
1014
0
                        if (elapsed < duration) {
1015
                            // Only display tasks which has been running for more than {duration} seconds.
1016
0
                            continue;
1017
0
                        }
1018
0
                        auto timeout_second = it.second->timeout_second();
1019
0
                        fmt::format_to(
1020
0
                                debug_string_buffer,
1021
0
                                "No.{} (elapse_second={}s, query_timeout_second={}s, instance_id="
1022
0
                                "{}) : {}\n",
1023
0
                                i, elapsed, timeout_second, print_id(it.first),
1024
0
                                it.second->debug_string());
1025
0
                        i++;
1026
0
                    }
1027
0
                    return Status::OK();
1028
0
                });
1029
0
    }
1030
0
    return fmt::to_string(debug_string_buffer);
1031
0
}
1032
1033
0
std::string FragmentMgr::dump_pipeline_tasks(TUniqueId& query_id) {
1034
0
    if (auto q_ctx = get_query_context(query_id)) {
1035
0
        return q_ctx->print_all_pipeline_context();
1036
0
    } else {
1037
0
        return fmt::format("Query context (query id = {}) not found. \n", print_id(query_id));
1038
0
    }
1039
0
}
1040
1041
Status FragmentMgr::exec_plan_fragment(const TPipelineFragmentParams& params,
1042
0
                                       QuerySource query_source, const FinishCallback& cb) {
1043
0
    VLOG_ROW << "query: " << print_id(params.query_id) << " exec_plan_fragment params is "
1044
0
             << apache::thrift::ThriftDebugString(params).c_str();
1045
    // sometimes TExecPlanFragmentParams debug string is too long and glog
1046
    // will truncate the log line, so print query options seperately for debuggin purpose
1047
0
    VLOG_ROW << "query: " << print_id(params.query_id) << "query options is "
1048
0
             << apache::thrift::ThriftDebugString(params.query_options).c_str();
1049
1050
0
    std::shared_ptr<QueryContext> query_ctx;
1051
0
    RETURN_IF_ERROR(_get_query_ctx(params, params.query_id, true, query_source, query_ctx));
1052
0
    SCOPED_ATTACH_TASK(query_ctx.get());
1053
0
    const bool enable_pipeline_x = params.query_options.__isset.enable_pipeline_x_engine &&
1054
0
                                   params.query_options.enable_pipeline_x_engine;
1055
0
    if (enable_pipeline_x) {
1056
0
        _setup_shared_hashtable_for_broadcast_join(params, query_ctx.get());
1057
0
        int64_t duration_ns = 0;
1058
0
        std::shared_ptr<pipeline::PipelineFragmentContext> context =
1059
0
                std::make_shared<pipeline::PipelineXFragmentContext>(
1060
0
                        query_ctx->query_id(), params.fragment_id, query_ctx, _exec_env, cb,
1061
0
                        std::bind<Status>(
1062
0
                                std::mem_fn(&FragmentMgr::trigger_pipeline_context_report), this,
1063
0
                                std::placeholders::_1, std::placeholders::_2));
1064
0
        {
1065
0
            SCOPED_RAW_TIMER(&duration_ns);
1066
0
            auto prepare_st = context->prepare(params, _thread_pool.get());
1067
0
            if (!prepare_st.ok()) {
1068
0
                context->close_if_prepare_failed(prepare_st);
1069
0
                query_ctx->set_execution_dependency_ready();
1070
0
                return prepare_st;
1071
0
            }
1072
0
        }
1073
0
        g_fragmentmgr_prepare_latency << (duration_ns / 1000);
1074
1075
0
        DBUG_EXECUTE_IF("FragmentMgr.exec_plan_fragment.failed",
1076
0
                        { return Status::Aborted("FragmentMgr.exec_plan_fragment.failed"); });
1077
1078
0
        std::shared_ptr<RuntimeFilterMergeControllerEntity> handler;
1079
0
        RETURN_IF_ERROR(_runtimefilter_controller.add_entity(
1080
0
                params.local_params[0], params.query_id, params.query_options, &handler,
1081
0
                RuntimeFilterParamsContext::create(context->get_runtime_state())));
1082
0
        if (handler) {
1083
0
            query_ctx->set_merge_controller_handler(handler);
1084
0
        }
1085
1086
0
        for (const auto& local_param : params.local_params) {
1087
0
            const TUniqueId& fragment_instance_id = local_param.fragment_instance_id;
1088
0
            auto iter = _pipeline_map.find(fragment_instance_id);
1089
0
            if (iter != nullptr) {
1090
0
                return Status::InternalError(
1091
0
                        "exec_plan_fragment input duplicated fragment_instance_id({})",
1092
0
                        UniqueId(fragment_instance_id).to_string());
1093
0
            }
1094
0
            query_ctx->push_instance_ids(fragment_instance_id);
1095
0
        }
1096
1097
0
        if (!params.__isset.need_wait_execution_trigger || !params.need_wait_execution_trigger) {
1098
0
            query_ctx->set_ready_to_execute_only();
1099
0
        }
1100
1101
0
        {
1102
0
            std::vector<TUniqueId> ins_ids;
1103
0
            reinterpret_cast<pipeline::PipelineXFragmentContext*>(context.get())
1104
0
                    ->instance_ids(ins_ids);
1105
            // TODO: simplify this mapping
1106
0
            for (const auto& ins_id : ins_ids) {
1107
0
                _pipeline_map.insert(ins_id, context);
1108
0
            }
1109
0
        }
1110
0
        query_ctx->set_pipeline_context(params.fragment_id, context);
1111
1112
0
        RETURN_IF_ERROR(context->submit());
1113
0
        return Status::OK();
1114
0
    } else {
1115
0
        auto pre_and_submit = [&](int i) {
1116
0
            const auto& local_params = params.local_params[i];
1117
1118
0
            const TUniqueId& fragment_instance_id = local_params.fragment_instance_id;
1119
0
            {
1120
0
                auto res = _pipeline_map.find(fragment_instance_id);
1121
0
                if (res != nullptr) {
1122
                    // Duplicated
1123
0
                    return Status::OK();
1124
0
                }
1125
0
                query_ctx->push_instance_ids(fragment_instance_id);
1126
0
            }
1127
1128
0
            int64_t duration_ns = 0;
1129
0
            if (!params.__isset.need_wait_execution_trigger ||
1130
0
                !params.need_wait_execution_trigger) {
1131
0
                query_ctx->set_ready_to_execute_only();
1132
0
            }
1133
0
            _setup_shared_hashtable_for_broadcast_join(params, local_params, query_ctx.get());
1134
0
            std::shared_ptr<pipeline::PipelineFragmentContext> context =
1135
0
                    std::make_shared<pipeline::PipelineFragmentContext>(
1136
0
                            query_ctx->query_id(), fragment_instance_id, params.fragment_id,
1137
0
                            local_params.backend_num, query_ctx, _exec_env, cb,
1138
0
                            std::bind<Status>(
1139
0
                                    std::mem_fn(&FragmentMgr::trigger_pipeline_context_report),
1140
0
                                    this, std::placeholders::_1, std::placeholders::_2));
1141
0
            {
1142
0
                SCOPED_RAW_TIMER(&duration_ns);
1143
0
                auto prepare_st = context->prepare(params, i);
1144
0
                if (!prepare_st.ok()) {
1145
0
                    LOG(WARNING) << "Prepare failed: " << prepare_st.to_string();
1146
0
                    context->close_if_prepare_failed(prepare_st);
1147
0
                    static_cast<void>(context->update_status(prepare_st));
1148
0
                    return prepare_st;
1149
0
                }
1150
0
            }
1151
0
            g_fragmentmgr_prepare_latency << (duration_ns / 1000);
1152
1153
0
            DBUG_EXECUTE_IF("FragmentMgr.exec_plan_fragment.failed",
1154
0
                            { return Status::Aborted("FragmentMgr.exec_plan_fragment.failed"); });
1155
1156
0
            std::shared_ptr<RuntimeFilterMergeControllerEntity> handler;
1157
0
            RETURN_IF_ERROR(_runtimefilter_controller.add_entity(
1158
0
                    local_params, params.query_id, params.query_options, &handler,
1159
0
                    RuntimeFilterParamsContext::create(context->get_runtime_state())));
1160
0
            if (i == 0 && handler) {
1161
0
                query_ctx->set_merge_controller_handler(handler);
1162
0
            }
1163
0
            _pipeline_map.insert(fragment_instance_id, context);
1164
1165
0
            return context->submit();
1166
0
        };
1167
1168
0
        int target_size = params.local_params.size();
1169
0
        g_pipeline_fragment_instances_count << target_size;
1170
1171
0
        const auto& local_params = params.local_params[0];
1172
0
        if (local_params.__isset.runtime_filter_params) {
1173
0
            if (local_params.__isset.runtime_filter_params) {
1174
0
                query_ctx->runtime_filter_mgr()->set_runtime_filter_params(
1175
0
                        local_params.runtime_filter_params);
1176
0
            }
1177
0
        }
1178
0
        if (local_params.__isset.topn_filter_source_node_ids) {
1179
0
            query_ctx->init_runtime_predicates(local_params.topn_filter_source_node_ids);
1180
0
        } else {
1181
0
            query_ctx->init_runtime_predicates({0});
1182
0
        }
1183
1184
0
        if (target_size > 1) {
1185
0
            int prepare_done = {0};
1186
0
            Status prepare_status[target_size];
1187
0
            std::mutex m;
1188
0
            std::condition_variable cv;
1189
1190
0
            for (size_t i = 0; i < target_size; i++) {
1191
0
                RETURN_IF_ERROR(_thread_pool->submit_func([&, i]() {
1192
0
                    SCOPED_ATTACH_TASK(query_ctx.get());
1193
0
                    prepare_status[i] = pre_and_submit(i);
1194
0
                    std::unique_lock<std::mutex> lock(m);
1195
0
                    prepare_done++;
1196
0
                    if (prepare_done == target_size) {
1197
0
                        cv.notify_one();
1198
0
                    }
1199
0
                }));
1200
0
            }
1201
1202
0
            std::unique_lock<std::mutex> lock(m);
1203
0
            if (prepare_done != target_size) {
1204
0
                cv.wait(lock);
1205
1206
0
                for (size_t i = 0; i < target_size; i++) {
1207
0
                    if (!prepare_status[i].ok()) {
1208
0
                        return prepare_status[i];
1209
0
                    }
1210
0
                }
1211
0
            }
1212
0
            return Status::OK();
1213
0
        } else {
1214
0
            return pre_and_submit(0);
1215
0
        }
1216
0
    }
1217
0
    return Status::OK();
1218
0
}
1219
1220
template <typename Param>
1221
0
void FragmentMgr::_set_scan_concurrency(const Param& params, QueryContext* query_ctx) {
1222
#ifndef BE_TEST
1223
    // If the token is set, the scan task will use limited_scan_pool in scanner scheduler.
1224
    // Otherwise, the scan task will use local/remote scan pool in scanner scheduler
1225
    if (params.query_options.__isset.resource_limit &&
1226
        params.query_options.resource_limit.__isset.cpu_limit) {
1227
        query_ctx->set_thread_token(params.query_options.resource_limit.cpu_limit, false);
1228
    }
1229
#endif
1230
0
}
Unexecuted instantiation: _ZN5doris11FragmentMgr21_set_scan_concurrencyINS_23TExecPlanFragmentParamsEEEvRKT_PNS_12QueryContextE
Unexecuted instantiation: _ZN5doris11FragmentMgr21_set_scan_concurrencyINS_23TPipelineFragmentParamsEEEvRKT_PNS_12QueryContextE
1231
1232
0
std::shared_ptr<QueryContext> FragmentMgr::get_query_context(const TUniqueId& query_id) {
1233
0
    return _query_ctx_map.find(query_id);
1234
0
}
1235
1236
void FragmentMgr::cancel_query(const TUniqueId& query_id, const PPlanFragmentCancelReason& reason,
1237
0
                               const std::string& msg) {
1238
0
    std::shared_ptr<QueryContext> query_ctx;
1239
0
    std::vector<TUniqueId> all_instance_ids;
1240
0
    {
1241
0
        query_ctx = _query_ctx_map.find(query_id);
1242
1243
0
        if (query_ctx == nullptr) {
1244
0
            LOG(WARNING) << "Query " << print_id(query_id)
1245
0
                         << " does not exists, failed to cancel it";
1246
0
            return;
1247
0
        }
1248
        // Copy instanceids to avoid concurrent modification.
1249
        // And to reduce the scope of lock.
1250
0
        all_instance_ids = query_ctx->fragment_instance_ids;
1251
0
    }
1252
0
    if (query_ctx->enable_pipeline_x_exec()) {
1253
0
        query_ctx->cancel_all_pipeline_context(reason, msg);
1254
0
    } else {
1255
0
        for (auto it : all_instance_ids) {
1256
0
            cancel_instance(it, reason, msg);
1257
0
        }
1258
0
    }
1259
1260
0
    query_ctx->cancel(msg, Status::Cancelled(msg));
1261
0
    _query_ctx_map.erase(query_id);
1262
0
    LOG(INFO) << "Query " << print_id(query_id) << " is cancelled and removed. Reason: " << msg;
1263
0
}
1264
1265
void FragmentMgr::cancel_instance(const TUniqueId& instance_id,
1266
1
                                  const PPlanFragmentCancelReason& reason, const std::string& msg) {
1267
1
    std::shared_ptr<pipeline::PipelineFragmentContext> pipeline_ctx;
1268
1
    std::shared_ptr<PlanFragmentExecutor> non_pipeline_ctx;
1269
1
    {
1270
1
        pipeline_ctx = _pipeline_map.find(instance_id);
1271
1
        if (!pipeline_ctx) {
1272
1
            non_pipeline_ctx = _fragment_instance_map.find(instance_id);
1273
1
            if (non_pipeline_ctx == nullptr) {
1274
1
                LOG(WARNING) << "Could not find the fragment instance id:" << print_id(instance_id)
1275
1
                             << " to cancel";
1276
1
                return;
1277
1
            }
1278
1
        }
1279
1
    }
1280
1281
0
    if (pipeline_ctx != nullptr) {
1282
0
        pipeline_ctx->cancel(reason, msg);
1283
0
    } else if (non_pipeline_ctx != nullptr) {
1284
        // calling PlanFragmentExecutor::cancel
1285
0
        non_pipeline_ctx->cancel(reason, msg);
1286
0
    }
1287
0
}
1288
1289
void FragmentMgr::cancel_fragment(const TUniqueId& query_id, int32_t fragment_id,
1290
0
                                  const PPlanFragmentCancelReason& reason, const std::string& msg) {
1291
0
    auto res = _query_ctx_map.find(query_id);
1292
0
    if (res != nullptr) {
1293
        // Has to use value to keep the shared ptr not deconstructed.
1294
0
        WARN_IF_ERROR(res->cancel_pipeline_context(fragment_id, reason, msg),
1295
0
                      "fail to cancel fragment");
1296
0
    } else {
1297
0
        LOG(WARNING) << "Could not find the query id:" << print_id(query_id)
1298
0
                     << " fragment id:" << fragment_id << " to cancel";
1299
0
    }
1300
0
}
1301
1302
4
void FragmentMgr::cancel_worker() {
1303
4
    LOG(INFO) << "FragmentMgr cancel worker start working.";
1304
1305
4
    timespec check_invalid_query_last_timestamp;
1306
4
    clock_gettime(CLOCK_MONOTONIC, &check_invalid_query_last_timestamp);
1307
1308
4
    do {
1309
4
        std::vector<TUniqueId> queries_timeout;
1310
4
        std::vector<TUniqueId> queries_to_cancel;
1311
4
        std::vector<TUniqueId> queries_pipeline_task_leak;
1312
        // Fe process uuid -> set<QueryId>
1313
4
        std::map<int64_t, std::unordered_set<TUniqueId>> running_queries_on_all_fes;
1314
4
        const std::map<TNetworkAddress, FrontendInfo>& running_fes =
1315
4
                ExecEnv::GetInstance()->get_running_frontends();
1316
1317
4
        timespec now_for_check_invalid_query;
1318
4
        clock_gettime(CLOCK_MONOTONIC, &now_for_check_invalid_query);
1319
1320
4
        if (config::enable_pipeline_task_leakage_detect &&
1321
4
            now_for_check_invalid_query.tv_sec - check_invalid_query_last_timestamp.tv_sec >
1322
0
                    config::pipeline_task_leakage_detect_period_secs) {
1323
0
            check_invalid_query_last_timestamp = now_for_check_invalid_query;
1324
0
            running_queries_on_all_fes = _get_all_running_queries_from_fe();
1325
4
        } else {
1326
4
            running_queries_on_all_fes.clear();
1327
4
        }
1328
1329
4
        VecDateTimeValue now = VecDateTimeValue::local_time();
1330
4
        std::unordered_map<std::shared_ptr<PBackendService_Stub>, BrpcItem> brpc_stub_with_queries;
1331
4
        {
1332
4
            _fragment_instance_map.apply(
1333
4
                    [&](phmap::flat_hash_map<TUniqueId, std::shared_ptr<PlanFragmentExecutor>>& map)
1334
512
                            -> Status {
1335
512
                        for (auto& fragment_instance_itr : map) {
1336
0
                            if (fragment_instance_itr.second->is_timeout(now)) {
1337
0
                                queries_timeout.push_back(
1338
0
                                        fragment_instance_itr.second->fragment_instance_id());
1339
0
                            }
1340
0
                        }
1341
512
                        return Status::OK();
1342
512
                    });
1343
4
            _pipeline_map.apply(
1344
4
                    [&](phmap::flat_hash_map<
1345
4
                            TUniqueId, std::shared_ptr<pipeline::PipelineFragmentContext>>& map)
1346
512
                            -> Status {
1347
512
                        for (auto& pipeline_itr : map) {
1348
0
                            if (pipeline_itr.second->is_timeout(now)) {
1349
0
                                std::vector<TUniqueId> ins_ids;
1350
0
                                reinterpret_cast<pipeline::PipelineXFragmentContext*>(
1351
0
                                        pipeline_itr.second.get())
1352
0
                                        ->instance_ids(ins_ids);
1353
0
                                for (auto& ins_id : ins_ids) {
1354
0
                                    queries_timeout.push_back(ins_id);
1355
0
                                }
1356
0
                            } else {
1357
0
                                pipeline_itr.second->clear_finished_tasks();
1358
0
                            }
1359
0
                        }
1360
512
                        return Status::OK();
1361
512
                    });
1362
4
        }
1363
4
        {
1364
4
            _query_ctx_map.apply([&](phmap::flat_hash_map<TUniqueId, std::shared_ptr<QueryContext>>&
1365
512
                                             map) -> Status {
1366
512
                for (auto it = map.begin(); it != map.end();) {
1367
0
                    if (it->second->is_timeout(now)) {
1368
0
                        LOG_WARNING("Query {} is timeout", print_id(it->first));
1369
0
                        it = map.erase(it);
1370
0
                    } else {
1371
0
                        if (config::enable_brpc_connection_check) {
1372
0
                            auto brpc_stubs = it->second->get_using_brpc_stubs();
1373
0
                            for (auto& item : brpc_stubs) {
1374
0
                                if (!brpc_stub_with_queries.contains(item.second)) {
1375
0
                                    brpc_stub_with_queries.emplace(
1376
0
                                            item.second, BrpcItem {item.first, {it->second}});
1377
0
                                } else {
1378
0
                                    brpc_stub_with_queries[item.second].queries.emplace_back(
1379
0
                                            it->second);
1380
0
                                }
1381
0
                            }
1382
0
                        }
1383
0
                        ++it;
1384
0
                    }
1385
0
                }
1386
512
                return Status::OK();
1387
512
            });
1388
4
        }
1389
4
        {
1390
            // We use a very conservative cancel strategy.
1391
            // 0. If there are no running frontends, do not cancel any queries.
1392
            // 1. If query's process uuid is zero, do not cancel
1393
            // 2. If same process uuid, do not cancel
1394
            // 3. If fe has zero process uuid, do not cancel
1395
4
            if (running_fes.empty() && _query_ctx_map.num_items() != 0) {
1396
0
                LOG_EVERY_N(WARNING, 10)
1397
0
                        << "Could not find any running frontends, maybe we are upgrading or "
1398
0
                           "starting? "
1399
0
                        << "We will not cancel any outdated queries in this situation.";
1400
4
            } else {
1401
4
                _query_ctx_map.apply([&](phmap::flat_hash_map<TUniqueId,
1402
4
                                                              std::shared_ptr<QueryContext>>& map)
1403
512
                                             -> Status {
1404
512
                    for (const auto& q : map) {
1405
0
                        auto q_ctx = q.second;
1406
0
                        const int64_t fe_process_uuid = q_ctx->get_fe_process_uuid();
1407
1408
0
                        if (fe_process_uuid == 0) {
1409
                            // zero means this query is from a older version fe or
1410
                            // this fe is starting
1411
0
                            continue;
1412
0
                        }
1413
1414
                        // If the query is not running on the any frontends, cancel it.
1415
0
                        if (auto itr = running_queries_on_all_fes.find(fe_process_uuid);
1416
0
                            itr != running_queries_on_all_fes.end()) {
1417
                            // Query not found on this frontend, and the query arrives before the last check
1418
0
                            if (itr->second.find(q_ctx->query_id()) == itr->second.end() &&
1419
                                // tv_nsec represents the number of nanoseconds that have elapsed since the time point stored in tv_sec.
1420
                                // tv_sec is enough, we do not need to check tv_nsec.
1421
0
                                q_ctx->get_query_arrival_timestamp().tv_sec <
1422
0
                                        check_invalid_query_last_timestamp.tv_sec &&
1423
0
                                q_ctx->get_query_source() == QuerySource::INTERNAL_FRONTEND) {
1424
0
                                if (q_ctx->enable_pipeline_x_exec()) {
1425
0
                                    queries_pipeline_task_leak.push_back(q_ctx->query_id());
1426
0
                                    LOG_INFO(
1427
0
                                            "Query {}, type {} is not found on any frontends, "
1428
0
                                            "maybe it is leaked.",
1429
0
                                            print_id(q_ctx->query_id()),
1430
0
                                            toString(q_ctx->get_query_source()));
1431
0
                                    continue;
1432
0
                                }
1433
0
                            }
1434
0
                        }
1435
1436
0
                        auto query_context = q.second;
1437
1438
0
                        auto itr = running_fes.find(query_context->coord_addr);
1439
0
                        if (itr != running_fes.end()) {
1440
0
                            if (q.second->get_fe_process_uuid() == itr->second.info.process_uuid ||
1441
0
                                itr->second.info.process_uuid == 0) {
1442
0
                                continue;
1443
0
                            } else {
1444
0
                                LOG_WARNING(
1445
0
                                        "Coordinator of query {} restarted, going to cancel it.",
1446
0
                                        print_id(q.second->query_id()));
1447
0
                            }
1448
0
                        } else {
1449
                            // In some rear cases, the rpc port of follower is not updated in time,
1450
                            // then the port of this follower will be zero, but acutally it is still running,
1451
                            // and be has already received the query from follower.
1452
                            // So we need to check if host is in running_fes.
1453
0
                            bool fe_host_is_standing = std::any_of(
1454
0
                                    running_fes.begin(), running_fes.end(),
1455
0
                                    [query_context](const auto& fe) {
1456
0
                                        return fe.first.hostname ==
1457
0
                                                       query_context->coord_addr.hostname &&
1458
0
                                               fe.first.port == 0;
1459
0
                                    });
1460
1461
0
                            if (fe_host_is_standing) {
1462
0
                                LOG_WARNING(
1463
0
                                        "Coordinator {}:{} is not found, but its host is still "
1464
0
                                        "running with an unstable rpc port, not going to cancel "
1465
0
                                        "it.",
1466
0
                                        query_context->coord_addr.hostname,
1467
0
                                        query_context->coord_addr.port,
1468
0
                                        print_id(query_context->query_id()));
1469
0
                                continue;
1470
0
                            } else {
1471
0
                                LOG_WARNING(
1472
0
                                        "Could not find target coordinator {}:{} of query {}, "
1473
0
                                        "going to "
1474
0
                                        "cancel it.",
1475
0
                                        query_context->coord_addr.hostname,
1476
0
                                        query_context->coord_addr.port,
1477
0
                                        print_id(query_context->query_id()));
1478
0
                            }
1479
0
                        }
1480
1481
                        // Coorninator of this query has already dead.
1482
0
                        queries_to_cancel.push_back(q.first);
1483
0
                    }
1484
512
                    return Status::OK();
1485
512
                });
1486
4
            }
1487
4
        }
1488
1489
        // TODO(zhiqiang): It seems that timeout_canceled_fragment_count is
1490
        // designed to count canceled fragment of non-pipeline query.
1491
4
        timeout_canceled_fragment_count->increment(queries_timeout.size());
1492
4
        for (auto& id : queries_timeout) {
1493
0
            cancel_instance(id, PPlanFragmentCancelReason::TIMEOUT, "Query timeout");
1494
0
            LOG(INFO) << "FragmentMgr cancel worker going to cancel timeout instance "
1495
0
                      << print_id(id);
1496
0
        }
1497
1498
4
        for (const auto& qid : queries_pipeline_task_leak) {
1499
            // Cancel the query, and maybe try to report debug info to fe so that we can
1500
            // collect debug info by sql or http api instead of search log.
1501
0
            cancel_query(qid, PPlanFragmentCancelReason::INTERNAL_ERROR,
1502
0
                         std::string("Pipeline task leak."));
1503
0
        }
1504
1505
4
        if (!queries_to_cancel.empty()) {
1506
0
            LOG(INFO) << "There are " << queries_to_cancel.size()
1507
0
                      << " queries need to be cancelled, coordinator dead or restarted.";
1508
0
        }
1509
1510
4
        for (const auto& qid : queries_to_cancel) {
1511
0
            cancel_query(qid, PPlanFragmentCancelReason::INTERNAL_ERROR,
1512
0
                         std::string("Coordinator dead."));
1513
0
        }
1514
1515
4
        if (config::enable_brpc_connection_check) {
1516
0
            for (auto it : brpc_stub_with_queries) {
1517
0
                if (!it.first) {
1518
0
                    continue;
1519
0
                }
1520
0
                _check_brpc_available(it.first, it.second);
1521
0
            }
1522
0
        }
1523
4
    } while (!_stop_background_threads_latch.wait_for(
1524
4
            std::chrono::seconds(config::fragment_mgr_cancel_worker_interval_seconds)));
1525
4
    LOG(INFO) << "FragmentMgr cancel worker is going to exit.";
1526
4
}
1527
1528
0
void FragmentMgr::debug(std::stringstream& ss) {
1529
    // Keep things simple
1530
0
    ss << "FragmentMgr have " << _fragment_instance_map.num_items() << " jobs.\n";
1531
0
    ss << "job_id\t\tstart_time\t\texecute_time(s)\n";
1532
0
    VecDateTimeValue now = VecDateTimeValue::local_time();
1533
0
    _fragment_instance_map.apply(
1534
0
            [&](phmap::flat_hash_map<TUniqueId, std::shared_ptr<PlanFragmentExecutor>>& map)
1535
0
                    -> Status {
1536
0
                for (auto& it : map) {
1537
0
                    ss << it.first << "\t" << it.second->start_time().debug_string() << "\t"
1538
0
                       << now.second_diff(it.second->start_time()) << "\n";
1539
0
                }
1540
0
                return Status::OK();
1541
0
            });
1542
0
}
1543
1544
void FragmentMgr::_check_brpc_available(const std::shared_ptr<PBackendService_Stub>& brpc_stub,
1545
0
                                        const BrpcItem& brpc_item) {
1546
0
    const std::string message = "hello doris!";
1547
0
    std::string error_message;
1548
0
    int32_t failed_count = 0;
1549
0
    const int64_t check_timeout_ms =
1550
0
            std::max<int64_t>(100, config::brpc_connection_check_timeout_ms);
1551
1552
0
    while (true) {
1553
0
        PHandShakeRequest request;
1554
0
        request.set_hello(message);
1555
0
        PHandShakeResponse response;
1556
0
        brpc::Controller cntl;
1557
0
        cntl.set_timeout_ms(check_timeout_ms);
1558
0
        cntl.set_max_retry(10);
1559
0
        brpc_stub->hand_shake(&cntl, &request, &response, nullptr);
1560
1561
0
        if (cntl.Failed()) {
1562
0
            error_message = cntl.ErrorText();
1563
0
            LOG(WARNING) << "brpc stub: " << brpc_item.network_address.hostname << ":"
1564
0
                         << brpc_item.network_address.port << " check failed: " << error_message;
1565
0
        } else if (response.has_status() && response.status().status_code() == 0) {
1566
0
            break;
1567
0
        } else {
1568
0
            error_message = response.DebugString();
1569
0
            LOG(WARNING) << "brpc stub: " << brpc_item.network_address.hostname << ":"
1570
0
                         << brpc_item.network_address.port << " check failed: " << error_message;
1571
0
        }
1572
0
        failed_count++;
1573
0
        if (failed_count == 2) {
1574
0
            for (const auto& query_wptr : brpc_item.queries) {
1575
0
                auto query = query_wptr.lock();
1576
0
                if (query && !query->is_cancelled()) {
1577
0
                    cancel_query(query->query_id(), PPlanFragmentCancelReason::INTERNAL_ERROR,
1578
0
                                 fmt::format("brpc(dest: {}:{}) check failed: {}",
1579
0
                                             brpc_item.network_address.hostname,
1580
0
                                             brpc_item.network_address.port, error_message));
1581
0
                }
1582
0
            }
1583
1584
0
            LOG(WARNING) << "remove brpc stub from cache: " << brpc_item.network_address.hostname
1585
0
                         << ":" << brpc_item.network_address.port << ", error: " << error_message;
1586
0
            ExecEnv::GetInstance()->brpc_internal_client_cache()->erase(
1587
0
                    brpc_item.network_address.hostname, brpc_item.network_address.port);
1588
0
            break;
1589
0
        }
1590
0
    }
1591
0
}
1592
1593
/*
1594
 * 1. resolve opaqued_query_plan to thrift structure
1595
 * 2. build TExecPlanFragmentParams
1596
 */
1597
Status FragmentMgr::exec_external_plan_fragment(const TScanOpenParams& params,
1598
                                                const TUniqueId& fragment_instance_id,
1599
0
                                                std::vector<TScanColumnDesc>* selected_columns) {
1600
0
    const std::string& opaqued_query_plan = params.opaqued_query_plan;
1601
0
    std::string query_plan_info;
1602
    // base64 decode query plan
1603
0
    if (!base64_decode(opaqued_query_plan, &query_plan_info)) {
1604
0
        LOG(WARNING) << "open context error: base64_decode decode opaqued_query_plan failure";
1605
0
        std::stringstream msg;
1606
0
        msg << "query_plan_info: " << query_plan_info
1607
0
            << " validate error, should not be modified after returned Doris FE processed";
1608
0
        return Status::InvalidArgument(msg.str());
1609
0
    }
1610
0
    TQueryPlanInfo t_query_plan_info;
1611
0
    const uint8_t* buf = (const uint8_t*)query_plan_info.data();
1612
0
    uint32_t len = query_plan_info.size();
1613
    // deserialize TQueryPlanInfo
1614
0
    auto st = deserialize_thrift_msg(buf, &len, false, &t_query_plan_info);
1615
0
    if (!st.ok()) {
1616
0
        LOG(WARNING) << "open context error: deserialize TQueryPlanInfo failure";
1617
0
        std::stringstream msg;
1618
0
        msg << "query_plan_info: " << query_plan_info
1619
0
            << " deserialize error, should not be modified after returned Doris FE processed";
1620
0
        return Status::InvalidArgument(msg.str());
1621
0
    }
1622
1623
    // set up desc tbl
1624
0
    DescriptorTbl* desc_tbl = nullptr;
1625
0
    ObjectPool obj_pool;
1626
0
    st = DescriptorTbl::create(&obj_pool, t_query_plan_info.desc_tbl, &desc_tbl);
1627
0
    if (!st.ok()) {
1628
0
        LOG(WARNING) << "open context error: extract DescriptorTbl failure";
1629
0
        std::stringstream msg;
1630
0
        msg << "query_plan_info: " << query_plan_info
1631
0
            << " create DescriptorTbl error, should not be modified after returned Doris FE "
1632
0
               "processed";
1633
0
        return Status::InvalidArgument(msg.str());
1634
0
    }
1635
0
    TupleDescriptor* tuple_desc = desc_tbl->get_tuple_descriptor(0);
1636
0
    if (tuple_desc == nullptr) {
1637
0
        LOG(WARNING) << "open context error: extract TupleDescriptor failure";
1638
0
        std::stringstream msg;
1639
0
        msg << "query_plan_info: " << query_plan_info
1640
0
            << " get  TupleDescriptor error, should not be modified after returned Doris FE "
1641
0
               "processed";
1642
0
        return Status::InvalidArgument(msg.str());
1643
0
    }
1644
    // process selected columns form slots
1645
0
    for (const SlotDescriptor* slot : tuple_desc->slots()) {
1646
0
        TScanColumnDesc col;
1647
0
        col.__set_name(slot->col_name());
1648
0
        col.__set_type(to_thrift(slot->type().type));
1649
0
        selected_columns->emplace_back(std::move(col));
1650
0
    }
1651
1652
0
    VLOG_QUERY << "BackendService execute open()  TQueryPlanInfo: "
1653
0
               << apache::thrift::ThriftDebugString(t_query_plan_info);
1654
    // assign the param used to execute PlanFragment
1655
0
    TExecPlanFragmentParams exec_fragment_params;
1656
0
    exec_fragment_params.protocol_version = (PaloInternalServiceVersion::type)0;
1657
0
    exec_fragment_params.__set_is_simplified_param(false);
1658
0
    exec_fragment_params.__set_fragment(t_query_plan_info.plan_fragment);
1659
0
    exec_fragment_params.__set_desc_tbl(t_query_plan_info.desc_tbl);
1660
1661
    // assign the param used for executing of PlanFragment-self
1662
0
    TPlanFragmentExecParams fragment_exec_params;
1663
0
    fragment_exec_params.query_id = t_query_plan_info.query_id;
1664
0
    fragment_exec_params.fragment_instance_id = fragment_instance_id;
1665
0
    std::map<::doris::TPlanNodeId, std::vector<TScanRangeParams>> per_node_scan_ranges;
1666
0
    std::vector<TScanRangeParams> scan_ranges;
1667
0
    std::vector<int64_t> tablet_ids = params.tablet_ids;
1668
0
    TNetworkAddress address;
1669
0
    address.hostname = BackendOptions::get_localhost();
1670
0
    address.port = doris::config::be_port;
1671
0
    std::map<int64_t, TTabletVersionInfo> tablet_info = t_query_plan_info.tablet_info;
1672
0
    for (auto tablet_id : params.tablet_ids) {
1673
0
        TPaloScanRange scan_range;
1674
0
        scan_range.db_name = params.database;
1675
0
        scan_range.table_name = params.table;
1676
0
        auto iter = tablet_info.find(tablet_id);
1677
0
        if (iter != tablet_info.end()) {
1678
0
            TTabletVersionInfo info = iter->second;
1679
0
            scan_range.tablet_id = tablet_id;
1680
0
            scan_range.version = std::to_string(info.version);
1681
            // Useless but it is required field in TPaloScanRange
1682
0
            scan_range.version_hash = "0";
1683
0
            scan_range.schema_hash = std::to_string(info.schema_hash);
1684
0
            scan_range.hosts.push_back(address);
1685
0
        } else {
1686
0
            std::stringstream msg;
1687
0
            msg << "tablet_id: " << tablet_id << " not found";
1688
0
            LOG(WARNING) << "tablet_id [ " << tablet_id << " ] not found";
1689
0
            return Status::NotFound(msg.str());
1690
0
        }
1691
0
        TScanRange doris_scan_range;
1692
0
        doris_scan_range.__set_palo_scan_range(scan_range);
1693
0
        TScanRangeParams scan_range_params;
1694
0
        scan_range_params.scan_range = doris_scan_range;
1695
0
        scan_ranges.push_back(scan_range_params);
1696
0
    }
1697
0
    per_node_scan_ranges.insert(std::make_pair((::doris::TPlanNodeId)0, scan_ranges));
1698
0
    fragment_exec_params.per_node_scan_ranges = per_node_scan_ranges;
1699
0
    exec_fragment_params.__set_params(fragment_exec_params);
1700
0
    TQueryOptions query_options;
1701
0
    query_options.batch_size = params.batch_size;
1702
0
    query_options.execution_timeout = params.execution_timeout;
1703
0
    query_options.mem_limit = params.mem_limit;
1704
0
    query_options.query_type = TQueryType::EXTERNAL;
1705
0
    exec_fragment_params.__set_query_options(query_options);
1706
0
    VLOG_ROW << "external exec_plan_fragment params is "
1707
0
             << apache::thrift::ThriftDebugString(exec_fragment_params).c_str();
1708
0
    return exec_plan_fragment(exec_fragment_params, QuerySource::EXTERNAL_CONNECTOR);
1709
0
}
1710
1711
Status FragmentMgr::apply_filter(const PPublishFilterRequest* request,
1712
0
                                 butil::IOBufAsZeroCopyInputStream* attach_data) {
1713
0
    bool is_pipeline = request->has_is_pipeline() && request->is_pipeline();
1714
1715
0
    UniqueId fragment_instance_id = request->fragment_instance_id();
1716
0
    TUniqueId tfragment_instance_id = fragment_instance_id.to_thrift();
1717
1718
0
    std::shared_ptr<PlanFragmentExecutor> fragment_executor;
1719
0
    std::shared_ptr<pipeline::PipelineFragmentContext> pip_context;
1720
0
    QueryThreadContext query_thread_context;
1721
1722
0
    RuntimeFilterMgr* runtime_filter_mgr = nullptr;
1723
0
    if (is_pipeline) {
1724
0
        pip_context = _pipeline_map.find(tfragment_instance_id);
1725
0
        if (pip_context == nullptr) {
1726
0
            VLOG_CRITICAL << "unknown.... fragment-id:" << fragment_instance_id;
1727
0
            return Status::InvalidArgument("fragment-id: {}", fragment_instance_id.to_string());
1728
0
        }
1729
1730
0
        DCHECK(pip_context != nullptr);
1731
0
        runtime_filter_mgr = pip_context->get_query_ctx()->runtime_filter_mgr();
1732
0
        query_thread_context = {pip_context->get_query_ctx()->query_id(),
1733
0
                                pip_context->get_query_ctx()->query_mem_tracker};
1734
0
    } else {
1735
0
        fragment_executor = _fragment_instance_map.find(tfragment_instance_id);
1736
0
        if (fragment_executor == nullptr) {
1737
0
            VLOG_CRITICAL << "unknown.... fragment instance id:" << print_id(tfragment_instance_id);
1738
0
            return Status::InvalidArgument("fragment-id: {}", print_id(tfragment_instance_id));
1739
0
        }
1740
1741
0
        DCHECK(fragment_executor != nullptr);
1742
0
        runtime_filter_mgr =
1743
0
                fragment_executor->runtime_state()->get_query_ctx()->runtime_filter_mgr();
1744
0
        query_thread_context = {fragment_executor->get_query_ctx()->query_id(),
1745
0
                                fragment_executor->get_query_ctx()->query_mem_tracker};
1746
0
    }
1747
1748
0
    SCOPED_ATTACH_TASK(query_thread_context);
1749
0
    return runtime_filter_mgr->update_filter(request, attach_data);
1750
0
}
1751
1752
Status FragmentMgr::apply_filterv2(const PPublishFilterRequestV2* request,
1753
0
                                   butil::IOBufAsZeroCopyInputStream* attach_data) {
1754
0
    bool is_pipeline = request->has_is_pipeline() && request->is_pipeline();
1755
0
    int64_t start_apply = MonotonicMillis();
1756
1757
0
    std::shared_ptr<PlanFragmentExecutor> fragment_executor;
1758
0
    std::shared_ptr<pipeline::PipelineFragmentContext> pip_context;
1759
0
    QueryThreadContext query_thread_context;
1760
1761
0
    RuntimeFilterMgr* runtime_filter_mgr = nullptr;
1762
0
    ObjectPool* pool = nullptr;
1763
1764
0
    const auto& fragment_instance_ids = request->fragment_instance_ids();
1765
0
    {
1766
0
        for (UniqueId fragment_instance_id : fragment_instance_ids) {
1767
0
            TUniqueId tfragment_instance_id = fragment_instance_id.to_thrift();
1768
1769
0
            if (is_pipeline) {
1770
0
                pip_context = _pipeline_map.find(tfragment_instance_id);
1771
0
                if (pip_context == nullptr) {
1772
0
                    continue;
1773
0
                }
1774
1775
0
                DCHECK(pip_context != nullptr);
1776
0
                runtime_filter_mgr = pip_context->get_query_ctx()->runtime_filter_mgr();
1777
0
                pool = &pip_context->get_query_ctx()->obj_pool;
1778
0
                query_thread_context = {pip_context->get_query_ctx()->query_id(),
1779
0
                                        pip_context->get_query_ctx()->query_mem_tracker,
1780
0
                                        pip_context->get_query_ctx()->workload_group()};
1781
0
            } else {
1782
0
                fragment_executor = _fragment_instance_map.find(tfragment_instance_id);
1783
0
                if (fragment_executor == nullptr) {
1784
0
                    continue;
1785
0
                }
1786
1787
0
                DCHECK(fragment_executor != nullptr);
1788
0
                runtime_filter_mgr = fragment_executor->get_query_ctx()->runtime_filter_mgr();
1789
0
                pool = &fragment_executor->get_query_ctx()->obj_pool;
1790
0
                query_thread_context = {fragment_executor->get_query_ctx()->query_id(),
1791
0
                                        fragment_executor->get_query_ctx()->query_mem_tracker};
1792
0
            }
1793
0
            break;
1794
0
        }
1795
0
    }
1796
1797
0
    if (runtime_filter_mgr == nullptr) {
1798
        // all instance finished
1799
0
        return Status::OK();
1800
0
    }
1801
1802
0
    SCOPED_ATTACH_TASK(query_thread_context);
1803
    // 1. get the target filters
1804
0
    std::vector<IRuntimeFilter*> filters;
1805
0
    RETURN_IF_ERROR(runtime_filter_mgr->get_consume_filters(request->filter_id(), filters));
1806
1807
    // 2. create the filter wrapper to replace or ignore the target filters
1808
0
    if (!filters.empty()) {
1809
0
        UpdateRuntimeFilterParamsV2 params {request, attach_data, pool, filters[0]->column_type()};
1810
0
        RuntimePredicateWrapper* filter_wrapper = nullptr;
1811
0
        RETURN_IF_ERROR(IRuntimeFilter::create_wrapper(&params, &filter_wrapper));
1812
1813
0
        std::ranges::for_each(filters, [&](auto& filter) {
1814
0
            filter->update_filter(filter_wrapper, request->merge_time(), start_apply);
1815
0
        });
1816
0
    }
1817
1818
0
    return Status::OK();
1819
0
}
1820
1821
0
Status FragmentMgr::send_filter_size(const PSendFilterSizeRequest* request) {
1822
0
    UniqueId queryid = request->query_id();
1823
1824
0
    if (config::enable_debug_points &&
1825
0
        DebugPoints::instance()->is_enable("FragmentMgr::send_filter_size.return_eof")) {
1826
0
        return Status::EndOfFile("inject FragmentMgr::send_filter_size.return_eof");
1827
0
    }
1828
1829
0
    std::shared_ptr<QueryContext> query_ctx;
1830
0
    {
1831
0
        TUniqueId query_id;
1832
0
        query_id.__set_hi(queryid.hi);
1833
0
        query_id.__set_lo(queryid.lo);
1834
0
        query_ctx = _query_ctx_map.find(query_id);
1835
0
        if (query_ctx == nullptr) {
1836
0
            return Status::EndOfFile("Query context (query-id: {}) not found, maybe finished",
1837
0
                                     queryid.to_string());
1838
0
        }
1839
0
    }
1840
1841
0
    std::shared_ptr<RuntimeFilterMergeControllerEntity> filter_controller;
1842
0
    RETURN_IF_ERROR(_runtimefilter_controller.acquire(queryid, &filter_controller));
1843
0
    auto merge_status = filter_controller->send_filter_size(request);
1844
0
    return merge_status;
1845
0
}
1846
1847
0
Status FragmentMgr::sync_filter_size(const PSyncFilterSizeRequest* request) {
1848
0
    UniqueId queryid = request->query_id();
1849
0
    std::shared_ptr<QueryContext> query_ctx;
1850
0
    {
1851
0
        TUniqueId query_id;
1852
0
        query_id.__set_hi(queryid.hi);
1853
0
        query_id.__set_lo(queryid.lo);
1854
0
        query_ctx = _query_ctx_map.find(query_id);
1855
0
        if (query_ctx == nullptr) {
1856
0
            return Status::InvalidArgument("query-id: {}", queryid.to_string());
1857
0
        }
1858
0
    }
1859
0
    return query_ctx->runtime_filter_mgr()->sync_filter_size(request);
1860
0
}
1861
1862
Status FragmentMgr::merge_filter(const PMergeFilterRequest* request,
1863
0
                                 butil::IOBufAsZeroCopyInputStream* attach_data) {
1864
0
    UniqueId queryid = request->query_id();
1865
0
    bool opt_remote_rf = request->has_opt_remote_rf() && request->opt_remote_rf();
1866
0
    std::shared_ptr<RuntimeFilterMergeControllerEntity> filter_controller;
1867
0
    RETURN_IF_ERROR(_runtimefilter_controller.acquire(queryid, &filter_controller));
1868
1869
0
    std::shared_ptr<QueryContext> query_ctx;
1870
0
    {
1871
0
        TUniqueId query_id;
1872
0
        query_id.__set_hi(queryid.hi);
1873
0
        query_id.__set_lo(queryid.lo);
1874
0
        query_ctx = _query_ctx_map.find(query_id);
1875
0
        if (query_ctx == nullptr) {
1876
0
            return Status::InvalidArgument("query-id: {}", queryid.to_string());
1877
0
        }
1878
0
    }
1879
0
    SCOPED_ATTACH_TASK(query_ctx.get());
1880
0
    auto merge_status = filter_controller->merge(request, attach_data, opt_remote_rf);
1881
0
    return merge_status;
1882
0
}
1883
1884
void FragmentMgr::_setup_shared_hashtable_for_broadcast_join(const TExecPlanFragmentParams& params,
1885
0
                                                             QueryContext* query_ctx) {
1886
0
    if (!params.query_options.__isset.enable_share_hash_table_for_broadcast_join ||
1887
0
        !params.query_options.enable_share_hash_table_for_broadcast_join) {
1888
0
        return;
1889
0
    }
1890
1891
0
    if (!params.__isset.fragment || !params.fragment.__isset.plan ||
1892
0
        params.fragment.plan.nodes.empty()) {
1893
0
        return;
1894
0
    }
1895
0
    for (auto& node : params.fragment.plan.nodes) {
1896
0
        if (node.node_type != TPlanNodeType::HASH_JOIN_NODE ||
1897
0
            !node.hash_join_node.__isset.is_broadcast_join ||
1898
0
            !node.hash_join_node.is_broadcast_join) {
1899
0
            continue;
1900
0
        }
1901
1902
0
        if (params.build_hash_table_for_broadcast_join) {
1903
0
            query_ctx->get_shared_hash_table_controller()->set_builder_and_consumers(
1904
0
                    params.params.fragment_instance_id, node.node_id);
1905
0
        }
1906
0
    }
1907
0
}
1908
1909
void FragmentMgr::_setup_shared_hashtable_for_broadcast_join(
1910
        const TPipelineFragmentParams& params, const TPipelineInstanceParams& local_params,
1911
0
        QueryContext* query_ctx) {
1912
0
    if (!params.query_options.__isset.enable_share_hash_table_for_broadcast_join ||
1913
0
        !params.query_options.enable_share_hash_table_for_broadcast_join) {
1914
0
        return;
1915
0
    }
1916
1917
0
    if (!params.__isset.fragment || !params.fragment.__isset.plan ||
1918
0
        params.fragment.plan.nodes.empty()) {
1919
0
        return;
1920
0
    }
1921
0
    for (auto& node : params.fragment.plan.nodes) {
1922
0
        if (node.node_type != TPlanNodeType::HASH_JOIN_NODE ||
1923
0
            !node.hash_join_node.__isset.is_broadcast_join ||
1924
0
            !node.hash_join_node.is_broadcast_join) {
1925
0
            continue;
1926
0
        }
1927
1928
0
        if (local_params.build_hash_table_for_broadcast_join) {
1929
0
            query_ctx->get_shared_hash_table_controller()->set_builder_and_consumers(
1930
0
                    local_params.fragment_instance_id, node.node_id);
1931
0
        }
1932
0
    }
1933
0
}
1934
1935
void FragmentMgr::_setup_shared_hashtable_for_broadcast_join(const TPipelineFragmentParams& params,
1936
0
                                                             QueryContext* query_ctx) {
1937
0
    if (!params.query_options.__isset.enable_share_hash_table_for_broadcast_join ||
1938
0
        !params.query_options.enable_share_hash_table_for_broadcast_join) {
1939
0
        return;
1940
0
    }
1941
1942
0
    if (!params.__isset.fragment || !params.fragment.__isset.plan ||
1943
0
        params.fragment.plan.nodes.empty()) {
1944
0
        return;
1945
0
    }
1946
0
    for (auto& node : params.fragment.plan.nodes) {
1947
0
        if (node.node_type != TPlanNodeType::HASH_JOIN_NODE ||
1948
0
            !node.hash_join_node.__isset.is_broadcast_join ||
1949
0
            !node.hash_join_node.is_broadcast_join) {
1950
0
            continue;
1951
0
        }
1952
1953
0
        for (auto& local_param : params.local_params) {
1954
0
            if (local_param.build_hash_table_for_broadcast_join) {
1955
0
                query_ctx->get_shared_hash_table_controller()->set_builder_and_consumers(
1956
0
                        local_param.fragment_instance_id, node.node_id);
1957
0
            }
1958
0
        }
1959
0
    }
1960
0
}
1961
1962
0
void FragmentMgr::get_runtime_query_info(std::vector<WorkloadQueryInfo>* query_info_list) {
1963
0
    _query_ctx_map.apply(
1964
0
            [&](phmap::flat_hash_map<TUniqueId, std::shared_ptr<QueryContext>>& map) -> Status {
1965
0
                for (const auto& q : map) {
1966
0
                    WorkloadQueryInfo workload_query_info;
1967
0
                    workload_query_info.query_id = print_id(q.first);
1968
0
                    workload_query_info.tquery_id = q.first;
1969
0
                    workload_query_info.wg_id = q.second->workload_group() == nullptr
1970
0
                                                        ? -1
1971
0
                                                        : q.second->workload_group()->id();
1972
0
                    query_info_list->push_back(workload_query_info);
1973
0
                }
1974
0
                return Status::OK();
1975
0
            });
1976
0
}
1977
1978
} // namespace doris