Coverage Report

Created: 2025-04-15 14:04

/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 <fmt/format.h>
23
#include <gen_cpp/DorisExternalService_types.h>
24
#include <gen_cpp/FrontendService.h>
25
#include <gen_cpp/FrontendService_types.h>
26
#include <gen_cpp/HeartbeatService_types.h>
27
#include <gen_cpp/Metrics_types.h>
28
#include <gen_cpp/PaloInternalService_types.h>
29
#include <gen_cpp/PlanNodes_types.h>
30
#include <gen_cpp/Planner_types.h>
31
#include <gen_cpp/QueryPlanExtra_types.h>
32
#include <gen_cpp/RuntimeProfile_types.h>
33
#include <gen_cpp/Types_types.h>
34
#include <gen_cpp/internal_service.pb.h>
35
#include <pthread.h>
36
#include <sys/time.h>
37
#include <thrift/TApplicationException.h>
38
#include <thrift/Thrift.h>
39
#include <thrift/protocol/TDebugProtocol.h>
40
#include <thrift/transport/TTransportException.h>
41
#include <unistd.h>
42
43
#include <algorithm>
44
#include <cstddef>
45
#include <ctime>
46
47
// IWYU pragma: no_include <bits/chrono.h>
48
#include <chrono> // IWYU pragma: keep
49
#include <cstdint>
50
#include <map>
51
#include <memory>
52
#include <mutex>
53
#include <sstream>
54
#include <unordered_map>
55
#include <unordered_set>
56
#include <utility>
57
58
#include "common/config.h"
59
#include "common/exception.h"
60
#include "common/logging.h"
61
#include "common/object_pool.h"
62
#include "common/status.h"
63
#include "common/utils.h"
64
#include "io/fs/stream_load_pipe.h"
65
#include "pipeline/pipeline_fragment_context.h"
66
#include "runtime/client_cache.h"
67
#include "runtime/descriptors.h"
68
#include "runtime/exec_env.h"
69
#include "runtime/frontend_info.h"
70
#include "runtime/primitive_type.h"
71
#include "runtime/query_context.h"
72
#include "runtime/runtime_query_statistics_mgr.h"
73
#include "runtime/runtime_state.h"
74
#include "runtime/stream_load/new_load_stream_mgr.h"
75
#include "runtime/stream_load/stream_load_context.h"
76
#include "runtime/stream_load/stream_load_executor.h"
77
#include "runtime/thread_context.h"
78
#include "runtime/types.h"
79
#include "runtime/workload_group/workload_group.h"
80
#include "runtime/workload_group/workload_group_manager.h"
81
#include "runtime_filter/runtime_filter_consumer.h"
82
#include "runtime_filter/runtime_filter_mgr.h"
83
#include "service/backend_options.h"
84
#include "util/brpc_client_cache.h"
85
#include "util/debug_points.h"
86
#include "util/debug_util.h"
87
#include "util/doris_metrics.h"
88
#include "util/network_util.h"
89
#include "util/runtime_profile.h"
90
#include "util/thread.h"
91
#include "util/threadpool.h"
92
#include "util/thrift_util.h"
93
#include "util/uid_util.h"
94
95
namespace doris {
96
97
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(fragment_instance_count, MetricUnit::NOUNIT);
98
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(timeout_canceled_fragment_count, MetricUnit::NOUNIT);
99
100
bvar::LatencyRecorder g_fragmentmgr_prepare_latency("doris_FragmentMgr", "prepare");
101
102
bvar::Adder<uint64_t> g_fragment_executing_count("fragment_executing_count");
103
bvar::Status<uint64_t> g_fragment_last_active_time(
104
        "fragment_last_active_time", duration_cast<std::chrono::milliseconds>(
105
                                             std::chrono::system_clock::now().time_since_epoch())
106
                                             .count());
107
108
0
uint64_t get_fragment_executing_count() {
109
0
    return g_fragment_executing_count.get_value();
110
0
}
111
0
uint64_t get_fragment_last_active_time() {
112
0
    return g_fragment_last_active_time.get_value();
113
0
}
114
115
0
std::string to_load_error_http_path(const std::string& file_name) {
116
0
    if (file_name.empty()) {
117
0
        return "";
118
0
    }
119
0
    if (file_name.compare(0, 4, "http") == 0) {
120
0
        return file_name;
121
0
    }
122
0
    std::stringstream url;
123
0
    url << "http://" << get_host_port(BackendOptions::get_localhost(), config::webserver_port)
124
0
        << "/api/_load_error_log?"
125
0
        << "file=" << file_name;
126
0
    return url.str();
127
0
}
128
129
using apache::thrift::TException;
130
using apache::thrift::transport::TTransportException;
131
132
static Status _do_fetch_running_queries_rpc(const FrontendInfo& fe_info,
133
0
                                            std::unordered_set<TUniqueId>& query_set) {
134
0
    TFetchRunningQueriesResult rpc_result;
135
0
    TFetchRunningQueriesRequest rpc_request;
136
137
0
    Status client_status;
138
0
    const int32 timeout_ms = 3 * 1000;
139
0
    FrontendServiceConnection rpc_client(ExecEnv::GetInstance()->frontend_client_cache(),
140
0
                                         fe_info.info.coordinator_address, timeout_ms,
141
0
                                         &client_status);
142
    // Abort this fe.
143
0
    if (!client_status.ok()) {
144
0
        LOG_WARNING("Failed to get client for {}, reason is {}",
145
0
                    PrintThriftNetworkAddress(fe_info.info.coordinator_address),
146
0
                    client_status.to_string());
147
0
        return Status::InternalError("Failed to get client for {}, reason is {}",
148
0
                                     PrintThriftNetworkAddress(fe_info.info.coordinator_address),
149
0
                                     client_status.to_string());
150
0
    }
151
152
    // do rpc
153
0
    try {
154
0
        try {
155
0
            rpc_client->fetchRunningQueries(rpc_result, rpc_request);
156
0
        } catch (const apache::thrift::transport::TTransportException& e) {
157
0
            LOG_WARNING("Transport exception reason: {}, reopening", e.what());
158
0
            client_status = rpc_client.reopen(config::thrift_rpc_timeout_ms);
159
0
            if (!client_status.ok()) {
160
0
                LOG_WARNING("Reopen failed, reason: {}", client_status.to_string_no_stack());
161
0
                return Status::InternalError("Reopen failed, reason: {}",
162
0
                                             client_status.to_string_no_stack());
163
0
            }
164
165
0
            rpc_client->fetchRunningQueries(rpc_result, rpc_request);
166
0
        }
167
0
    } catch (apache::thrift::TException& e) {
168
        // During upgrading cluster or meet any other network error.
169
0
        LOG_WARNING("Failed to fetch running queries from {}, reason: {}",
170
0
                    PrintThriftNetworkAddress(fe_info.info.coordinator_address), e.what());
171
0
        return Status::InternalError("Failed to fetch running queries from {}, reason: {}",
172
0
                                     PrintThriftNetworkAddress(fe_info.info.coordinator_address),
173
0
                                     e.what());
174
0
    }
175
176
    // Avoid logic error in frontend.
177
0
    if (!rpc_result.__isset.status || rpc_result.status.status_code != TStatusCode::OK) {
178
0
        LOG_WARNING("Failed to fetch running queries from {}, reason: {}",
179
0
                    PrintThriftNetworkAddress(fe_info.info.coordinator_address),
180
0
                    doris::to_string(rpc_result.status.status_code));
181
0
        return Status::InternalError("Failed to fetch running queries from {}, reason: {}",
182
0
                                     PrintThriftNetworkAddress(fe_info.info.coordinator_address),
183
0
                                     doris::to_string(rpc_result.status.status_code));
184
0
    }
185
186
0
    if (!rpc_result.__isset.running_queries) {
187
0
        return Status::InternalError("Failed to fetch running queries from {}, reason: {}",
188
0
                                     PrintThriftNetworkAddress(fe_info.info.coordinator_address),
189
0
                                     "running_queries is not set");
190
0
    }
191
192
0
    query_set = std::unordered_set<TUniqueId>(rpc_result.running_queries.begin(),
193
0
                                              rpc_result.running_queries.end());
194
0
    return Status::OK();
195
0
};
196
197
0
static std::map<int64_t, std::unordered_set<TUniqueId>> _get_all_running_queries_from_fe() {
198
0
    const std::map<TNetworkAddress, FrontendInfo>& running_fes =
199
0
            ExecEnv::GetInstance()->get_running_frontends();
200
201
0
    std::map<int64_t, std::unordered_set<TUniqueId>> result;
202
0
    std::vector<FrontendInfo> qualified_fes;
203
204
0
    for (const auto& fe : running_fes) {
205
        // Only consider normal frontend.
206
0
        if (fe.first.port != 0 && fe.second.info.process_uuid != 0) {
207
0
            qualified_fes.push_back(fe.second);
208
0
        } else {
209
0
            return {};
210
0
        }
211
0
    }
212
213
0
    for (const auto& fe_addr : qualified_fes) {
214
0
        const int64_t process_uuid = fe_addr.info.process_uuid;
215
0
        std::unordered_set<TUniqueId> query_set;
216
0
        Status st = _do_fetch_running_queries_rpc(fe_addr, query_set);
217
0
        if (!st.ok()) {
218
            // Empty result, cancel worker will not do anything
219
0
            return {};
220
0
        }
221
222
        // frontend_info and process_uuid has been checked in rpc threads.
223
0
        result[process_uuid] = query_set;
224
0
    }
225
226
0
    return result;
227
0
}
228
229
1
inline uint32_t get_map_id(const TUniqueId& query_id, size_t capacity) {
230
1
    uint32_t value = HashUtil::hash(&query_id.lo, 8, 0);
231
1
    value = HashUtil::hash(&query_id.hi, 8, value);
232
1
    return value % capacity;
233
1
}
234
235
0
inline uint32_t get_map_id(std::pair<TUniqueId, int> key, size_t capacity) {
236
0
    uint32_t value = HashUtil::hash(&key.first.lo, 8, 0);
237
0
    value = HashUtil::hash(&key.first.hi, 8, value);
238
0
    return value % capacity;
239
0
}
240
241
template <typename Key, typename Value, typename ValueType>
242
20
ConcurrentContextMap<Key, Value, ValueType>::ConcurrentContextMap() {
243
20
    _internal_map.resize(config::num_query_ctx_map_partitions);
244
2.58k
    for (size_t i = 0; i < config::num_query_ctx_map_partitions; i++) {
245
2.56k
        _internal_map[i] = {std::make_unique<std::shared_mutex>(),
246
2.56k
                            phmap::flat_hash_map<Key, Value>()};
247
2.56k
    }
248
20
}
_ZN5doris20ConcurrentContextMapISt4pairINS_9TUniqueIdEiESt10shared_ptrINS_8pipeline23PipelineFragmentContextEES6_EC2Ev
Line
Count
Source
242
10
ConcurrentContextMap<Key, Value, ValueType>::ConcurrentContextMap() {
243
10
    _internal_map.resize(config::num_query_ctx_map_partitions);
244
1.29k
    for (size_t i = 0; i < config::num_query_ctx_map_partitions; i++) {
245
1.28k
        _internal_map[i] = {std::make_unique<std::shared_mutex>(),
246
1.28k
                            phmap::flat_hash_map<Key, Value>()};
247
1.28k
    }
248
10
}
_ZN5doris20ConcurrentContextMapINS_9TUniqueIdESt8weak_ptrINS_12QueryContextEES3_EC2Ev
Line
Count
Source
242
10
ConcurrentContextMap<Key, Value, ValueType>::ConcurrentContextMap() {
243
10
    _internal_map.resize(config::num_query_ctx_map_partitions);
244
1.29k
    for (size_t i = 0; i < config::num_query_ctx_map_partitions; i++) {
245
1.28k
        _internal_map[i] = {std::make_unique<std::shared_mutex>(),
246
1.28k
                            phmap::flat_hash_map<Key, Value>()};
247
1.28k
    }
248
10
}
249
250
template <typename Key, typename Value, typename ValueType>
251
1
Value ConcurrentContextMap<Key, Value, ValueType>::find(const Key& query_id) {
252
1
    auto id = get_map_id(query_id, _internal_map.size());
253
1
    {
254
1
        std::shared_lock lock(*_internal_map[id].first);
255
1
        auto& map = _internal_map[id].second;
256
1
        auto search = map.find(query_id);
257
1
        if (search != map.end()) {
258
0
            return search->second;
259
0
        }
260
1
        return std::shared_ptr<ValueType>(nullptr);
261
1
    }
262
1
}
_ZN5doris20ConcurrentContextMapINS_9TUniqueIdESt8weak_ptrINS_12QueryContextEES3_E4findERKS1_
Line
Count
Source
251
1
Value ConcurrentContextMap<Key, Value, ValueType>::find(const Key& query_id) {
252
1
    auto id = get_map_id(query_id, _internal_map.size());
253
1
    {
254
1
        std::shared_lock lock(*_internal_map[id].first);
255
1
        auto& map = _internal_map[id].second;
256
1
        auto search = map.find(query_id);
257
1
        if (search != map.end()) {
258
0
            return search->second;
259
0
        }
260
1
        return std::shared_ptr<ValueType>(nullptr);
261
1
    }
262
1
}
Unexecuted instantiation: _ZN5doris20ConcurrentContextMapISt4pairINS_9TUniqueIdEiESt10shared_ptrINS_8pipeline23PipelineFragmentContextEES6_E4findERKS3_
263
264
template <typename Key, typename Value, typename ValueType>
265
Status ConcurrentContextMap<Key, Value, ValueType>::apply_if_not_exists(
266
0
        const Key& query_id, std::shared_ptr<ValueType>& query_ctx, ApplyFunction&& function) {
267
0
    auto id = get_map_id(query_id, _internal_map.size());
268
0
    {
269
0
        std::unique_lock lock(*_internal_map[id].first);
270
0
        auto& map = _internal_map[id].second;
271
0
        auto search = map.find(query_id);
272
0
        if (search != map.end()) {
273
0
            query_ctx = search->second.lock();
274
0
        }
275
0
        if (!query_ctx) {
276
0
            return function(map);
277
0
        }
278
0
        return Status::OK();
279
0
    }
280
0
}
281
282
template <typename Key, typename Value, typename ValueType>
283
0
void ConcurrentContextMap<Key, Value, ValueType>::erase(const Key& query_id) {
284
0
    auto id = get_map_id(query_id, _internal_map.size());
285
0
    {
286
0
        std::unique_lock lock(*_internal_map[id].first);
287
0
        auto& map = _internal_map[id].second;
288
0
        map.erase(query_id);
289
0
    }
290
0
}
Unexecuted instantiation: _ZN5doris20ConcurrentContextMapISt4pairINS_9TUniqueIdEiESt10shared_ptrINS_8pipeline23PipelineFragmentContextEES6_E5eraseERKS3_
Unexecuted instantiation: _ZN5doris20ConcurrentContextMapINS_9TUniqueIdESt8weak_ptrINS_12QueryContextEES3_E5eraseERKS1_
291
292
template <typename Key, typename Value, typename ValueType>
293
void ConcurrentContextMap<Key, Value, ValueType>::insert(const Key& query_id,
294
0
                                                         std::shared_ptr<ValueType> query_ctx) {
295
0
    auto id = get_map_id(query_id, _internal_map.size());
296
0
    {
297
0
        std::unique_lock lock(*_internal_map[id].first);
298
0
        auto& map = _internal_map[id].second;
299
0
        map.insert({query_id, query_ctx});
300
0
    }
301
0
}
302
303
template <typename Key, typename Value, typename ValueType>
304
20
void ConcurrentContextMap<Key, Value, ValueType>::clear() {
305
2.56k
    for (auto& pair : _internal_map) {
306
2.56k
        std::unique_lock lock(*pair.first);
307
2.56k
        auto& map = pair.second;
308
2.56k
        map.clear();
309
2.56k
    }
310
20
}
_ZN5doris20ConcurrentContextMapINS_9TUniqueIdESt8weak_ptrINS_12QueryContextEES3_E5clearEv
Line
Count
Source
304
10
void ConcurrentContextMap<Key, Value, ValueType>::clear() {
305
1.28k
    for (auto& pair : _internal_map) {
306
1.28k
        std::unique_lock lock(*pair.first);
307
1.28k
        auto& map = pair.second;
308
1.28k
        map.clear();
309
1.28k
    }
310
10
}
_ZN5doris20ConcurrentContextMapISt4pairINS_9TUniqueIdEiESt10shared_ptrINS_8pipeline23PipelineFragmentContextEES6_E5clearEv
Line
Count
Source
304
10
void ConcurrentContextMap<Key, Value, ValueType>::clear() {
305
1.28k
    for (auto& pair : _internal_map) {
306
1.28k
        std::unique_lock lock(*pair.first);
307
1.28k
        auto& map = pair.second;
308
1.28k
        map.clear();
309
1.28k
    }
310
10
}
311
312
FragmentMgr::FragmentMgr(ExecEnv* exec_env)
313
10
        : _exec_env(exec_env), _stop_background_threads_latch(1) {
314
10
    _entity = DorisMetrics::instance()->metric_registry()->register_entity("FragmentMgr");
315
10
    INT_UGAUGE_METRIC_REGISTER(_entity, timeout_canceled_fragment_count);
316
317
10
    auto s = Thread::create(
318
10
            "FragmentMgr", "cancel_timeout_plan_fragment", [this]() { this->cancel_worker(); },
319
10
            &_cancel_thread);
320
10
    CHECK(s.ok()) << s.to_string();
321
322
10
    s = ThreadPoolBuilder("FragmentMgrAsyncWorkThreadPool")
323
10
                .set_min_threads(config::fragment_mgr_asynic_work_pool_thread_num_min)
324
10
                .set_max_threads(config::fragment_mgr_asynic_work_pool_thread_num_max)
325
10
                .set_max_queue_size(config::fragment_mgr_asynic_work_pool_queue_size)
326
10
                .build(&_thread_pool);
327
10
    CHECK(s.ok()) << s.to_string();
328
10
}
329
330
10
FragmentMgr::~FragmentMgr() = default;
331
332
10
void FragmentMgr::stop() {
333
10
    DEREGISTER_HOOK_METRIC(fragment_instance_count);
334
10
    _stop_background_threads_latch.count_down();
335
10
    if (_cancel_thread) {
336
10
        _cancel_thread->join();
337
10
    }
338
339
    // Only me can delete
340
10
    _query_ctx_map.clear();
341
10
    _pipeline_map.clear();
342
10
    _thread_pool->shutdown();
343
10
}
344
345
0
std::string FragmentMgr::to_http_path(const std::string& file_name) {
346
0
    std::stringstream url;
347
0
    url << "http://" << BackendOptions::get_localhost() << ":" << config::webserver_port
348
0
        << "/api/_download_load?"
349
0
        << "token=" << _exec_env->token() << "&file=" << file_name;
350
0
    return url.str();
351
0
}
352
353
Status FragmentMgr::trigger_pipeline_context_report(
354
0
        const ReportStatusRequest req, std::shared_ptr<pipeline::PipelineFragmentContext>&& ctx) {
355
0
    return _thread_pool->submit_func([this, req, ctx]() {
356
0
        SCOPED_ATTACH_TASK(ctx->get_query_ctx()->query_mem_tracker());
357
0
        coordinator_callback(req);
358
0
        if (!req.done) {
359
0
            ctx->refresh_next_report_time();
360
0
        }
361
0
    });
362
0
}
363
364
// There can only be one of these callbacks in-flight at any moment, because
365
// it is only invoked from the executor's reporting thread.
366
// Also, the reported status will always reflect the most recent execution status,
367
// including the final status when execution finishes.
368
0
void FragmentMgr::coordinator_callback(const ReportStatusRequest& req) {
369
0
    DCHECK(req.status.ok() || req.done); // if !status.ok() => done
370
0
    if (req.coord_addr.hostname == "external") {
371
        // External query (flink/spark read tablets) not need to report to FE.
372
0
        return;
373
0
    }
374
0
    int callback_retries = 10;
375
0
    const int sleep_ms = 1000;
376
0
    Status exec_status = req.status;
377
0
    Status coord_status;
378
0
    std::unique_ptr<FrontendServiceConnection> coord = nullptr;
379
0
    do {
380
0
        coord = std::make_unique<FrontendServiceConnection>(_exec_env->frontend_client_cache(),
381
0
                                                            req.coord_addr, &coord_status);
382
0
        if (!coord_status.ok()) {
383
0
            std::this_thread::sleep_for(std::chrono::milliseconds(sleep_ms));
384
0
        }
385
0
    } while (!coord_status.ok() && callback_retries-- > 0);
386
387
0
    if (!coord_status.ok()) {
388
0
        std::stringstream ss;
389
0
        UniqueId uid(req.query_id.hi, req.query_id.lo);
390
0
        static_cast<void>(req.cancel_fn(Status::InternalError(
391
0
                "query_id: {}, couldn't get a client for {}, reason is {}", uid.to_string(),
392
0
                PrintThriftNetworkAddress(req.coord_addr), coord_status.to_string())));
393
0
        return;
394
0
    }
395
396
0
    TReportExecStatusParams params;
397
0
    params.protocol_version = FrontendServiceVersion::V1;
398
0
    params.__set_query_id(req.query_id);
399
0
    params.__set_backend_num(req.backend_num);
400
0
    params.__set_fragment_instance_id(req.fragment_instance_id);
401
0
    params.__set_fragment_id(req.fragment_id);
402
0
    params.__set_status(exec_status.to_thrift());
403
0
    params.__set_done(req.done);
404
0
    params.__set_query_type(req.runtime_state->query_type());
405
0
    params.__isset.profile = false;
406
407
0
    DCHECK(req.runtime_state != nullptr);
408
409
0
    if (req.runtime_state->query_type() == TQueryType::LOAD) {
410
0
        params.__set_loaded_rows(req.runtime_state->num_rows_load_total());
411
0
        params.__set_loaded_bytes(req.runtime_state->num_bytes_load_total());
412
0
    } else {
413
0
        DCHECK(!req.runtime_states.empty());
414
0
        if (!req.runtime_state->output_files().empty()) {
415
0
            params.__isset.delta_urls = true;
416
0
            for (auto& it : req.runtime_state->output_files()) {
417
0
                params.delta_urls.push_back(to_http_path(it));
418
0
            }
419
0
        }
420
0
        if (!params.delta_urls.empty()) {
421
0
            params.__isset.delta_urls = true;
422
0
        }
423
0
    }
424
425
    // load rows
426
0
    static std::string s_dpp_normal_all = "dpp.norm.ALL";
427
0
    static std::string s_dpp_abnormal_all = "dpp.abnorm.ALL";
428
0
    static std::string s_unselected_rows = "unselected.rows";
429
0
    int64_t num_rows_load_success = 0;
430
0
    int64_t num_rows_load_filtered = 0;
431
0
    int64_t num_rows_load_unselected = 0;
432
0
    if (req.runtime_state->num_rows_load_total() > 0 ||
433
0
        req.runtime_state->num_rows_load_filtered() > 0 ||
434
0
        req.runtime_state->num_finished_range() > 0) {
435
0
        params.__isset.load_counters = true;
436
437
0
        num_rows_load_success = req.runtime_state->num_rows_load_success();
438
0
        num_rows_load_filtered = req.runtime_state->num_rows_load_filtered();
439
0
        num_rows_load_unselected = req.runtime_state->num_rows_load_unselected();
440
0
        params.__isset.fragment_instance_reports = true;
441
0
        TFragmentInstanceReport t;
442
0
        t.__set_fragment_instance_id(req.runtime_state->fragment_instance_id());
443
0
        t.__set_num_finished_range(req.runtime_state->num_finished_range());
444
0
        t.__set_loaded_rows(req.runtime_state->num_rows_load_total());
445
0
        t.__set_loaded_bytes(req.runtime_state->num_bytes_load_total());
446
0
        params.fragment_instance_reports.push_back(t);
447
0
    } else if (!req.runtime_states.empty()) {
448
0
        for (auto* rs : req.runtime_states) {
449
0
            if (rs->num_rows_load_total() > 0 || rs->num_rows_load_filtered() > 0 ||
450
0
                req.runtime_state->num_finished_range() > 0) {
451
0
                params.__isset.load_counters = true;
452
0
                num_rows_load_success += rs->num_rows_load_success();
453
0
                num_rows_load_filtered += rs->num_rows_load_filtered();
454
0
                num_rows_load_unselected += rs->num_rows_load_unselected();
455
0
                params.__isset.fragment_instance_reports = true;
456
0
                TFragmentInstanceReport t;
457
0
                t.__set_fragment_instance_id(rs->fragment_instance_id());
458
0
                t.__set_num_finished_range(rs->num_finished_range());
459
0
                t.__set_loaded_rows(rs->num_rows_load_total());
460
0
                t.__set_loaded_bytes(rs->num_bytes_load_total());
461
0
                params.fragment_instance_reports.push_back(t);
462
0
            }
463
0
        }
464
0
    }
465
0
    params.load_counters.emplace(s_dpp_normal_all, std::to_string(num_rows_load_success));
466
0
    params.load_counters.emplace(s_dpp_abnormal_all, std::to_string(num_rows_load_filtered));
467
0
    params.load_counters.emplace(s_unselected_rows, std::to_string(num_rows_load_unselected));
468
469
0
    if (!req.load_error_url.empty()) {
470
0
        params.__set_tracking_url(req.load_error_url);
471
0
    }
472
0
    for (auto* rs : req.runtime_states) {
473
0
        if (rs->wal_id() > 0) {
474
0
            params.__set_txn_id(rs->wal_id());
475
0
            params.__set_label(rs->import_label());
476
0
        }
477
0
    }
478
0
    if (!req.runtime_state->export_output_files().empty()) {
479
0
        params.__isset.export_files = true;
480
0
        params.export_files = req.runtime_state->export_output_files();
481
0
    } else if (!req.runtime_states.empty()) {
482
0
        for (auto* rs : req.runtime_states) {
483
0
            if (!rs->export_output_files().empty()) {
484
0
                params.__isset.export_files = true;
485
0
                params.export_files.insert(params.export_files.end(),
486
0
                                           rs->export_output_files().begin(),
487
0
                                           rs->export_output_files().end());
488
0
            }
489
0
        }
490
0
    }
491
0
    if (auto tci = req.runtime_state->tablet_commit_infos(); !tci.empty()) {
492
0
        params.__isset.commitInfos = true;
493
0
        params.commitInfos.insert(params.commitInfos.end(), tci.begin(), tci.end());
494
0
    } else if (!req.runtime_states.empty()) {
495
0
        for (auto* rs : req.runtime_states) {
496
0
            if (auto rs_tci = rs->tablet_commit_infos(); !rs_tci.empty()) {
497
0
                params.__isset.commitInfos = true;
498
0
                params.commitInfos.insert(params.commitInfos.end(), rs_tci.begin(), rs_tci.end());
499
0
            }
500
0
        }
501
0
    }
502
0
    if (auto eti = req.runtime_state->error_tablet_infos(); !eti.empty()) {
503
0
        params.__isset.errorTabletInfos = true;
504
0
        params.errorTabletInfos.insert(params.errorTabletInfos.end(), eti.begin(), eti.end());
505
0
    } else if (!req.runtime_states.empty()) {
506
0
        for (auto* rs : req.runtime_states) {
507
0
            if (auto rs_eti = rs->error_tablet_infos(); !rs_eti.empty()) {
508
0
                params.__isset.errorTabletInfos = true;
509
0
                params.errorTabletInfos.insert(params.errorTabletInfos.end(), rs_eti.begin(),
510
0
                                               rs_eti.end());
511
0
            }
512
0
        }
513
0
    }
514
0
    if (auto hpu = req.runtime_state->hive_partition_updates(); !hpu.empty()) {
515
0
        params.__isset.hive_partition_updates = true;
516
0
        params.hive_partition_updates.insert(params.hive_partition_updates.end(), hpu.begin(),
517
0
                                             hpu.end());
518
0
    } else if (!req.runtime_states.empty()) {
519
0
        for (auto* rs : req.runtime_states) {
520
0
            if (auto rs_hpu = rs->hive_partition_updates(); !rs_hpu.empty()) {
521
0
                params.__isset.hive_partition_updates = true;
522
0
                params.hive_partition_updates.insert(params.hive_partition_updates.end(),
523
0
                                                     rs_hpu.begin(), rs_hpu.end());
524
0
            }
525
0
        }
526
0
    }
527
0
    if (auto icd = req.runtime_state->iceberg_commit_datas(); !icd.empty()) {
528
0
        params.__isset.iceberg_commit_datas = true;
529
0
        params.iceberg_commit_datas.insert(params.iceberg_commit_datas.end(), icd.begin(),
530
0
                                           icd.end());
531
0
    } else if (!req.runtime_states.empty()) {
532
0
        for (auto* rs : req.runtime_states) {
533
0
            if (auto rs_icd = rs->iceberg_commit_datas(); !rs_icd.empty()) {
534
0
                params.__isset.iceberg_commit_datas = true;
535
0
                params.iceberg_commit_datas.insert(params.iceberg_commit_datas.end(),
536
0
                                                   rs_icd.begin(), rs_icd.end());
537
0
            }
538
0
        }
539
0
    }
540
541
    // Send new errors to coordinator
542
0
    req.runtime_state->get_unreported_errors(&(params.error_log));
543
0
    params.__isset.error_log = (!params.error_log.empty());
544
545
0
    if (_exec_env->cluster_info()->backend_id != 0) {
546
0
        params.__set_backend_id(_exec_env->cluster_info()->backend_id);
547
0
    }
548
549
0
    TReportExecStatusResult res;
550
0
    Status rpc_status;
551
552
0
    VLOG_DEBUG << "reportExecStatus params is "
553
0
               << apache::thrift::ThriftDebugString(params).c_str();
554
0
    if (!exec_status.ok()) {
555
0
        LOG(WARNING) << "report error status: " << exec_status.msg()
556
0
                     << " to coordinator: " << req.coord_addr
557
0
                     << ", query id: " << print_id(req.query_id);
558
0
    }
559
0
    try {
560
0
        try {
561
0
            (*coord)->reportExecStatus(res, params);
562
0
        } catch ([[maybe_unused]] TTransportException& e) {
563
#ifndef ADDRESS_SANITIZER
564
            LOG(WARNING) << "Retrying ReportExecStatus. query id: " << print_id(req.query_id)
565
                         << ", instance id: " << print_id(req.fragment_instance_id) << " to "
566
                         << req.coord_addr << ", err: " << e.what();
567
#endif
568
0
            rpc_status = coord->reopen();
569
570
0
            if (!rpc_status.ok()) {
571
                // we need to cancel the execution of this fragment
572
0
                req.cancel_fn(rpc_status);
573
0
                return;
574
0
            }
575
0
            (*coord)->reportExecStatus(res, params);
576
0
        }
577
578
0
        rpc_status = Status::create<false>(res.status);
579
0
    } catch (TException& e) {
580
0
        rpc_status = Status::InternalError("ReportExecStatus() to {} failed: {}",
581
0
                                           PrintThriftNetworkAddress(req.coord_addr), e.what());
582
0
    }
583
584
0
    if (!rpc_status.ok()) {
585
0
        LOG_INFO("Going to cancel query {} since report exec status got rpc failed: {}",
586
0
                 print_id(req.query_id), rpc_status.to_string());
587
        // we need to cancel the execution of this fragment
588
0
        req.cancel_fn(rpc_status);
589
0
    }
590
0
}
591
592
0
static void empty_function(RuntimeState*, Status*) {}
593
594
Status FragmentMgr::exec_plan_fragment(const TExecPlanFragmentParams& params,
595
0
                                       const QuerySource query_source) {
596
0
    return Status::InternalError("Non-pipeline is disabled!");
597
0
}
598
599
Status FragmentMgr::exec_plan_fragment(const TPipelineFragmentParams& params,
600
                                       const QuerySource query_source,
601
0
                                       const TPipelineFragmentParamsList& parent) {
602
0
    if (params.txn_conf.need_txn) {
603
0
        std::shared_ptr<StreamLoadContext> stream_load_ctx =
604
0
                std::make_shared<StreamLoadContext>(_exec_env);
605
0
        stream_load_ctx->db = params.txn_conf.db;
606
0
        stream_load_ctx->db_id = params.txn_conf.db_id;
607
0
        stream_load_ctx->table = params.txn_conf.tbl;
608
0
        stream_load_ctx->txn_id = params.txn_conf.txn_id;
609
0
        stream_load_ctx->id = UniqueId(params.query_id);
610
0
        stream_load_ctx->put_result.__set_pipeline_params(params);
611
0
        stream_load_ctx->use_streaming = true;
612
0
        stream_load_ctx->load_type = TLoadType::MANUL_LOAD;
613
0
        stream_load_ctx->load_src_type = TLoadSourceType::RAW;
614
0
        stream_load_ctx->label = params.import_label;
615
0
        stream_load_ctx->format = TFileFormatType::FORMAT_CSV_PLAIN;
616
0
        stream_load_ctx->timeout_second = 3600;
617
0
        stream_load_ctx->auth.token = params.txn_conf.token;
618
0
        stream_load_ctx->need_commit_self = true;
619
0
        stream_load_ctx->need_rollback = true;
620
0
        auto pipe = std::make_shared<io::StreamLoadPipe>(
621
0
                io::kMaxPipeBufferedBytes /* max_buffered_bytes */, 64 * 1024 /* min_chunk_size */,
622
0
                -1 /* total_length */, true /* use_proto */);
623
0
        stream_load_ctx->body_sink = pipe;
624
0
        stream_load_ctx->pipe = pipe;
625
0
        stream_load_ctx->max_filter_ratio = params.txn_conf.max_filter_ratio;
626
627
0
        RETURN_IF_ERROR(
628
0
                _exec_env->new_load_stream_mgr()->put(stream_load_ctx->id, stream_load_ctx));
629
630
0
        RETURN_IF_ERROR(
631
0
                _exec_env->stream_load_executor()->execute_plan_fragment(stream_load_ctx, parent));
632
0
        return Status::OK();
633
0
    } else {
634
0
        return exec_plan_fragment(params, query_source, empty_function, parent);
635
0
    }
636
0
}
637
638
// Stage 2. prepare finished. then get FE instruction to execute
639
0
Status FragmentMgr::start_query_execution(const PExecPlanFragmentStartRequest* request) {
640
0
    TUniqueId query_id;
641
0
    query_id.__set_hi(request->query_id().hi());
642
0
    query_id.__set_lo(request->query_id().lo());
643
0
    auto q_ctx = get_query_ctx(query_id);
644
0
    if (q_ctx) {
645
0
        q_ctx->set_ready_to_execute(Status::OK());
646
0
        LOG_INFO("Query {} start execution", print_id(query_id));
647
0
    } else {
648
0
        return Status::InternalError(
649
0
                "Failed to get query fragments context. Query may be "
650
0
                "timeout or be cancelled. host: {}",
651
0
                BackendOptions::get_localhost());
652
0
    }
653
0
    return Status::OK();
654
0
}
655
656
0
void FragmentMgr::remove_pipeline_context(std::pair<TUniqueId, int> key) {
657
0
    int64 now = duration_cast<std::chrono::milliseconds>(
658
0
                        std::chrono::system_clock::now().time_since_epoch())
659
0
                        .count();
660
0
    g_fragment_executing_count << -1;
661
0
    g_fragment_last_active_time.set_value(now);
662
663
0
    _pipeline_map.erase(key);
664
0
}
665
666
1
std::shared_ptr<QueryContext> FragmentMgr::get_query_ctx(const TUniqueId& query_id) {
667
1
    auto val = _query_ctx_map.find(query_id);
668
1
    if (auto q_ctx = val.lock()) {
669
0
        return q_ctx;
670
0
    }
671
1
    return nullptr;
672
1
}
673
674
Status FragmentMgr::_get_or_create_query_ctx(const TPipelineFragmentParams& params,
675
                                             const TPipelineFragmentParamsList& parent,
676
                                             QuerySource query_source,
677
0
                                             std::shared_ptr<QueryContext>& query_ctx) {
678
0
    auto query_id = params.query_id;
679
0
    DBUG_EXECUTE_IF("FragmentMgr._get_query_ctx.failed", {
680
0
        return Status::InternalError("FragmentMgr._get_query_ctx.failed, query id {}",
681
0
                                     print_id(query_id));
682
0
    });
683
684
    // Find _query_ctx_map, in case some other request has already
685
    // create the query fragments context.
686
0
    query_ctx = get_query_ctx(query_id);
687
0
    if (params.is_simplified_param) {
688
        // Get common components from _query_ctx_map
689
0
        if (!query_ctx) {
690
0
            return Status::InternalError(
691
0
                    "Failed to get query fragments context. Query {} may be timeout or be "
692
0
                    "cancelled. host: {}",
693
0
                    print_id(query_id), BackendOptions::get_localhost());
694
0
        }
695
0
    } else {
696
0
        if (!query_ctx) {
697
0
            RETURN_IF_ERROR(_query_ctx_map.apply_if_not_exists(
698
0
                    query_id, query_ctx,
699
0
                    [&](phmap::flat_hash_map<TUniqueId, std::weak_ptr<QueryContext>>& map)
700
0
                            -> Status {
701
0
                        WorkloadGroupPtr workload_group_ptr = nullptr;
702
0
                        std::string wg_info_str = "Workload Group not set";
703
0
                        if (params.__isset.workload_groups && !params.workload_groups.empty()) {
704
0
                            uint64_t wg_id = params.workload_groups[0].id;
705
0
                            workload_group_ptr = _exec_env->workload_group_mgr()->get_group(wg_id);
706
0
                            if (workload_group_ptr != nullptr) {
707
0
                                wg_info_str = workload_group_ptr->debug_string();
708
0
                            } else {
709
0
                                wg_info_str = "set wg but not find it in be";
710
0
                            }
711
0
                        }
712
713
                        // First time a fragment of a query arrived. print logs.
714
0
                        LOG(INFO) << "query_id: " << print_id(query_id)
715
0
                                  << ", coord_addr: " << params.coord
716
0
                                  << ", total fragment num on current host: "
717
0
                                  << params.fragment_num_on_host
718
0
                                  << ", fe process uuid: " << params.query_options.fe_process_uuid
719
0
                                  << ", query type: " << params.query_options.query_type
720
0
                                  << ", report audit fe:" << params.current_connect_fe
721
0
                                  << ", use wg:" << wg_info_str;
722
723
                        // This may be a first fragment request of the query.
724
                        // Create the query fragments context.
725
0
                        query_ctx = QueryContext::create(query_id, _exec_env, params.query_options,
726
0
                                                         params.coord, params.is_nereids,
727
0
                                                         params.current_connect_fe, query_source);
728
0
                        SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(query_ctx->query_mem_tracker());
729
0
                        RETURN_IF_ERROR(DescriptorTbl::create(
730
0
                                &(query_ctx->obj_pool), params.desc_tbl, &(query_ctx->desc_tbl)));
731
                        // set file scan range params
732
0
                        if (params.__isset.file_scan_params) {
733
0
                            query_ctx->file_scan_range_params_map = params.file_scan_params;
734
0
                        }
735
736
0
                        query_ctx->query_globals = params.query_globals;
737
738
0
                        if (params.__isset.resource_info) {
739
0
                            query_ctx->user = params.resource_info.user;
740
0
                            query_ctx->group = params.resource_info.group;
741
0
                            query_ctx->set_rsc_info = true;
742
0
                        }
743
744
0
                        _set_scan_concurrency(params, query_ctx.get());
745
746
0
                        if (workload_group_ptr != nullptr) {
747
0
                            RETURN_IF_ERROR(workload_group_ptr->add_query(query_id, query_ctx));
748
0
                            query_ctx->set_workload_group(workload_group_ptr);
749
0
                        } else {
750
0
                            auto dummy_wg = _exec_env->workload_group_mgr()->dummy_workload_group();
751
0
                            query_ctx->set_workload_group(dummy_wg);
752
0
                        }
753
754
0
                        if (parent.__isset.runtime_filter_info) {
755
0
                            auto info = parent.runtime_filter_info;
756
0
                            if (info.__isset.runtime_filter_params) {
757
0
                                if (!info.runtime_filter_params.rid_to_runtime_filter.empty()) {
758
0
                                    auto handler =
759
0
                                            std::make_shared<RuntimeFilterMergeControllerEntity>();
760
0
                                    RETURN_IF_ERROR(
761
0
                                            handler->init(query_ctx, info.runtime_filter_params));
762
0
                                    query_ctx->set_merge_controller_handler(handler);
763
0
                                }
764
765
0
                                query_ctx->runtime_filter_mgr()->set_runtime_filter_params(
766
0
                                        info.runtime_filter_params);
767
0
                            }
768
0
                            if (info.__isset.topn_filter_descs) {
769
0
                                query_ctx->init_runtime_predicates(info.topn_filter_descs);
770
0
                            }
771
0
                        }
772
773
                        // There is some logic in query ctx's dctor, we could not check if exists and delete the
774
                        // temp query ctx now. For example, the query id maybe removed from workload group's queryset.
775
0
                        map.insert({query_id, query_ctx});
776
0
                        return Status::OK();
777
0
                    }));
778
0
        }
779
0
    }
780
0
    return Status::OK();
781
0
}
782
783
Status FragmentMgr::exec_plan_fragment(const TExecPlanFragmentParams& params,
784
0
                                       QuerySource query_source, const FinishCallback& cb) {
785
0
    return Status::InternalError("Non-pipeline is disabled!");
786
0
}
787
788
0
std::string FragmentMgr::dump_pipeline_tasks(int64_t duration) {
789
0
    fmt::memory_buffer debug_string_buffer;
790
0
    size_t i = 0;
791
0
    {
792
0
        fmt::format_to(debug_string_buffer,
793
0
                       "{} pipeline fragment contexts are still running! duration_limit={}\n",
794
0
                       _pipeline_map.num_items(), duration);
795
0
        timespec now;
796
0
        clock_gettime(CLOCK_MONOTONIC, &now);
797
798
0
        _pipeline_map.apply([&](phmap::flat_hash_map<
799
0
                                    std::pair<TUniqueId, int>,
800
0
                                    std::shared_ptr<pipeline::PipelineFragmentContext>>& map)
801
0
                                    -> Status {
802
0
            for (auto& it : map) {
803
0
                auto elapsed = it.second->elapsed_time() / 1000000000.0;
804
0
                if (elapsed < duration) {
805
                    // Only display tasks which has been running for more than {duration} seconds.
806
0
                    continue;
807
0
                }
808
0
                auto timeout_second = it.second->timeout_second();
809
0
                fmt::format_to(
810
0
                        debug_string_buffer,
811
0
                        "No.{} (elapse_second={}s, query_timeout_second={}s, is_timeout={}) : {}\n",
812
0
                        i, elapsed, timeout_second, it.second->is_timeout(now),
813
0
                        it.second->debug_string());
814
0
                i++;
815
0
            }
816
0
            return Status::OK();
817
0
        });
818
0
    }
819
0
    return fmt::to_string(debug_string_buffer);
820
0
}
821
822
0
std::string FragmentMgr::dump_pipeline_tasks(TUniqueId& query_id) {
823
0
    if (auto q_ctx = get_query_ctx(query_id)) {
824
0
        return q_ctx->print_all_pipeline_context();
825
0
    } else {
826
0
        return fmt::format(
827
0
                "Dump pipeline tasks failed: Query context (query id = {}) not found. \n",
828
0
                print_id(query_id));
829
0
    }
830
0
}
831
832
Status FragmentMgr::exec_plan_fragment(const TPipelineFragmentParams& params,
833
                                       QuerySource query_source, const FinishCallback& cb,
834
0
                                       const TPipelineFragmentParamsList& parent) {
835
0
    VLOG_ROW << "Query: " << print_id(params.query_id) << " exec_plan_fragment params is "
836
0
             << apache::thrift::ThriftDebugString(params).c_str();
837
    // sometimes TExecPlanFragmentParams debug string is too long and glog
838
    // will truncate the log line, so print query options seperately for debuggin purpose
839
0
    VLOG_ROW << "Query: " << print_id(params.query_id) << "query options is "
840
0
             << apache::thrift::ThriftDebugString(params.query_options).c_str();
841
842
0
    std::shared_ptr<QueryContext> query_ctx;
843
0
    RETURN_IF_ERROR(_get_or_create_query_ctx(params, parent, query_source, query_ctx));
844
0
    SCOPED_SWITCH_RESOURCE_CONTEXT(query_ctx.get()->resource_ctx());
845
0
    int64_t duration_ns = 0;
846
0
    std::shared_ptr<pipeline::PipelineFragmentContext> context =
847
0
            std::make_shared<pipeline::PipelineFragmentContext>(
848
0
                    query_ctx->query_id(), params.fragment_id, query_ctx, _exec_env, cb,
849
0
                    std::bind<Status>(std::mem_fn(&FragmentMgr::trigger_pipeline_context_report),
850
0
                                      this, std::placeholders::_1, std::placeholders::_2));
851
0
    {
852
0
        SCOPED_RAW_TIMER(&duration_ns);
853
0
        Status prepare_st = Status::OK();
854
0
        ASSIGN_STATUS_IF_CATCH_EXCEPTION(prepare_st = context->prepare(params, _thread_pool.get()),
855
0
                                         prepare_st);
856
0
        if (!prepare_st.ok()) {
857
0
            query_ctx->cancel(prepare_st, params.fragment_id);
858
0
            return prepare_st;
859
0
        }
860
0
    }
861
0
    g_fragmentmgr_prepare_latency << (duration_ns / 1000);
862
863
0
    DBUG_EXECUTE_IF("FragmentMgr.exec_plan_fragment.failed",
864
0
                    { return Status::Aborted("FragmentMgr.exec_plan_fragment.failed"); });
865
0
    {
866
0
        int64 now = duration_cast<std::chrono::milliseconds>(
867
0
                            std::chrono::system_clock::now().time_since_epoch())
868
0
                            .count();
869
0
        g_fragment_executing_count << 1;
870
0
        g_fragment_last_active_time.set_value(now);
871
872
        // (query_id, fragment_id) is executed only on one BE, locks _pipeline_map.
873
0
        auto res = _pipeline_map.find({params.query_id, params.fragment_id});
874
0
        if (res != nullptr) {
875
0
            return Status::InternalError(
876
0
                    "exec_plan_fragment query_id({}) input duplicated fragment_id({})",
877
0
                    print_id(params.query_id), params.fragment_id);
878
0
        }
879
0
        _pipeline_map.insert({params.query_id, params.fragment_id}, context);
880
0
    }
881
882
0
    if (!params.__isset.need_wait_execution_trigger || !params.need_wait_execution_trigger) {
883
0
        query_ctx->set_ready_to_execute_only();
884
0
    }
885
886
0
    query_ctx->set_pipeline_context(params.fragment_id, context);
887
888
0
    RETURN_IF_ERROR(context->submit());
889
0
    return Status::OK();
890
0
}
891
892
template <typename Param>
893
0
void FragmentMgr::_set_scan_concurrency(const Param& params, QueryContext* query_ctx) {
894
#ifndef BE_TEST
895
    // If the token is set, the scan task will use limited_scan_pool in scanner scheduler.
896
    // Otherwise, the scan task will use local/remote scan pool in scanner scheduler
897
    if (params.query_options.__isset.resource_limit &&
898
        params.query_options.resource_limit.__isset.cpu_limit) {
899
        query_ctx->set_thread_token(params.query_options.resource_limit.cpu_limit, false);
900
    }
901
#endif
902
0
}
903
904
1
void FragmentMgr::cancel_query(const TUniqueId query_id, const Status reason) {
905
1
    std::shared_ptr<QueryContext> query_ctx = nullptr;
906
1
    {
907
1
        if (auto q_ctx = get_query_ctx(query_id)) {
908
0
            query_ctx = q_ctx;
909
1
        } else {
910
1
            LOG(WARNING) << "Query " << print_id(query_id)
911
1
                         << " does not exists, failed to cancel it";
912
1
            return;
913
1
        }
914
1
    }
915
0
    query_ctx->cancel(reason);
916
0
    _query_ctx_map.erase(query_id);
917
0
    LOG(INFO) << "Query " << print_id(query_id)
918
0
              << " is cancelled and removed. Reason: " << reason.to_string();
919
0
}
920
921
10
void FragmentMgr::cancel_worker() {
922
10
    LOG(INFO) << "FragmentMgr cancel worker start working.";
923
924
10
    timespec check_invalid_query_last_timestamp;
925
10
    clock_gettime(CLOCK_MONOTONIC, &check_invalid_query_last_timestamp);
926
927
14
    do {
928
14
        std::vector<TUniqueId> queries_lost_coordinator;
929
14
        std::vector<TUniqueId> queries_timeout;
930
14
        std::vector<TUniqueId> queries_pipeline_task_leak;
931
        // Fe process uuid -> set<QueryId>
932
14
        std::map<int64_t, std::unordered_set<TUniqueId>> running_queries_on_all_fes;
933
14
        const std::map<TNetworkAddress, FrontendInfo>& running_fes =
934
14
                ExecEnv::GetInstance()->get_running_frontends();
935
936
14
        timespec now;
937
14
        clock_gettime(CLOCK_MONOTONIC, &now);
938
939
14
        if (config::enable_pipeline_task_leakage_detect &&
940
14
            now.tv_sec - check_invalid_query_last_timestamp.tv_sec >
941
0
                    config::pipeline_task_leakage_detect_period_secs) {
942
0
            check_invalid_query_last_timestamp = now;
943
0
            running_queries_on_all_fes = _get_all_running_queries_from_fe();
944
14
        } else {
945
14
            running_queries_on_all_fes.clear();
946
14
        }
947
948
14
        std::vector<std::shared_ptr<pipeline::PipelineFragmentContext>> ctx;
949
14
        _pipeline_map.apply(
950
14
                [&](phmap::flat_hash_map<std::pair<TUniqueId, int>,
951
14
                                         std::shared_ptr<pipeline::PipelineFragmentContext>>& map)
952
1.79k
                        -> Status {
953
1.79k
                    ctx.reserve(ctx.size() + map.size());
954
1.79k
                    for (auto& pipeline_itr : map) {
955
0
                        ctx.push_back(pipeline_itr.second);
956
0
                    }
957
1.79k
                    return Status::OK();
958
1.79k
                });
959
14
        for (auto& c : ctx) {
960
0
            c->clear_finished_tasks();
961
0
        }
962
963
14
        std::unordered_map<std::shared_ptr<PBackendService_Stub>, BrpcItem> brpc_stub_with_queries;
964
14
        {
965
14
            _query_ctx_map.apply([&](phmap::flat_hash_map<TUniqueId, std::weak_ptr<QueryContext>>&
966
1.79k
                                             map) -> Status {
967
1.79k
                for (auto it = map.begin(); it != map.end();) {
968
0
                    if (auto q_ctx = it->second.lock()) {
969
0
                        if (q_ctx->is_timeout(now)) {
970
0
                            LOG_WARNING("Query {} is timeout", print_id(it->first));
971
0
                            queries_timeout.push_back(it->first);
972
0
                        } else if (config::enable_brpc_connection_check) {
973
0
                            auto brpc_stubs = q_ctx->get_using_brpc_stubs();
974
0
                            for (auto& item : brpc_stubs) {
975
0
                                if (!brpc_stub_with_queries.contains(item.second)) {
976
0
                                    brpc_stub_with_queries.emplace(item.second,
977
0
                                                                   BrpcItem {item.first, {q_ctx}});
978
0
                                } else {
979
0
                                    brpc_stub_with_queries[item.second].queries.emplace_back(q_ctx);
980
0
                                }
981
0
                            }
982
0
                        }
983
0
                        ++it;
984
0
                    } else {
985
0
                        it = map.erase(it);
986
0
                    }
987
0
                }
988
1.79k
                return Status::OK();
989
1.79k
            });
990
991
            // We use a very conservative cancel strategy.
992
            // 0. If there are no running frontends, do not cancel any queries.
993
            // 1. If query's process uuid is zero, do not cancel
994
            // 2. If same process uuid, do not cancel
995
            // 3. If fe has zero process uuid, do not cancel
996
14
            if (running_fes.empty() && _query_ctx_map.num_items() != 0) {
997
0
                LOG_EVERY_N(WARNING, 10)
998
0
                        << "Could not find any running frontends, maybe we are upgrading or "
999
0
                           "starting? "
1000
0
                        << "We will not cancel any outdated queries in this situation.";
1001
14
            } else {
1002
14
                _query_ctx_map.apply([&](phmap::flat_hash_map<TUniqueId,
1003
14
                                                              std::weak_ptr<QueryContext>>& map)
1004
1.79k
                                             -> Status {
1005
1.79k
                    for (const auto& it : map) {
1006
0
                        if (auto q_ctx = it.second.lock()) {
1007
0
                            const int64_t fe_process_uuid = q_ctx->get_fe_process_uuid();
1008
1009
0
                            if (fe_process_uuid == 0) {
1010
                                // zero means this query is from a older version fe or
1011
                                // this fe is starting
1012
0
                                continue;
1013
0
                            }
1014
1015
                            // If the query is not running on the any frontends, cancel it.
1016
0
                            if (auto itr = running_queries_on_all_fes.find(fe_process_uuid);
1017
0
                                itr != running_queries_on_all_fes.end()) {
1018
                                // Query not found on this frontend, and the query arrives before the last check
1019
0
                                if (itr->second.find(it.first) == itr->second.end() &&
1020
                                    // tv_nsec represents the number of nanoseconds that have elapsed since the time point stored in tv_sec.
1021
                                    // tv_sec is enough, we do not need to check tv_nsec.
1022
0
                                    q_ctx->get_query_arrival_timestamp().tv_sec <
1023
0
                                            check_invalid_query_last_timestamp.tv_sec &&
1024
0
                                    q_ctx->get_query_source() == QuerySource::INTERNAL_FRONTEND) {
1025
0
                                    queries_pipeline_task_leak.push_back(q_ctx->query_id());
1026
0
                                    LOG_INFO(
1027
0
                                            "Query {}, type {} is not found on any frontends, "
1028
0
                                            "maybe it "
1029
0
                                            "is leaked.",
1030
0
                                            print_id(q_ctx->query_id()),
1031
0
                                            toString(q_ctx->get_query_source()));
1032
0
                                    continue;
1033
0
                                }
1034
0
                            }
1035
1036
0
                            auto itr = running_fes.find(q_ctx->coord_addr);
1037
0
                            if (itr != running_fes.end()) {
1038
0
                                if (fe_process_uuid == itr->second.info.process_uuid ||
1039
0
                                    itr->second.info.process_uuid == 0) {
1040
0
                                    continue;
1041
0
                                } else {
1042
0
                                    LOG_WARNING(
1043
0
                                            "Coordinator of query {} restarted, going to cancel "
1044
0
                                            "it.",
1045
0
                                            print_id(q_ctx->query_id()));
1046
0
                                }
1047
0
                            } else {
1048
                                // In some rear cases, the rpc port of follower is not updated in time,
1049
                                // then the port of this follower will be zero, but acutally it is still running,
1050
                                // and be has already received the query from follower.
1051
                                // So we need to check if host is in running_fes.
1052
0
                                bool fe_host_is_standing =
1053
0
                                        std::any_of(running_fes.begin(), running_fes.end(),
1054
0
                                                    [&q_ctx](const auto& fe) {
1055
0
                                                        return fe.first.hostname ==
1056
0
                                                                       q_ctx->coord_addr.hostname &&
1057
0
                                                               fe.first.port == 0;
1058
0
                                                    });
1059
0
                                if (fe_host_is_standing) {
1060
0
                                    LOG_WARNING(
1061
0
                                            "Coordinator {}:{} is not found, but its host is still "
1062
0
                                            "running with an unstable brpc port, not going to "
1063
0
                                            "cancel "
1064
0
                                            "it.",
1065
0
                                            q_ctx->coord_addr.hostname, q_ctx->coord_addr.port,
1066
0
                                            print_id(q_ctx->query_id()));
1067
0
                                    continue;
1068
0
                                } else {
1069
0
                                    LOG_WARNING(
1070
0
                                            "Could not find target coordinator {}:{} of query {}, "
1071
0
                                            "going to "
1072
0
                                            "cancel it.",
1073
0
                                            q_ctx->coord_addr.hostname, q_ctx->coord_addr.port,
1074
0
                                            print_id(q_ctx->query_id()));
1075
0
                                }
1076
0
                            }
1077
0
                        }
1078
                        // Coordinator of this query has already dead or query context has been released.
1079
0
                        queries_lost_coordinator.push_back(it.first);
1080
0
                    }
1081
1.79k
                    return Status::OK();
1082
1.79k
                });
1083
14
            }
1084
14
        }
1085
1086
14
        if (config::enable_brpc_connection_check) {
1087
0
            for (auto it : brpc_stub_with_queries) {
1088
0
                if (!it.first) {
1089
0
                    LOG(WARNING) << "brpc stub is nullptr, skip it.";
1090
0
                    continue;
1091
0
                }
1092
0
                _check_brpc_available(it.first, it.second);
1093
0
            }
1094
0
        }
1095
1096
14
        if (!queries_lost_coordinator.empty()) {
1097
0
            LOG(INFO) << "There are " << queries_lost_coordinator.size()
1098
0
                      << " queries need to be cancelled, coordinator dead or restarted.";
1099
0
        }
1100
1101
14
        for (const auto& qid : queries_timeout) {
1102
0
            cancel_query(qid,
1103
0
                         Status::Error<ErrorCode::TIMEOUT>(
1104
0
                                 "FragmentMgr cancel worker going to cancel timeout instance "));
1105
0
        }
1106
1107
14
        for (const auto& qid : queries_pipeline_task_leak) {
1108
            // Cancel the query, and maybe try to report debug info to fe so that we can
1109
            // collect debug info by sql or http api instead of search log.
1110
0
            cancel_query(qid, Status::Error<ErrorCode::ILLEGAL_STATE>(
1111
0
                                      "Potential pipeline task leakage"));
1112
0
        }
1113
1114
14
        for (const auto& qid : queries_lost_coordinator) {
1115
0
            cancel_query(qid, Status::Error<ErrorCode::CANCELLED>(
1116
0
                                      "Source frontend is not running or restarted"));
1117
0
        }
1118
1119
14
    } while (!_stop_background_threads_latch.wait_for(
1120
14
            std::chrono::seconds(config::fragment_mgr_cancel_worker_interval_seconds)));
1121
10
    LOG(INFO) << "FragmentMgr cancel worker is going to exit.";
1122
10
}
1123
1124
void FragmentMgr::_check_brpc_available(const std::shared_ptr<PBackendService_Stub>& brpc_stub,
1125
0
                                        const BrpcItem& brpc_item) {
1126
0
    const std::string message = "hello doris!";
1127
0
    std::string error_message;
1128
0
    int32_t failed_count = 0;
1129
0
    const int64_t check_timeout_ms =
1130
0
            std::max<int64_t>(100, config::brpc_connection_check_timeout_ms);
1131
1132
0
    while (true) {
1133
0
        PHandShakeRequest request;
1134
0
        request.set_hello(message);
1135
0
        PHandShakeResponse response;
1136
0
        brpc::Controller cntl;
1137
0
        cntl.set_timeout_ms(check_timeout_ms);
1138
0
        cntl.set_max_retry(10);
1139
0
        brpc_stub->hand_shake(&cntl, &request, &response, nullptr);
1140
1141
0
        if (cntl.Failed()) {
1142
0
            error_message = cntl.ErrorText();
1143
0
            LOG(WARNING) << "brpc stub: " << brpc_item.network_address.hostname << ":"
1144
0
                         << brpc_item.network_address.port << " check failed: " << error_message;
1145
0
        } else if (response.has_status() && response.status().status_code() == 0) {
1146
0
            break;
1147
0
        } else {
1148
0
            error_message = response.DebugString();
1149
0
            LOG(WARNING) << "brpc stub: " << brpc_item.network_address.hostname << ":"
1150
0
                         << brpc_item.network_address.port << " check failed: " << error_message;
1151
0
        }
1152
0
        failed_count++;
1153
0
        if (failed_count == 2) {
1154
0
            for (const auto& query_wptr : brpc_item.queries) {
1155
0
                auto query = query_wptr.lock();
1156
0
                if (query && !query->is_cancelled()) {
1157
0
                    query->cancel(Status::InternalError("brpc(dest: {}:{}) check failed: {}",
1158
0
                                                        brpc_item.network_address.hostname,
1159
0
                                                        brpc_item.network_address.port,
1160
0
                                                        error_message));
1161
0
                }
1162
0
            }
1163
1164
0
            LOG(WARNING) << "remove brpc stub from cache: " << brpc_item.network_address.hostname
1165
0
                         << ":" << brpc_item.network_address.port << ", error: " << error_message;
1166
0
            ExecEnv::GetInstance()->brpc_internal_client_cache()->erase(
1167
0
                    brpc_item.network_address.hostname, brpc_item.network_address.port);
1168
0
            break;
1169
0
        }
1170
0
    }
1171
0
}
1172
1173
0
void FragmentMgr::debug(std::stringstream& ss) {}
1174
/*
1175
 * 1. resolve opaqued_query_plan to thrift structure
1176
 * 2. build TExecPlanFragmentParams
1177
 */
1178
Status FragmentMgr::exec_external_plan_fragment(const TScanOpenParams& params,
1179
                                                const TQueryPlanInfo& t_query_plan_info,
1180
                                                const TUniqueId& query_id,
1181
                                                const TUniqueId& fragment_instance_id,
1182
0
                                                std::vector<TScanColumnDesc>* selected_columns) {
1183
    // set up desc tbl
1184
0
    DescriptorTbl* desc_tbl = nullptr;
1185
0
    ObjectPool obj_pool;
1186
0
    Status st = DescriptorTbl::create(&obj_pool, t_query_plan_info.desc_tbl, &desc_tbl);
1187
0
    if (!st.ok()) {
1188
0
        LOG(WARNING) << "open context error: extract DescriptorTbl failure";
1189
0
        std::stringstream msg;
1190
0
        msg << " create DescriptorTbl error, should not be modified after returned Doris FE "
1191
0
               "processed";
1192
0
        return Status::InvalidArgument(msg.str());
1193
0
    }
1194
0
    TupleDescriptor* tuple_desc = desc_tbl->get_tuple_descriptor(0);
1195
0
    if (tuple_desc == nullptr) {
1196
0
        LOG(WARNING) << "open context error: extract TupleDescriptor failure";
1197
0
        std::stringstream msg;
1198
0
        msg << " get  TupleDescriptor error, should not be modified after returned Doris FE "
1199
0
               "processed";
1200
0
        return Status::InvalidArgument(msg.str());
1201
0
    }
1202
    // process selected columns form slots
1203
0
    for (const SlotDescriptor* slot : tuple_desc->slots()) {
1204
0
        TScanColumnDesc col;
1205
0
        col.__set_name(slot->col_name());
1206
0
        col.__set_type(to_thrift(slot->type().type));
1207
0
        selected_columns->emplace_back(std::move(col));
1208
0
    }
1209
1210
0
    VLOG_QUERY << "BackendService execute open()  TQueryPlanInfo: "
1211
0
               << apache::thrift::ThriftDebugString(t_query_plan_info);
1212
    // assign the param used to execute PlanFragment
1213
0
    TPipelineFragmentParams exec_fragment_params;
1214
0
    exec_fragment_params.protocol_version = (PaloInternalServiceVersion::type)0;
1215
0
    exec_fragment_params.__set_is_simplified_param(false);
1216
0
    exec_fragment_params.__set_fragment(t_query_plan_info.plan_fragment);
1217
0
    exec_fragment_params.__set_desc_tbl(t_query_plan_info.desc_tbl);
1218
1219
    // assign the param used for executing of PlanFragment-self
1220
0
    TPipelineInstanceParams fragment_exec_params;
1221
0
    exec_fragment_params.query_id = query_id;
1222
0
    fragment_exec_params.fragment_instance_id = fragment_instance_id;
1223
0
    exec_fragment_params.coord.hostname = "external";
1224
0
    std::map<::doris::TPlanNodeId, std::vector<TScanRangeParams>> per_node_scan_ranges;
1225
0
    std::vector<TScanRangeParams> scan_ranges;
1226
0
    std::vector<int64_t> tablet_ids = params.tablet_ids;
1227
0
    TNetworkAddress address;
1228
0
    address.hostname = BackendOptions::get_localhost();
1229
0
    address.port = doris::config::be_port;
1230
0
    std::map<int64_t, TTabletVersionInfo> tablet_info = t_query_plan_info.tablet_info;
1231
0
    for (auto tablet_id : params.tablet_ids) {
1232
0
        TPaloScanRange scan_range;
1233
0
        scan_range.db_name = params.database;
1234
0
        scan_range.table_name = params.table;
1235
0
        auto iter = tablet_info.find(tablet_id);
1236
0
        if (iter != tablet_info.end()) {
1237
0
            TTabletVersionInfo info = iter->second;
1238
0
            scan_range.tablet_id = tablet_id;
1239
0
            scan_range.version = std::to_string(info.version);
1240
            // Useless but it is required field in TPaloScanRange
1241
0
            scan_range.version_hash = "0";
1242
0
            scan_range.schema_hash = std::to_string(info.schema_hash);
1243
0
            scan_range.hosts.push_back(address);
1244
0
        } else {
1245
0
            std::stringstream msg;
1246
0
            msg << "tablet_id: " << tablet_id << " not found";
1247
0
            LOG(WARNING) << "tablet_id [ " << tablet_id << " ] not found";
1248
0
            return Status::NotFound(msg.str());
1249
0
        }
1250
0
        TScanRange doris_scan_range;
1251
0
        doris_scan_range.__set_palo_scan_range(scan_range);
1252
0
        TScanRangeParams scan_range_params;
1253
0
        scan_range_params.scan_range = doris_scan_range;
1254
0
        scan_ranges.push_back(scan_range_params);
1255
0
    }
1256
0
    per_node_scan_ranges.insert(std::make_pair((::doris::TPlanNodeId)0, scan_ranges));
1257
0
    fragment_exec_params.per_node_scan_ranges = per_node_scan_ranges;
1258
0
    exec_fragment_params.local_params.push_back(fragment_exec_params);
1259
0
    TQueryOptions query_options;
1260
0
    query_options.batch_size = params.batch_size;
1261
0
    query_options.execution_timeout = params.execution_timeout;
1262
0
    query_options.mem_limit = params.mem_limit;
1263
0
    query_options.query_type = TQueryType::EXTERNAL;
1264
0
    query_options.be_exec_version = BeExecVersionManager::get_newest_version();
1265
0
    exec_fragment_params.__set_query_options(query_options);
1266
0
    VLOG_ROW << "external exec_plan_fragment params is "
1267
0
             << apache::thrift::ThriftDebugString(exec_fragment_params).c_str();
1268
1269
0
    TPipelineFragmentParamsList mocked;
1270
0
    return exec_plan_fragment(exec_fragment_params, QuerySource::EXTERNAL_CONNECTOR, mocked);
1271
0
}
1272
1273
Status FragmentMgr::apply_filterv2(const PPublishFilterRequestV2* request,
1274
0
                                   butil::IOBufAsZeroCopyInputStream* attach_data) {
1275
0
    UniqueId queryid = request->query_id();
1276
0
    TUniqueId query_id;
1277
0
    query_id.__set_hi(queryid.hi);
1278
0
    query_id.__set_lo(queryid.lo);
1279
0
    if (auto q_ctx = get_query_ctx(query_id)) {
1280
0
        SCOPED_ATTACH_TASK(q_ctx.get());
1281
0
        RuntimeFilterMgr* runtime_filter_mgr = q_ctx->runtime_filter_mgr();
1282
0
        DCHECK(runtime_filter_mgr != nullptr);
1283
1284
        // 1. get the target filters
1285
0
        std::vector<std::shared_ptr<RuntimeFilterConsumer>> filters =
1286
0
                runtime_filter_mgr->get_consume_filters(request->filter_id());
1287
1288
        // 2. create the filter wrapper to replace or ignore/disable the target filters
1289
0
        if (!filters.empty()) {
1290
0
            RETURN_IF_ERROR(filters[0]->assign(*request, attach_data));
1291
0
            std::ranges::for_each(filters, [&](auto& filter) { filter->signal(filters[0].get()); });
1292
0
        }
1293
0
    }
1294
0
    return Status::OK();
1295
0
}
1296
1297
0
Status FragmentMgr::send_filter_size(const PSendFilterSizeRequest* request) {
1298
0
    UniqueId queryid = request->query_id();
1299
0
    TUniqueId query_id;
1300
0
    query_id.__set_hi(queryid.hi);
1301
0
    query_id.__set_lo(queryid.lo);
1302
1303
0
    if (config::enable_debug_points &&
1304
0
        DebugPoints::instance()->is_enable("FragmentMgr::send_filter_size.return_eof")) {
1305
0
        return Status::EndOfFile("inject FragmentMgr::send_filter_size.return_eof");
1306
0
    }
1307
1308
0
    if (auto q_ctx = get_query_ctx(query_id)) {
1309
0
        return q_ctx->get_merge_controller_handler()->send_filter_size(q_ctx, request);
1310
0
    } else {
1311
0
        return Status::EndOfFile(
1312
0
                "Send filter size failed: Query context (query-id: {}) not found, maybe "
1313
0
                "finished",
1314
0
                queryid.to_string());
1315
0
    }
1316
0
}
1317
1318
0
Status FragmentMgr::sync_filter_size(const PSyncFilterSizeRequest* request) {
1319
0
    UniqueId queryid = request->query_id();
1320
0
    TUniqueId query_id;
1321
0
    query_id.__set_hi(queryid.hi);
1322
0
    query_id.__set_lo(queryid.lo);
1323
0
    if (auto q_ctx = get_query_ctx(query_id)) {
1324
0
        try {
1325
0
            return q_ctx->runtime_filter_mgr()->sync_filter_size(request);
1326
0
        } catch (const Exception& e) {
1327
0
            return Status::InternalError(
1328
0
                    "Sync filter size failed: Query context (query-id: {}) error: {}",
1329
0
                    queryid.to_string(), e.what());
1330
0
        }
1331
0
    } else {
1332
0
        return Status::EndOfFile(
1333
0
                "Sync filter size failed: Query context (query-id: {}) already finished",
1334
0
                queryid.to_string());
1335
0
    }
1336
0
}
1337
1338
Status FragmentMgr::merge_filter(const PMergeFilterRequest* request,
1339
0
                                 butil::IOBufAsZeroCopyInputStream* attach_data) {
1340
0
    UniqueId queryid = request->query_id();
1341
1342
0
    TUniqueId query_id;
1343
0
    query_id.__set_hi(queryid.hi);
1344
0
    query_id.__set_lo(queryid.lo);
1345
0
    if (auto q_ctx = get_query_ctx(query_id)) {
1346
0
        SCOPED_ATTACH_TASK(q_ctx.get());
1347
0
        if (!q_ctx->get_merge_controller_handler()) {
1348
0
            return Status::InternalError("Merge filter failed: Merge controller handler is null");
1349
0
        }
1350
0
        return q_ctx->get_merge_controller_handler()->merge(q_ctx, request, attach_data);
1351
0
    } else {
1352
0
        return Status::EndOfFile(
1353
0
                "Merge filter size failed: Query context (query-id: {}) already finished",
1354
0
                queryid.to_string());
1355
0
    }
1356
0
}
1357
1358
void FragmentMgr::get_runtime_query_info(
1359
0
        std::vector<std::weak_ptr<ResourceContext>>* _resource_ctx_list) {
1360
0
    _query_ctx_map.apply(
1361
0
            [&](phmap::flat_hash_map<TUniqueId, std::weak_ptr<QueryContext>>& map) -> Status {
1362
0
                for (auto iter = map.begin(); iter != map.end();) {
1363
0
                    if (auto q_ctx = iter->second.lock()) {
1364
0
                        _resource_ctx_list->push_back(q_ctx->resource_ctx());
1365
0
                        iter++;
1366
0
                    } else {
1367
0
                        iter = map.erase(iter);
1368
0
                    }
1369
0
                }
1370
0
                return Status::OK();
1371
0
            });
1372
0
}
1373
1374
Status FragmentMgr::get_realtime_exec_status(const TUniqueId& query_id,
1375
0
                                             TReportExecStatusParams* exec_status) {
1376
0
    if (exec_status == nullptr) {
1377
0
        return Status::InvalidArgument("exes_status is nullptr");
1378
0
    }
1379
1380
0
    std::shared_ptr<QueryContext> query_context = get_query_ctx(query_id);
1381
0
    if (query_context == nullptr) {
1382
0
        return Status::NotFound("Query {} not found or released", print_id(query_id));
1383
0
    }
1384
1385
0
    *exec_status = query_context->get_realtime_exec_status();
1386
1387
0
    return Status::OK();
1388
0
}
1389
1390
} // namespace doris