Coverage Report

Created: 2026-07-08 22:08

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