Coverage Report

Created: 2026-08-05 13:32

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/runtime/runtime_query_statistics_mgr.cpp
Line
Count
Source
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/runtime_query_statistics_mgr.h"
19
20
#include <gen_cpp/FrontendService_types.h>
21
#include <gen_cpp/RuntimeProfile_types.h>
22
#include <gen_cpp/Status_types.h>
23
#include <gen_cpp/Types_types.h>
24
#include <thrift/TApplicationException.h>
25
26
#include <condition_variable>
27
#include <cstdint>
28
#include <memory>
29
#include <mutex>
30
#include <shared_mutex>
31
#include <string>
32
#include <tuple>
33
#include <unordered_map>
34
#include <vector>
35
36
#include "common/logging.h"
37
#include "common/status.h"
38
#include "core/block/block.h"
39
#include "information_schema/schema_scanner_helper.h"
40
#include "runtime/cluster_info.h"
41
#include "runtime/exec_env.h"
42
#include "runtime/workload_group/workload_group.h"
43
#include "util/client_cache.h"
44
#include "util/debug_util.h"
45
#include "util/threadpool.h"
46
#include "util/thrift_client.h"
47
#include "util/time.h"
48
#include "util/uid_util.h"
49
50
namespace doris {
51
// TODO: Currently this function is only used to report profile.
52
// In the future, all exec status and query statistics should be reported
53
// thorough this function.
54
static Status _do_report_exec_stats_rpc(const TNetworkAddress& coor_addr,
55
                                        const TReportExecStatusParams& req,
56
1.48k
                                        TReportExecStatusResult& res) {
57
1.48k
    Status client_status;
58
1.48k
    FrontendServiceConnection rpc_client(ExecEnv::GetInstance()->frontend_client_cache(), coor_addr,
59
1.48k
                                         config::thrift_rpc_timeout_ms, &client_status);
60
1.48k
    if (!client_status.ok()) {
61
0
        LOG_WARNING(
62
0
                "Could not get client rpc client of {} when reporting profiles, reason is {}, "
63
0
                "not reporting, profile will be lost",
64
0
                PrintThriftNetworkAddress(coor_addr), client_status.to_string());
65
0
        return Status::RpcError("Client rpc client failed");
66
0
    }
67
68
1.48k
    VLOG_DEBUG << "Sending profile";
69
70
1.48k
    try {
71
1.48k
        try {
72
1.48k
            rpc_client->reportExecStatus(res, req);
73
1.48k
        } catch (const apache::thrift::transport::TTransportException& e) {
74
0
            LOG_WARNING("Transport exception from {}, reason: {}, reopening",
75
0
                        PrintThriftNetworkAddress(coor_addr), e.what());
76
0
            client_status = rpc_client.reopen(config::thrift_rpc_timeout_ms);
77
0
            if (!client_status.ok()) {
78
0
                LOG_WARNING("Reopen failed, reason: {}", client_status.to_string());
79
0
                return Status::RpcError("Open rpc client failed");
80
0
            }
81
82
0
            rpc_client->reportExecStatus(res, req);
83
0
        }
84
1.48k
    } catch (apache::thrift::TApplicationException& e) {
85
0
        if (e.getType() == e.UNKNOWN_METHOD) {
86
0
            LOG_WARNING(
87
0
                    "Failed to report query profile to {} due to {}, usually because the frontend "
88
0
                    "is not upgraded, check the version",
89
0
                    PrintThriftNetworkAddress(coor_addr), e.what());
90
0
        } else {
91
0
            LOG_WARNING(
92
0
                    "Failed to report query profile to {}, reason: {}, you can see fe log for "
93
0
                    "details.",
94
0
                    PrintThriftNetworkAddress(coor_addr), e.what());
95
0
        }
96
0
        return Status::RpcError("Send stats failed");
97
0
    } catch (apache::thrift::TException& e) {
98
0
        LOG_WARNING("Failed to report query profile to {}, reason: {} ",
99
0
                    PrintThriftNetworkAddress(coor_addr), e.what());
100
0
        std::this_thread::sleep_for(
101
0
                std::chrono::milliseconds(config::thrift_client_retry_interval_ms * 2));
102
        // just reopen to disable this connection
103
0
        static_cast<void>(rpc_client.reopen(config::thrift_rpc_timeout_ms));
104
0
        return Status::RpcError("Transport exception when report query profile");
105
0
    } catch (std::exception& e) {
106
0
        LOG_WARNING(
107
0
                "Failed to report query profile to {}, reason: {}, you can see fe log for details.",
108
0
                PrintThriftNetworkAddress(coor_addr), e.what());
109
0
        return Status::RpcError("Send report query profile failed");
110
0
    }
111
112
1.48k
    return Status::OK();
113
1.48k
}
114
115
static void _report_query_profiles_function(
116
        std::unordered_map<
117
                TUniqueId,
118
                std::tuple<
119
                        TNetworkAddress,
120
                        std::unordered_map<int, std::vector<std::shared_ptr<TRuntimeProfileTree>>>>>
121
                profile_copy,
122
        std::unordered_map<std::pair<TUniqueId, int32_t>, std::shared_ptr<TRuntimeProfileTree>>
123
1.48k
                load_channel_profile_copy) {
124
    // query_id -> {coordinator_addr, {fragment_id -> std::vectpr<pipeline_profile>}}
125
1.48k
    for (auto& entry : profile_copy) {
126
1.48k
        const auto& query_id = entry.first;
127
1.48k
        const auto& coor_addr = std::get<0>(entry.second);
128
1.48k
        auto& fragment_profile_map = std::get<1>(entry.second);
129
130
1.48k
        if (fragment_profile_map.empty()) {
131
0
            auto msg = fmt::format("Query {} does not have profile", print_id(query_id));
132
0
            DCHECK(false) << msg;
133
0
            LOG_ERROR(msg);
134
0
            continue;
135
0
        }
136
137
1.48k
        std::vector<std::shared_ptr<TRuntimeProfileTree>> load_channel_profiles;
138
3.03k
        for (auto load_channel_profile : load_channel_profile_copy) {
139
3.03k
            if (load_channel_profile.second == nullptr) {
140
0
                auto msg = fmt::format(
141
0
                        "Register fragment profile {} {} failed, load channel profile is null",
142
0
                        print_id(query_id), -1);
143
0
                DCHECK(false) << msg;
144
0
                LOG_ERROR(msg);
145
0
                continue;
146
0
            }
147
148
3.03k
            load_channel_profiles.push_back(load_channel_profile.second);
149
3.03k
        }
150
151
1.48k
        TReportExecStatusParams req = RuntimeQueryStatisticsMgr::create_report_exec_status_params(
152
1.48k
                query_id, std::move(fragment_profile_map), std::move(load_channel_profiles),
153
1.48k
                /*is_done=*/true);
154
1.48k
        TReportExecStatusResult res;
155
156
1.48k
        auto rpc_status = _do_report_exec_stats_rpc(coor_addr, req, res);
157
158
1.48k
        if (res.status.status_code != TStatusCode::OK || !rpc_status.ok()) {
159
0
            LOG_WARNING("Query {} send profile to {} failed", print_id(query_id),
160
0
                        PrintThriftNetworkAddress(coor_addr));
161
1.48k
        } else {
162
1.48k
            VLOG_CRITICAL << fmt::format("Send {} profile succeed", print_id(query_id));
163
1.48k
        }
164
1.48k
    }
165
1.48k
}
166
167
TReportExecStatusParams RuntimeQueryStatisticsMgr::create_report_exec_status_params(
168
        const TUniqueId& query_id,
169
        std::unordered_map<int32_t, std::vector<std::shared_ptr<TRuntimeProfileTree>>>
170
                fragment_id_to_profile,
171
1.48k
        std::vector<std::shared_ptr<TRuntimeProfileTree>> load_channel_profiles, bool is_done) {
172
    // This function will clear the data of fragment_id_to_profile and load_channel_profiles.
173
1.48k
    TQueryProfile profile;
174
1.48k
    profile.__set_query_id(query_id);
175
176
1.48k
    std::map<int32_t, std::vector<TDetailedReportParams>> fragment_id_to_profile_req;
177
178
3.03k
    for (const auto& entry : fragment_id_to_profile) {
179
3.03k
        int32_t fragment_id = entry.first;
180
3.03k
        const std::vector<std::shared_ptr<TRuntimeProfileTree>>& fragment_profile = entry.second;
181
3.03k
        std::vector<TDetailedReportParams> detailed_params;
182
3.03k
        bool is_first = true;
183
8.71k
        for (auto pipeline_profile : fragment_profile) {
184
8.71k
            if (pipeline_profile == nullptr) {
185
0
                auto msg = fmt::format("Register fragment profile {} {} failed, profile is null",
186
0
                                       print_id(query_id), fragment_id);
187
0
                DCHECK(false) << msg;
188
0
                LOG_ERROR(msg);
189
0
                continue;
190
0
            }
191
192
8.71k
            TDetailedReportParams tmp;
193
8.71k
            THRIFT_MOVE_VALUES(tmp, profile, *pipeline_profile);
194
            // First profile is fragment level
195
8.71k
            tmp.__set_is_fragment_level(is_first);
196
8.71k
            is_first = false;
197
            // tmp.fragment_instance_id is not needed for pipeline x
198
8.71k
            detailed_params.push_back(std::move(tmp));
199
8.71k
        }
200
201
3.03k
        fragment_id_to_profile_req[fragment_id] = std::move(detailed_params);
202
3.03k
    }
203
204
1.48k
    if (fragment_id_to_profile_req.empty()) {
205
0
        LOG_WARNING("No fragment profile found for query {}", print_id(query_id));
206
0
    }
207
208
1.48k
    profile.__set_fragment_id_to_profile(fragment_id_to_profile_req);
209
210
1.48k
    std::vector<TRuntimeProfileTree> load_channel_profiles_req;
211
3.03k
    for (auto load_channel_profile : load_channel_profiles) {
212
3.03k
        if (load_channel_profile == nullptr) {
213
0
            auto msg = fmt::format(
214
0
                    "Register fragment profile {} {} failed, load channel profile is null",
215
0
                    print_id(query_id), -1);
216
0
            DCHECK(false) << msg;
217
0
            LOG_ERROR(msg);
218
0
            continue;
219
0
        }
220
221
3.03k
        load_channel_profiles_req.push_back(std::move(*load_channel_profile));
222
3.03k
    }
223
224
1.48k
    if (!load_channel_profiles_req.empty()) {
225
1.48k
        THRIFT_MOVE_VALUES(profile, load_channel_profiles, load_channel_profiles_req);
226
1.48k
    }
227
228
1.48k
    TReportExecStatusParams req;
229
1.48k
    THRIFT_MOVE_VALUES(req, query_profile, profile);
230
1.48k
    req.__set_backend_id(ExecEnv::GetInstance()->cluster_info()->backend_id);
231
    // invalid query id to avoid API compatibility during upgrade
232
1.48k
    req.__set_query_id(TUniqueId());
233
1.48k
    req.__set_done(is_done);
234
235
1.48k
    return req;
236
1.48k
}
237
238
6
Status RuntimeQueryStatisticsMgr::start_report_thread() {
239
6
    if (started.load()) {
240
0
        DCHECK(false) << "report thread has been started";
241
0
        LOG_ERROR("report thread has been started");
242
0
        return Status::InternalError("Report thread has been started");
243
0
    }
244
245
6
    started.store(true);
246
6
    ThreadPoolBuilder profile_report_thread_pool_builder("ReportProfileThreadPool");
247
248
6
    return profile_report_thread_pool_builder.set_max_threads(config::report_exec_status_thread_num)
249
6
            .build(&_thread_pool);
250
6
}
251
252
// 1. lock the profile_map.
253
// 2. copy the profile_map and load_channel_profile_map to local variables.
254
// 3. unlock the profile_map.
255
// 4. create a profile reporting task and add it to the thread pool.
256
1.48k
void RuntimeQueryStatisticsMgr::trigger_profile_reporting() {
257
1.48k
    decltype(_profile_map) profile_copy;
258
1.48k
    decltype(_load_channel_profile_map) load_channel_profile_copy;
259
260
1.48k
    {
261
1.48k
        std::unique_lock<std::mutex> lg(_profile_map_lock);
262
1.48k
        _profile_map.swap(profile_copy);
263
1.48k
        _load_channel_profile_map.swap(load_channel_profile_copy);
264
1.48k
    }
265
266
    // ATTN: Local variables are copied to avoid memory reclamation issues.
267
1.48k
    auto st = _thread_pool->submit_func([profile_copy, load_channel_profile_copy]() {
268
1.48k
        _report_query_profiles_function(profile_copy, load_channel_profile_copy);
269
1.48k
    });
270
271
1.48k
    if (!st.ok()) {
272
0
        LOG_WARNING("Failed to submit profile reporting task, reason: {}", st.to_string());
273
        // If the thread pool is full, we will not report the profile.
274
        // The profile will be lost.
275
0
        return;
276
0
    }
277
1.48k
}
278
279
30
void RuntimeQueryStatisticsMgr::stop_report_thread() {
280
30
    if (!started) {
281
28
        return;
282
28
    }
283
284
2
    LOG_INFO("All report threads are going to stop");
285
2
    _thread_pool->shutdown();
286
2
    LOG_INFO("All report threads stopped");
287
2
}
288
289
void RuntimeQueryStatisticsMgr::register_fragment_profile(
290
        const TUniqueId& query_id, const TNetworkAddress& coor_addr, int32_t fragment_id,
291
        std::vector<std::shared_ptr<TRuntimeProfileTree>> p_profiles,
292
3.03k
        std::shared_ptr<TRuntimeProfileTree> load_channel_profile) {
293
8.71k
    for (const auto& p : p_profiles) {
294
8.71k
        if (p == nullptr) {
295
0
            auto msg = fmt::format("Register fragment profile {} {} failed, profile is null",
296
0
                                   print_id(query_id), fragment_id);
297
0
            DCHECK(false) << msg;
298
0
            LOG_ERROR(msg);
299
0
            return;
300
0
        }
301
8.71k
    }
302
303
3.03k
    std::unique_lock<std::mutex> lg(_profile_map_lock);
304
305
3.03k
    if (!_profile_map.contains(query_id)) {
306
1.48k
        _profile_map[query_id] = std::make_tuple(
307
1.48k
                coor_addr,
308
1.48k
                std::unordered_map<int, std::vector<std::shared_ptr<TRuntimeProfileTree>>>());
309
1.48k
    }
310
311
3.03k
    std::unordered_map<int, std::vector<std::shared_ptr<TRuntimeProfileTree>>>&
312
3.03k
            fragment_profile_map = std::get<1>(_profile_map[query_id]);
313
3.03k
    fragment_profile_map.insert(std::make_pair(fragment_id, p_profiles));
314
315
3.03k
    if (load_channel_profile != nullptr) {
316
3.03k
        _load_channel_profile_map[std::make_pair(query_id, fragment_id)] = load_channel_profile;
317
3.03k
    }
318
319
3.03k
    VLOG_CRITICAL << fmt::format("register x profile done {}, fragment {}, profiles {}",
320
0
                                 print_id(query_id), fragment_id, p_profiles.size());
321
3.03k
}
322
323
void RuntimeQueryStatisticsMgr::register_resource_context(
324
313k
        std::string query_id, std::shared_ptr<ResourceContext> resource_ctx) {
325
313k
    std::lock_guard<std::shared_mutex> write_lock(_resource_contexts_map_lock);
326
    // Note: `group_commit_insert` will use the same `query_id` to submit multiple load tasks in sequence.
327
    // After the previous load task ends but QueryStatistics has not been reported to FE,
328
    // if the next load task with the same `query_id` starts to execute, `register_resource_context` will
329
    // find that `query_id` already exists in _resource_contexts_map.
330
    // At this time, directly overwriting the `resource_ctx` corresponding to the `query_id`
331
    // in `register_resource_context` will cause the previous load task not to be reported to FE.
332
    // DCHECK(_resource_contexts_map.find(query_id) == _resource_contexts_map.end());
333
313k
    _resource_contexts_map[query_id] = resource_ctx;
334
313k
}
335
336
4.39k
void RuntimeQueryStatisticsMgr::report_runtime_query_statistics() {
337
4.39k
    int64_t be_id = ExecEnv::GetInstance()->cluster_info()->backend_id;
338
    // 1 get query statistics map
339
    // <fe_addr, <query_id, <query_statistics, is_query_finished>>>
340
4.39k
    std::map<TNetworkAddress, std::map<std::string, std::pair<TQueryStatistics, bool>>> fe_qs_map;
341
4.39k
    std::map<std::string, std::pair<bool, bool>> qs_status; // <finished, timeout>
342
4.39k
    {
343
4.39k
        std::lock_guard<std::shared_mutex> write_lock(_resource_contexts_map_lock);
344
4.39k
        int64_t current_time = MonotonicMillis();
345
4.39k
        int64_t conf_qs_timeout = config::query_statistics_reserve_timeout_ms;
346
347
337k
        for (auto iter = _resource_contexts_map.begin(); iter != _resource_contexts_map.end();) {
348
332k
            std::string query_id = iter->first;
349
332k
            auto resource_ctx = iter->second;
350
332k
            bool is_query_finished = resource_ctx->task_controller()->is_finished();
351
332k
            bool is_timeout_after_finish = false;
352
332k
            if (is_query_finished) {
353
314k
                is_timeout_after_finish =
354
314k
                        (current_time - resource_ctx->task_controller()->finish_time()) >
355
314k
                        conf_qs_timeout;
356
314k
            }
357
358
            // external query not need to report to FE, so we can remove it directly.
359
332k
            if (resource_ctx->task_controller()->query_type() == TQueryType::EXTERNAL &&
360
332k
                is_query_finished) {
361
3
                iter = _resource_contexts_map.erase(iter);
362
332k
            } else {
363
332k
                if (resource_ctx->task_controller()->query_type() != TQueryType::EXTERNAL) {
364
332k
                    if (fe_qs_map.find(resource_ctx->task_controller()->fe_addr()) ==
365
332k
                        fe_qs_map.end()) {
366
3.00k
                        std::map<std::string, std::pair<TQueryStatistics, bool>> tmp_map;
367
3.00k
                        fe_qs_map[resource_ctx->task_controller()->fe_addr()] = std::move(tmp_map);
368
3.00k
                    }
369
370
332k
                    TQueryStatistics ret_t_qs;
371
332k
                    resource_ctx->to_thrift_query_statistics(&ret_t_qs);
372
332k
                    fe_qs_map.at(resource_ctx->task_controller()->fe_addr())[query_id] =
373
332k
                            std::make_pair(ret_t_qs, is_query_finished);
374
332k
                    qs_status[query_id] =
375
332k
                            std::make_pair(is_query_finished, is_timeout_after_finish);
376
332k
                }
377
378
332k
                iter++;
379
332k
            }
380
332k
        }
381
4.39k
    }
382
383
    // 2 report query statistics to fe
384
4.39k
    std::map<TNetworkAddress, bool> rpc_result;
385
4.39k
    for (auto& [addr, qs_map] : fe_qs_map) {
386
3.00k
        rpc_result[addr] = false;
387
        // 2.1 get client
388
3.00k
        Status coord_status;
389
3.00k
        FrontendServiceConnection coord(ExecEnv::GetInstance()->frontend_client_cache(), addr,
390
3.00k
                                        config::thrift_rpc_timeout_ms, &coord_status);
391
3.00k
        std::string add_str = PrintThriftNetworkAddress(addr);
392
3.00k
        if (!coord_status.ok()) {
393
0
            std::stringstream ss;
394
0
            LOG(WARNING) << "[report_query_statistics]could not get client " << add_str
395
0
                         << " when report workload runtime stats, reason:"
396
0
                         << coord_status.to_string();
397
0
            continue;
398
0
        }
399
400
3.00k
        auto reopen_coord = [&coord]() -> Status {
401
0
            std::this_thread::sleep_for(
402
0
                    std::chrono::milliseconds(config::thrift_client_retry_interval_ms * 2));
403
            // just reopen to disable this connection
404
0
            return coord.reopen(config::thrift_rpc_timeout_ms);
405
0
        };
406
407
        // 2.2 send report
408
3.00k
        TReportWorkloadRuntimeStatusParams report_runtime_params;
409
3.00k
        report_runtime_params.__set_backend_id(be_id);
410
411
        // Build the query statistics map with TQueryStatisticsResult
412
3.00k
        std::map<std::string, TQueryStatisticsResult> query_stats_result_map;
413
332k
        for (const auto& [query_id, query_stats_pair] : qs_map) {
414
332k
            TQueryStatisticsResult stats_result;
415
332k
            stats_result.__set_statistics(query_stats_pair.first);      // TQueryStatistics
416
332k
            stats_result.__set_query_finished(query_stats_pair.second); // is_query_finished
417
332k
            query_stats_result_map[query_id] = stats_result;
418
332k
        }
419
420
3.00k
        report_runtime_params.__set_query_statistics_result_map(query_stats_result_map);
421
422
3.00k
        TReportExecStatusParams params;
423
3.00k
        params.__set_report_workload_runtime_status(report_runtime_params);
424
425
3.00k
        TReportExecStatusResult res;
426
3.00k
        Status rpc_status;
427
428
3.00k
        try {
429
3.00k
            try {
430
3.00k
                coord->reportExecStatus(res, params);
431
3.00k
                rpc_result[addr] = true;
432
3.00k
            } catch (apache::thrift::transport::TTransportException& e) {
433
0
                rpc_status = reopen_coord();
434
0
                LOG_WARNING(
435
0
                        "[report_query_statistics] report to fe {} failed, reason:{}, try reopen.",
436
0
                        add_str, e.what());
437
0
                if (rpc_status.ok()) {
438
0
                    coord->reportExecStatus(res, params);
439
0
                    rpc_result[addr] = true;
440
0
                }
441
0
            }
442
3.00k
        } catch (apache::thrift::TApplicationException& e) {
443
0
            LOG_WARNING(
444
0
                    "[report_query_statistics]fe {} throw exception when report statistics, "
445
0
                    "reason:{}, you can see fe log for details.",
446
0
                    add_str, e.what());
447
0
            rpc_status = reopen_coord();
448
0
        } catch (apache::thrift::TException& e) {
449
0
            LOG_WARNING(
450
0
                    "[report_query_statistics]report workload runtime statistics to {} failed,  "
451
0
                    "reason: {}",
452
0
                    add_str, e.what());
453
0
            rpc_status = reopen_coord();
454
0
        } catch (std::exception& e) {
455
0
            LOG_WARNING(
456
0
                    "[report_query_statistics]unknown exception when report workload runtime "
457
0
                    "statistics to {}, reason:{}. ",
458
0
                    add_str, e.what());
459
0
        }
460
461
3.00k
        if (!rpc_status.ok()) {
462
0
            LOG_WARNING(
463
0
                    "[report_query_statistics]reopen thrift client failed when report "
464
0
                    "workload runtime statistics to {}, reason: {}",
465
0
                    add_str, rpc_status.to_string());
466
0
        }
467
3.00k
    }
468
469
    //  3 when query is finished and (last rpc is send success), remove finished query statistics
470
4.39k
    if (fe_qs_map.empty()) {
471
1.39k
        return;
472
1.39k
    }
473
474
3.00k
    {
475
3.00k
        std::lock_guard<std::shared_mutex> write_lock(_resource_contexts_map_lock);
476
3.00k
        for (auto& [addr, qs_map] : fe_qs_map) {
477
3.00k
            bool is_rpc_success = rpc_result[addr];
478
332k
            for (auto& [query_id, qs] : qs_map) {
479
332k
                auto& qs_status_pair = qs_status[query_id];
480
332k
                bool is_query_finished = qs_status_pair.first;
481
332k
                bool is_timeout_after_finish = qs_status_pair.second;
482
332k
                if ((is_rpc_success && is_query_finished) || is_timeout_after_finish) {
483
314k
                    _resource_contexts_map.erase(query_id);
484
314k
                }
485
332k
            }
486
3.00k
        }
487
3.00k
    }
488
3.00k
}
489
490
608
void RuntimeQueryStatisticsMgr::get_active_be_tasks_block(Block* block) {
491
608
    std::shared_lock<std::shared_mutex> read_lock(_resource_contexts_map_lock);
492
608
    int64_t be_id = ExecEnv::GetInstance()->cluster_info()->backend_id;
493
494
    // block's schema come from SchemaBackendActiveTasksScanner::_s_tbls_columns
495
93.0k
    for (auto& [query_id, resource_ctx] : _resource_contexts_map) {
496
93.0k
        TQueryStatistics tqs;
497
93.0k
        resource_ctx->to_thrift_query_statistics(&tqs);
498
93.0k
        SchemaScannerHelper::insert_int64_value(0, be_id, block);
499
93.0k
        SchemaScannerHelper::insert_string_value(
500
93.0k
                1, resource_ctx->task_controller()->fe_addr().hostname, block);
501
93.0k
        auto wg = resource_ctx->workload_group();
502
93.0k
        SchemaScannerHelper::insert_int64_value(2, wg ? wg->id() : -1, block);
503
93.0k
        SchemaScannerHelper::insert_string_value(3, query_id, block);
504
505
93.0k
        int64_t task_time =
506
93.0k
                resource_ctx->task_controller()->is_finished()
507
93.0k
                        ? resource_ctx->task_controller()->finish_time() -
508
84.2k
                                  resource_ctx->task_controller()->start_time()
509
93.0k
                        : MonotonicMillis() - resource_ctx->task_controller()->start_time();
510
93.0k
        SchemaScannerHelper::insert_int64_value(4, task_time, block);
511
93.0k
        SchemaScannerHelper::insert_int64_value(5, tqs.cpu_ms, block);
512
93.0k
        SchemaScannerHelper::insert_int64_value(6, tqs.scan_rows, block);
513
93.0k
        SchemaScannerHelper::insert_int64_value(7, tqs.scan_bytes, block);
514
93.0k
        SchemaScannerHelper::insert_int64_value(8, tqs.max_peak_memory_bytes, block);
515
93.0k
        SchemaScannerHelper::insert_int64_value(9, tqs.current_used_memory_bytes, block);
516
93.0k
        SchemaScannerHelper::insert_int64_value(10, tqs.shuffle_send_bytes, block);
517
93.0k
        SchemaScannerHelper::insert_int64_value(11, tqs.shuffle_send_rows, block);
518
519
93.0k
        std::stringstream ss;
520
93.0k
        ss << resource_ctx->task_controller()->query_type();
521
93.0k
        SchemaScannerHelper::insert_string_value(12, ss.str(), block);
522
93.0k
        SchemaScannerHelper::insert_int64_value(13, tqs.spill_write_bytes_to_local_storage, block);
523
93.0k
        SchemaScannerHelper::insert_int64_value(14, tqs.spill_read_bytes_from_local_storage, block);
524
93.0k
    }
525
608
}
526
527
Status RuntimeQueryStatisticsMgr::get_query_statistics(const std::string& query_id,
528
1
                                                       TQueryStatistics* query_stats) {
529
1
    std::shared_lock<std::shared_mutex> read_lock(_resource_contexts_map_lock);
530
531
1
    auto resource_ctx = _resource_contexts_map.find(query_id);
532
1
    if (resource_ctx == _resource_contexts_map.end()) {
533
0
        return Status::InternalError("failed to find query with id {}", query_id);
534
0
    }
535
536
1
    resource_ctx->second->to_thrift_query_statistics(query_stats);
537
1
    return Status::OK();
538
1
}
539
540
void RuntimeQueryStatisticsMgr::get_tasks_resource_context(
541
0
        std::vector<std::shared_ptr<ResourceContext>>& resource_ctxs) {
542
0
    std::shared_lock<std::shared_mutex> read_lock(_resource_contexts_map_lock);
543
0
    for (auto& iter : _resource_contexts_map) {
544
0
        resource_ctxs.push_back(iter.second);
545
0
    }
546
0
}
547
548
} // namespace doris