Coverage Report

Created: 2026-07-12 14:58

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/runtime/runtime_profile.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
// This file is copied from
18
// https://github.com/apache/impala/blob/branch-2.9.0/be/src/util/runtime-profile.cc
19
// and modified by Doris
20
21
#include "runtime/runtime_profile.h"
22
23
#include <gen_cpp/RuntimeProfile_types.h>
24
#include <rapidjson/encodings.h>
25
#include <rapidjson/stringbuffer.h>
26
#include <rapidjson/writer.h>
27
28
#include <algorithm>
29
#include <iomanip>
30
#include <iostream>
31
#include <memory>
32
#include <string>
33
34
#include "common/logging.h"
35
#include "common/object_pool.h"
36
#include "runtime/runtime_profile_counter_tree_node.h"
37
#ifdef BE_TEST
38
#include "common/status.h" // For ErrorCode
39
#endif
40
41
namespace doris {
42
// Thread counters name
43
static const std::string THREAD_VOLUNTARY_CONTEXT_SWITCHES = "VoluntaryContextSwitches";
44
static const std::string THREAD_INVOLUNTARY_CONTEXT_SWITCHES = "InvoluntaryContextSwitches";
45
46
const std::string RuntimeProfile::ROOT_COUNTER;
47
48
6
std::unique_ptr<RuntimeProfile> RuntimeProfile::from_thrift(const TRuntimeProfileTree& node) {
49
6
    if (node.nodes.empty()) {
50
0
        return std::make_unique<RuntimeProfile>("");
51
0
    }
52
6
    TRuntimeProfileNode root_node = node.nodes.front();
53
6
    std::unique_ptr<RuntimeProfile> res = std::make_unique<RuntimeProfile>(root_node.name);
54
6
    res->update(node);
55
6
    return res;
56
6
}
57
58
6
std::unique_ptr<RuntimeProfile> RuntimeProfile::from_proto(const PRuntimeProfileTree& tree) {
59
6
    if (tree.nodes().empty()) {
60
0
        return std::make_unique<RuntimeProfile>("");
61
0
    }
62
63
6
    const PRuntimeProfileNode& root_node = tree.nodes(0);
64
6
    std::unique_ptr<RuntimeProfile> res = std::make_unique<RuntimeProfile>(root_node.name());
65
6
    res->update(tree);
66
6
    return res;
67
6
}
68
69
RuntimeProfile::RuntimeProfile(const std::string& name, bool is_averaged_profile)
70
2.48M
        : _pool(new ObjectPool()),
71
2.48M
          _name(name),
72
2.48M
          _metadata(-1),
73
2.48M
          _timestamp(-1),
74
2.48M
          _is_averaged_profile(is_averaged_profile),
75
2.48M
          _counter_total_time(TUnit::TIME_NS, 0, 3),
76
2.48M
          _local_time_percent(0) {
77
    // TotalTime counter has level3 to disable it from plan profile, because
78
    // it contains its child running time, we use exec time instead.
79
2.48M
    _counter_map["TotalTime"] = &_counter_total_time;
80
2.48M
}
81
82
2.48M
RuntimeProfile::~RuntimeProfile() = default;
83
84
4
bool RuntimeProfile::Counter::operator==(const Counter& other) const {
85
4
    return _value.load(std::memory_order_relaxed) == other._value.load(std::memory_order_relaxed) &&
86
4
           _type == other._type && _level == other._level;
87
4
}
88
89
48
void RuntimeProfile::merge(const RuntimeProfile* other) {
90
48
    DCHECK(other != nullptr);
91
92
    // Merge this level
93
48
    {
94
48
        CounterMap::iterator dst_iter;
95
48
        CounterMap::const_iterator src_iter;
96
48
        std::lock_guard<std::mutex> l(_counter_map_lock);
97
48
        std::lock_guard<std::mutex> m(other->_counter_map_lock);
98
99
136
        for (src_iter = other->_counter_map.begin(); src_iter != other->_counter_map.end();
100
88
             ++src_iter) {
101
88
            dst_iter = _counter_map.find(src_iter->first);
102
103
88
            if (dst_iter == _counter_map.end()) {
104
16
                _counter_map[src_iter->first] = _pool->add(src_iter->second->clone());
105
72
            } else {
106
72
                DCHECK(dst_iter->second->type() == src_iter->second->type());
107
108
72
                if (dst_iter->second->type() == TUnit::DOUBLE_VALUE) {
109
0
                    double new_val =
110
0
                            dst_iter->second->double_value() + src_iter->second->double_value();
111
0
                    dst_iter->second->set(new_val);
112
72
                } else {
113
72
                    dst_iter->second->update(src_iter->second->value());
114
72
                }
115
72
            }
116
88
        }
117
118
48
        ChildCounterMap::const_iterator child_counter_src_itr;
119
120
48
        for (child_counter_src_itr = other->_child_counter_map.begin();
121
84
             child_counter_src_itr != other->_child_counter_map.end(); ++child_counter_src_itr) {
122
36
            _child_counter_map[child_counter_src_itr->first].insert(
123
36
                    child_counter_src_itr->second.begin(), child_counter_src_itr->second.end());
124
36
        }
125
48
    }
126
127
48
    {
128
48
        std::lock_guard<std::mutex> l(_children_lock);
129
48
        std::lock_guard<std::mutex> m(other->_children_lock);
130
131
        // Recursively merge children with matching names
132
80
        for (int i = 0; i < other->_children.size(); ++i) {
133
32
            RuntimeProfile* other_child = other->_children[i].first;
134
32
            ChildMap::iterator j = _child_map.find(other_child->_name);
135
32
            RuntimeProfile* child = nullptr;
136
137
32
            if (j != _child_map.end()) {
138
20
                child = j->second;
139
20
            } else {
140
12
                child = _pool->add(new RuntimeProfile(other_child->_name));
141
12
                child->_local_time_percent = other_child->_local_time_percent;
142
12
                child->_metadata = other_child->_metadata;
143
12
                child->_timestamp = other_child->_timestamp;
144
12
                bool indent_other_child = other->_children[i].second;
145
12
                _child_map[child->_name] = child;
146
12
                _children.push_back(std::make_pair(child, indent_other_child));
147
12
            }
148
149
32
            child->merge(other_child);
150
32
        }
151
48
    }
152
48
}
153
154
18
void RuntimeProfile::update(const TRuntimeProfileTree& thrift_profile) {
155
18
    int idx = 0;
156
18
    update(thrift_profile.nodes, &idx);
157
18
    DCHECK_EQ(idx, thrift_profile.nodes.size());
158
18
}
159
160
18
void RuntimeProfile::update(const PRuntimeProfileTree& proto_profile) {
161
18
    int idx = 0;
162
18
    update(proto_profile.nodes(), &idx);
163
18
    DCHECK_EQ(idx, proto_profile.nodes_size());
164
18
}
165
166
42
void RuntimeProfile::update(const std::vector<TRuntimeProfileNode>& nodes, int* idx) {
167
42
    DCHECK_LT(*idx, nodes.size());
168
42
    const TRuntimeProfileNode& node = nodes[*idx];
169
42
    {
170
42
        std::lock_guard<std::mutex> l(_counter_map_lock);
171
        // update this level
172
42
        std::map<std::string, Counter*>::iterator dst_iter;
173
174
82
        for (int i = 0; i < node.counters.size(); ++i) {
175
40
            const TCounter& tcounter = node.counters[i];
176
40
            CounterMap::iterator j = _counter_map.find(tcounter.name);
177
178
40
            if (j == _counter_map.end()) {
179
28
                _counter_map[tcounter.name] =
180
28
                        _pool->add(new Counter(tcounter.type, tcounter.value));
181
28
            } else {
182
12
                if (j->second->type() != tcounter.type) {
183
0
                    LOG(ERROR) << "Cannot update counters with the same name (" << j->first
184
0
                               << ") but different types.";
185
12
                } else {
186
12
                    j->second->set(tcounter.value);
187
12
                }
188
12
            }
189
40
        }
190
191
42
        ChildCounterMap::const_iterator child_counter_src_itr;
192
193
42
        for (child_counter_src_itr = node.child_counters_map.begin();
194
70
             child_counter_src_itr != node.child_counters_map.end(); ++child_counter_src_itr) {
195
28
            _child_counter_map[child_counter_src_itr->first].insert(
196
28
                    child_counter_src_itr->second.begin(), child_counter_src_itr->second.end());
197
28
        }
198
42
    }
199
200
42
    {
201
42
        std::lock_guard<std::mutex> l(_info_strings_lock);
202
42
        const InfoStrings& info_strings = node.info_strings;
203
42
        for (const std::string& key : node.info_strings_display_order) {
204
            // Look for existing info strings and update in place. If there
205
            // are new strings, add them to the end of the display order.
206
            // TODO: Is nodes.info_strings always a superset of
207
            // _info_strings? If so, can just copy the display order.
208
8
            InfoStrings::const_iterator it = info_strings.find(key);
209
8
            DCHECK(it != info_strings.end());
210
8
            InfoStrings::iterator existing = _info_strings.find(key);
211
212
8
            if (existing == _info_strings.end()) {
213
6
                _info_strings.insert(std::make_pair(key, it->second));
214
6
                _info_strings_display_order.push_back(key);
215
6
            } else {
216
2
                _info_strings[key] = it->second;
217
2
            }
218
8
        }
219
42
    }
220
221
42
    ++*idx;
222
42
    {
223
42
        std::lock_guard<std::mutex> l(_children_lock);
224
225
        // update children with matching names; create new ones if they don't match
226
66
        for (int i = 0; i < node.num_children; ++i) {
227
24
            const TRuntimeProfileNode& tchild = nodes[*idx];
228
24
            ChildMap::iterator j = _child_map.find(tchild.name);
229
24
            RuntimeProfile* child = nullptr;
230
231
24
            if (j != _child_map.end()) {
232
10
                child = j->second;
233
14
            } else {
234
14
                child = _pool->add(new RuntimeProfile(tchild.name));
235
14
                child->_metadata = tchild.metadata;
236
14
                child->_timestamp = tchild.timestamp;
237
14
                _child_map[tchild.name] = child;
238
14
                _children.push_back(std::make_pair(child, tchild.indent));
239
14
            }
240
241
24
            child->update(nodes, idx);
242
24
        }
243
42
    }
244
42
}
245
246
void RuntimeProfile::update(const google::protobuf::RepeatedPtrField<PRuntimeProfileNode>& nodes,
247
42
                            int* idx) {
248
42
    DCHECK_LT(*idx, nodes.size());
249
42
    const PRuntimeProfileNode& node = nodes.Get(*idx);
250
251
42
    {
252
42
        std::lock_guard<std::mutex> l(_counter_map_lock);
253
254
42
        for (const auto& pcounter : node.counters()) {
255
40
            const std::string& name = pcounter.name();
256
40
            auto j = _counter_map.find(name);
257
258
40
            if (j == _counter_map.end()) {
259
28
                _counter_map[name] =
260
28
                        _pool->add(new Counter(unit_to_thrift(pcounter.type()), pcounter.value()));
261
28
            } else {
262
12
                if (unit_to_proto(j->second->type()) != pcounter.type()) {
263
0
                    LOG(ERROR) << "Cannot update counters with the same name (" << name
264
0
                               << ") but different types.";
265
12
                } else {
266
12
                    j->second->set(pcounter.value());
267
12
                }
268
12
            }
269
40
        }
270
271
42
        for (const auto& kv : node.child_counters_map()) {
272
40
            for (const auto& child_name : kv.second.child_counters()) {
273
40
                _child_counter_map[kv.first].insert(child_name);
274
40
            }
275
28
        }
276
42
    }
277
278
42
    {
279
42
        std::lock_guard<std::mutex> l(_info_strings_lock);
280
42
        const auto& info_map = node.info_strings();
281
282
42
        for (const std::string& key : node.info_strings_display_order()) {
283
8
            auto it = info_map.find(key);
284
8
            DCHECK(it != info_map.end());
285
286
8
            auto existing = _info_strings.find(key);
287
8
            if (existing == _info_strings.end()) {
288
6
                _info_strings.insert(std::make_pair(key, it->second));
289
6
                _info_strings_display_order.push_back(key);
290
6
            } else {
291
2
                _info_strings[key] = it->second;
292
2
            }
293
8
        }
294
42
    }
295
296
42
    ++*idx;
297
298
42
    {
299
42
        std::lock_guard<std::mutex> l(_children_lock);
300
66
        for (int i = 0; i < node.num_children(); ++i) {
301
24
            const PRuntimeProfileNode& pchild = nodes.Get(*idx);
302
24
            RuntimeProfile* child = nullptr;
303
304
24
            auto j = _child_map.find(pchild.name());
305
24
            if (j != _child_map.end()) {
306
10
                child = j->second;
307
14
            } else {
308
14
                child = _pool->add(new RuntimeProfile(pchild.name()));
309
14
                child->_metadata = pchild.metadata();
310
14
                child->_timestamp = pchild.timestamp();
311
14
                _child_map[pchild.name()] = child;
312
14
                _children.emplace_back(child, pchild.indent());
313
14
            }
314
315
24
            child->update(nodes, idx);
316
24
        }
317
42
    }
318
42
}
319
320
0
void RuntimeProfile::divide(int n) {
321
0
    DCHECK_GT(n, 0);
322
0
    std::map<std::string, Counter*>::iterator iter;
323
0
    {
324
0
        std::lock_guard<std::mutex> l(_counter_map_lock);
325
326
0
        for (iter = _counter_map.begin(); iter != _counter_map.end(); ++iter) {
327
0
            if (iter->second->type() == TUnit::DOUBLE_VALUE) {
328
0
                iter->second->set(iter->second->double_value() / n);
329
0
            } else {
330
0
                int64_t value = iter->second->_value.load();
331
0
                value = value / n;
332
0
                iter->second->_value.store(value);
333
0
            }
334
0
        }
335
0
    }
336
0
    {
337
0
        std::lock_guard<std::mutex> l(_children_lock);
338
339
0
        for (ChildMap::iterator i = _child_map.begin(); i != _child_map.end(); ++i) {
340
0
            i->second->divide(n);
341
0
        }
342
0
    }
343
0
}
344
345
0
void RuntimeProfile::clear_children() {
346
0
    std::lock_guard<std::mutex> l(_children_lock);
347
0
    _children.clear();
348
0
}
349
350
0
void RuntimeProfile::compute_time_in_profile() {
351
0
    compute_time_in_profile(total_time_counter()->value());
352
0
}
353
354
0
void RuntimeProfile::compute_time_in_profile(int64_t total) {
355
0
    if (total == 0) {
356
0
        return;
357
0
    }
358
359
    // Add all the total times in all the children
360
0
    int64_t total_child_time = 0;
361
0
    std::lock_guard<std::mutex> l(_children_lock);
362
363
0
    for (int i = 0; i < _children.size(); ++i) {
364
0
        total_child_time += _children[i].first->total_time_counter()->value();
365
0
    }
366
367
0
    int64_t local_time = total_time_counter()->value() - total_child_time;
368
    // Counters have some margin, set to 0 if it was negative.
369
0
    local_time = std::max<int64_t>(0L, local_time);
370
0
    _local_time_percent = static_cast<double>(local_time) / static_cast<double>(total);
371
0
    _local_time_percent = std::min(1.0, _local_time_percent) * 100;
372
373
    // Recurse on children
374
0
    for (int i = 0; i < _children.size(); ++i) {
375
0
        _children[i].first->compute_time_in_profile(total);
376
0
    }
377
0
}
378
379
268
RuntimeProfile* RuntimeProfile::create_child(const std::string& name, bool indent, bool prepend) {
380
268
    std::lock_guard<std::mutex> l(_children_lock);
381
268
    DCHECK(_child_map.find(name) == _child_map.end()) << ", name: " << name;
382
268
    RuntimeProfile* child = _pool->add(new RuntimeProfile(name));
383
268
    if (this->is_set_metadata()) {
384
0
        child->set_metadata(this->metadata());
385
0
    }
386
387
268
    if (_children.empty()) {
388
174
        add_child_unlock(child, indent, nullptr);
389
174
    } else {
390
94
        auto* pos = prepend ? _children.begin()->first : nullptr;
391
94
        add_child_unlock(child, indent, pos);
392
94
    }
393
268
    return child;
394
268
}
395
396
581k
void RuntimeProfile::add_child_unlock(RuntimeProfile* child, bool indent, RuntimeProfile* loc) {
397
581k
    DCHECK(child != nullptr);
398
581k
    _child_map[child->_name] = child;
399
400
581k
    if (loc == nullptr) {
401
581k
        _children.push_back(std::make_pair(child, indent));
402
581k
    } else {
403
78
        for (ChildVector::iterator it = _children.begin(); it != _children.end(); ++it) {
404
78
            if (it->first == loc) {
405
78
                _children.insert(it, std::make_pair(child, indent));
406
78
                return;
407
78
            }
408
78
        }
409
78
        DCHECK(false) << "Invalid loc";
410
0
    }
411
581k
}
412
413
581k
void RuntimeProfile::add_child(RuntimeProfile* child, bool indent, RuntimeProfile* loc) {
414
581k
    std::lock_guard<std::mutex> l(_children_lock);
415
581k
    add_child_unlock(child, indent, loc);
416
581k
}
417
418
1.57k
RuntimeProfile* RuntimeProfile::get_child(std::string name) {
419
1.57k
    std::lock_guard<std::mutex> l(_children_lock);
420
1.57k
    auto it = _child_map.find(name);
421
422
1.57k
    if (it == _child_map.end()) {
423
4
        return nullptr;
424
4
    }
425
426
1.56k
    return it->second;
427
1.57k
}
428
429
8
void RuntimeProfile::get_children(std::vector<RuntimeProfile*>* children) const {
430
8
    children->clear();
431
8
    std::lock_guard<std::mutex> l(_children_lock);
432
433
32
    for (ChildMap::const_iterator i = _child_map.begin(); i != _child_map.end(); ++i) {
434
24
        children->push_back(i->second);
435
24
    }
436
8
}
437
438
0
void RuntimeProfile::get_all_children(std::vector<RuntimeProfile*>* children) {
439
0
    std::lock_guard<std::mutex> l(_children_lock);
440
441
0
    for (ChildMap::iterator i = _child_map.begin(); i != _child_map.end(); ++i) {
442
0
        children->push_back(i->second);
443
0
        i->second->get_all_children(children);
444
0
    }
445
0
}
446
447
1.15M
void RuntimeProfile::add_info_string(const std::string& key, const std::string& value) {
448
1.15M
    std::lock_guard<std::mutex> l(_info_strings_lock);
449
1.15M
    InfoStrings::iterator it = _info_strings.find(key);
450
451
1.15M
    if (it == _info_strings.end()) {
452
1.15M
        _info_strings.insert(std::make_pair(key, value));
453
1.15M
        _info_strings_display_order.push_back(key);
454
1.15M
    } else {
455
340
        it->second = value;
456
340
    }
457
1.15M
}
458
459
72
const std::string* RuntimeProfile::get_info_string(const std::string& key) {
460
72
    std::lock_guard<std::mutex> l(_info_strings_lock);
461
72
    InfoStrings::const_iterator it = _info_strings.find(key);
462
463
72
    if (it == _info_strings.end()) {
464
4
        return nullptr;
465
4
    }
466
467
68
    return &it->second;
468
72
}
469
470
RuntimeProfile::HighWaterMarkCounter* RuntimeProfile::AddHighWaterMarkCounter(
471
        const std::string& name, TUnit::type unit, const std::string& parent_counter_name,
472
242k
        int64_t level) {
473
242k
    DCHECK_EQ(_is_averaged_profile, false);
474
242k
    std::lock_guard<std::mutex> l(_counter_map_lock);
475
242k
    if (_counter_map.find(name) != _counter_map.end()) {
476
178
        return reinterpret_cast<RuntimeProfile::HighWaterMarkCounter*>(_counter_map[name]);
477
178
    }
478
242k
    DCHECK(parent_counter_name == ROOT_COUNTER ||
479
242k
           _counter_map.find(parent_counter_name) != _counter_map.end());
480
242k
    RuntimeProfile::HighWaterMarkCounter* counter =
481
242k
            _pool->add(new RuntimeProfile::HighWaterMarkCounter(unit, level, parent_counter_name));
482
242k
    _counter_map[name] = counter;
483
242k
    _child_counter_map[parent_counter_name].insert(name);
484
242k
    return counter;
485
242k
}
486
487
RuntimeProfile::Counter* RuntimeProfile::add_counter(const std::string& name, TUnit::type type,
488
                                                     const std::string& parent_counter_name,
489
8.03M
                                                     int64_t level) {
490
8.03M
    std::lock_guard<std::mutex> l(_counter_map_lock);
491
492
8.03M
    if (_counter_map.find(name) != _counter_map.end()) {
493
8.46k
        return _counter_map[name];
494
8.46k
    }
495
496
    // Parent counter must already exist.
497
8.03M
    DCHECK(parent_counter_name == ROOT_COUNTER ||
498
8.02M
           _counter_map.find(parent_counter_name) != _counter_map.end());
499
500
8.02M
    Counter* counter = _pool->add(new Counter(type, 0, level));
501
8.02M
    _counter_map[name] = counter;
502
8.02M
    _child_counter_map[parent_counter_name].insert(name);
503
8.02M
    return counter;
504
8.03M
}
505
506
RuntimeProfile::NonZeroCounter* RuntimeProfile::add_nonzero_counter(
507
        const std::string& name, TUnit::type type, const std::string& parent_counter_name,
508
24
        int64_t level) {
509
24
    std::lock_guard<std::mutex> l(_counter_map_lock);
510
24
    if (_counter_map.find(name) != _counter_map.end()) {
511
0
        DCHECK(dynamic_cast<NonZeroCounter*>(_counter_map[name]));
512
0
        return static_cast<NonZeroCounter*>(_counter_map[name]);
513
0
    }
514
515
24
    DCHECK(parent_counter_name == ROOT_COUNTER ||
516
24
           _counter_map.find(parent_counter_name) != _counter_map.end());
517
24
    NonZeroCounter* counter = _pool->add(new NonZeroCounter(type, level, parent_counter_name));
518
24
    _counter_map[name] = counter;
519
24
    _child_counter_map[parent_counter_name].insert(name);
520
24
    return counter;
521
24
}
522
523
RuntimeProfile::DerivedCounter* RuntimeProfile::add_derived_counter(
524
        const std::string& name, TUnit::type type, const DerivedCounterFunction& counter_fn,
525
16
        const std::string& parent_counter_name) {
526
16
    std::lock_guard<std::mutex> l(_counter_map_lock);
527
528
16
    if (_counter_map.find(name) != _counter_map.end()) {
529
0
        return nullptr;
530
0
    }
531
532
16
    DerivedCounter* counter = _pool->add(new DerivedCounter(type, counter_fn));
533
16
    _counter_map[name] = counter;
534
16
    _child_counter_map[parent_counter_name].insert(name);
535
16
    return counter;
536
16
}
537
538
void RuntimeProfile::add_description(const std::string& name, const std::string& description,
539
144k
                                     std::string parent_counter_name) {
540
144k
    std::lock_guard<std::mutex> l(_counter_map_lock);
541
542
144k
    if (_counter_map.find(name) != _counter_map.end()) {
543
0
        Counter* counter = _counter_map[name];
544
0
        if (dynamic_cast<DescriptionEntry*>(counter) != nullptr) {
545
            // Do replace instead of update to avoid data race.
546
0
            _counter_map.erase(name);
547
0
        } else {
548
0
            DCHECK(false) << "Counter type mismatch, name: " << name
549
0
                          << ", type: " << counter->type() << ", description: " << description;
550
0
        }
551
0
    }
552
553
    // Parent counter must already exist.
554
144k
    DCHECK(parent_counter_name == ROOT_COUNTER ||
555
144k
           _counter_map.find(parent_counter_name) != _counter_map.end());
556
144k
    DescriptionEntry* counter = _pool->add(new DescriptionEntry(name, description));
557
144k
    _counter_map[name] = counter;
558
144k
    _child_counter_map[parent_counter_name].insert(name);
559
144k
}
560
561
RuntimeProfile::ConditionCounter* RuntimeProfile::add_conditition_counter(
562
        const std::string& name, TUnit::type type, const ConditionCounterFunction& counter_fn,
563
2
        const std::string& parent_counter_name, int64_t level) {
564
2
    std::lock_guard<std::mutex> l(_counter_map_lock);
565
566
2
    if (_counter_map.find(name) != _counter_map.end()) {
567
0
        RuntimeProfile::ConditionCounter* contition_counter =
568
0
                dynamic_cast<ConditionCounter*>(_counter_map[name]);
569
0
        if (contition_counter == nullptr) {
570
0
            throw doris::Exception(doris::ErrorCode::INTERNAL_ERROR,
571
0
                                   "Failed to add a conditition counter that is duplicate and of a "
572
0
                                   "different type for {}.",
573
0
                                   name);
574
0
        }
575
0
        return contition_counter;
576
0
    }
577
578
2
    ConditionCounter* counter = _pool->add(new ConditionCounter(type, counter_fn, level));
579
2
    _counter_map[name] = counter;
580
2
    _child_counter_map[parent_counter_name].insert(name);
581
2
    return counter;
582
2
}
583
584
12.8k
RuntimeProfile::Counter* RuntimeProfile::get_counter(const std::string& name) {
585
12.8k
    std::lock_guard<std::mutex> l(_counter_map_lock);
586
587
12.8k
    if (_counter_map.find(name) != _counter_map.end()) {
588
11.7k
        return _counter_map[name];
589
11.7k
    }
590
591
1.14k
    return nullptr;
592
12.8k
}
593
594
0
void RuntimeProfile::get_counters(const std::string& name, std::vector<Counter*>* counters) {
595
0
    Counter* c = get_counter(name);
596
597
0
    if (c != nullptr) {
598
0
        counters->push_back(c);
599
0
    }
600
601
0
    std::lock_guard<std::mutex> l(_children_lock);
602
603
0
    for (int i = 0; i < _children.size(); ++i) {
604
0
        _children[i].first->get_counters(name, counters);
605
0
    }
606
0
}
607
608
// Print the profile:
609
//  1. Profile Name
610
//  2. Info Strings
611
//  3. Counters
612
//  4. Children
613
void RuntimeProfile::pretty_print(std::ostream* s, const std::string& prefix,
614
270
                                  int64_t profile_level) const {
615
270
    std::ostream& stream = *s;
616
617
    // create copy of _counter_map and _child_counter_map so we don't need to hold lock
618
    // while we call value() on the counters
619
270
    CounterMap counter_map;
620
270
    ChildCounterMap child_counter_map;
621
270
    {
622
270
        std::lock_guard<std::mutex> l(_counter_map_lock);
623
270
        counter_map = _counter_map;
624
270
        child_counter_map = _child_counter_map;
625
270
    }
626
627
270
    std::map<std::string, Counter*>::const_iterator total_time = counter_map.find("TotalTime");
628
270
    DCHECK(total_time != counter_map.end());
629
630
270
    stream.flags(std::ios::fixed);
631
270
    stream << prefix << _name << ":";
632
633
270
    if (total_time->second->value() != 0) {
634
0
        stream << "(Active: "
635
0
               << PrettyPrinter::print(total_time->second->value(), total_time->second->type())
636
0
               << ", non-child: " << std::setprecision(2) << _local_time_percent << "%)";
637
0
    }
638
639
270
    stream << std::endl;
640
641
270
    {
642
270
        std::lock_guard<std::mutex> l(_info_strings_lock);
643
270
        for (const std::string& key : _info_strings_display_order) {
644
2
            stream << prefix << "   - " << key << ": " << _info_strings.find(key)->second
645
2
                   << std::endl;
646
2
        }
647
270
    }
648
649
    // Build counter tree and prune by profile_level before printing
650
270
    RuntimeProfileCounterTreeNode counter_tree =
651
270
            RuntimeProfileCounterTreeNode::from_map(counter_map, child_counter_map, ROOT_COUNTER);
652
270
    counter_tree = RuntimeProfileCounterTreeNode::prune_the_tree(counter_tree, profile_level);
653
270
    counter_tree.pretty_print(s, prefix);
654
655
    // create copy of _children so we don't need to hold lock while we call
656
    // pretty_print() on the children
657
270
    ChildVector children;
658
270
    {
659
270
        std::lock_guard<std::mutex> l(_children_lock);
660
270
        children = _children;
661
270
    }
662
663
442
    for (int i = 0; i < children.size(); ++i) {
664
172
        RuntimeProfile* profile = children[i].first;
665
172
        bool indent = children[i].second;
666
172
        profile->pretty_print(s, prefix + (indent ? "  " : ""));
667
172
    }
668
270
}
669
670
531
void RuntimeProfile::to_thrift(TRuntimeProfileTree* tree, int64_t profile_level) {
671
531
    tree->nodes.clear();
672
531
    to_thrift(&tree->nodes, profile_level);
673
531
}
674
675
547
void RuntimeProfile::to_thrift(std::vector<TRuntimeProfileNode>* nodes, int64_t profile_level) {
676
547
    size_t index = nodes->size();
677
547
    nodes->push_back(TRuntimeProfileNode());
678
547
    TRuntimeProfileNode& node = (*nodes)[index];
679
547
    node.name = _name;
680
547
    node.metadata = _metadata;
681
547
    node.timestamp = _timestamp;
682
547
    node.indent = true;
683
684
547
    {
685
547
        std::lock_guard<std::mutex> l(_counter_map_lock);
686
547
        RuntimeProfileCounterTreeNode conter_tree = RuntimeProfileCounterTreeNode::from_map(
687
547
                _counter_map, _child_counter_map, ROOT_COUNTER);
688
547
        conter_tree = RuntimeProfileCounterTreeNode::prune_the_tree(conter_tree, profile_level);
689
547
        conter_tree.to_thrift(node.counters, node.child_counters_map);
690
547
    }
691
692
547
    {
693
547
        std::lock_guard<std::mutex> l(_info_strings_lock);
694
547
        node.info_strings = _info_strings;
695
547
        node.info_strings_display_order = _info_strings_display_order;
696
547
    }
697
698
547
    ChildVector children;
699
547
    {
700
        // _children may be modified during to_thrift(),
701
        // so we have to lock and copy _children to avoid race condition
702
547
        std::lock_guard<std::mutex> l(_children_lock);
703
547
        children = _children;
704
547
    }
705
547
    node.num_children = cast_set<int32_t>(children.size());
706
547
    nodes->reserve(nodes->size() + children.size());
707
708
559
    for (int i = 0; i < children.size(); ++i) {
709
12
        size_t child_idx = nodes->size();
710
12
        children[i].first->to_thrift(nodes, profile_level);
711
        // fix up indentation flag
712
12
        (*nodes)[child_idx].indent = children[i].second;
713
12
    }
714
547
}
715
716
10
void RuntimeProfile::to_proto(PRuntimeProfileTree* tree, int64_t profile_level) {
717
10
    tree->clear_nodes();
718
10
    to_proto(tree->mutable_nodes(), profile_level);
719
10
}
720
721
void RuntimeProfile::to_proto(google::protobuf::RepeatedPtrField<PRuntimeProfileNode>* nodes,
722
22
                              int64_t profile_level) {
723
22
    PRuntimeProfileNode* node = nodes->Add(); // allocate new node
724
22
    node->set_name(_name);
725
22
    node->set_metadata(_metadata);
726
22
    node->set_timestamp(_timestamp);
727
22
    node->set_indent(true);
728
729
22
    {
730
22
        std::lock_guard<std::mutex> l(_counter_map_lock);
731
22
        RuntimeProfileCounterTreeNode counter_tree = RuntimeProfileCounterTreeNode::from_map(
732
22
                _counter_map, _child_counter_map, ROOT_COUNTER);
733
22
        counter_tree = RuntimeProfileCounterTreeNode::prune_the_tree(counter_tree, profile_level);
734
22
        counter_tree.to_proto(node->mutable_counters(), node->mutable_child_counters_map());
735
22
    }
736
737
22
    {
738
22
        std::lock_guard<std::mutex> l(_info_strings_lock);
739
22
        auto* info_map = node->mutable_info_strings();
740
22
        for (const auto& kv : _info_strings) {
741
6
            (*info_map)[kv.first] = kv.second;
742
6
        }
743
22
        for (const auto& key : _info_strings_display_order) {
744
6
            node->add_info_strings_display_order(key);
745
6
        }
746
22
    }
747
748
22
    ChildVector children;
749
22
    {
750
22
        std::lock_guard<std::mutex> l(_children_lock);
751
22
        children = _children;
752
22
    }
753
754
22
    node->set_num_children(cast_set<int32_t>(children.size()));
755
756
22
    for (const auto& child : children) {
757
12
        int child_index = cast_set<int>(nodes->size()); // capture index for indent correction
758
12
        child.first->to_proto(nodes, profile_level);
759
12
        (*nodes)[child_index].set_indent(child.second);
760
12
    }
761
22
}
762
763
int64_t RuntimeProfile::units_per_second(const RuntimeProfile::Counter* total_counter,
764
6
                                         const RuntimeProfile::Counter* timer) {
765
6
    DCHECK(total_counter->type() == TUnit::BYTES || total_counter->type() == TUnit::UNIT);
766
6
    DCHECK(timer->type() == TUnit::TIME_NS);
767
768
6
    if (timer->value() == 0) {
769
0
        return 0;
770
0
    }
771
772
6
    double secs = static_cast<double>(timer->value()) / 1000.0 / 1000.0 / 1000.0;
773
6
    return int64_t(static_cast<double>(total_counter->value()) / secs);
774
6
}
775
776
0
int64_t RuntimeProfile::counter_sum(const std::vector<Counter*>* counters) {
777
0
    int64_t value = 0;
778
779
0
    for (int i = 0; i < counters->size(); ++i) {
780
0
        value += (*counters)[i]->value();
781
0
    }
782
783
0
    return value;
784
0
}
785
786
void RuntimeProfile::print_child_counters(const std::string& prefix,
787
                                          const std::string& counter_name,
788
                                          const CounterMap& counter_map,
789
                                          const ChildCounterMap& child_counter_map,
790
0
                                          std::ostream* s) {
791
0
    auto itr = child_counter_map.find(counter_name);
792
793
0
    if (itr != child_counter_map.end()) {
794
0
        const std::set<std::string>& child_counters = itr->second;
795
0
        for (const std::string& child_counter : child_counters) {
796
0
            auto iter = counter_map.find(child_counter);
797
            DCHECK(iter != counter_map.end());
798
0
            iter->second->pretty_print(s, prefix, iter->first);
799
0
            RuntimeProfile::print_child_counters(prefix + "  ", child_counter, counter_map,
800
0
                                                 child_counter_map, s);
801
0
        }
802
0
    }
803
0
}
804
805
} // namespace doris