Coverage Report

Created: 2025-09-18 13:12

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