Coverage Report

Created: 2026-07-28 02:15

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