forked from redpanda-data/redpanda
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredpanda-gdb.py
1841 lines (1506 loc) · 59.9 KB
/
redpanda-gdb.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Scylla is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Scylla is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Scylla. If not, see <http://www.gnu.org/licenses/>.
#
# - Copyright (C) 2015 ScyllaDB
# - Copyright 2020 Redpanda Data, Inc. - libc++ support and redpanda types
#
# -----
#
# (gdb) source redpanda-gdb.py
# (gdb) redpanda memory
#
import gdb
import gdb.printing
import uuid
import argparse
import re
from operator import attrgetter
from collections import defaultdict, Counter
import sys
import struct
import random
import bisect
import os
import subprocess
import time
import socket
class std_unique_ptr:
def __init__(self, obj):
self.obj = obj
def get(self):
# return self.obj['_M_t']['_M_t']['_M_head_impl']
return self.obj['__ptr_']['__value_']
def dereference(self):
return self.get().dereference()
def __getitem__(self, item):
return self.dereference()[item]
def address(self):
return self.get()
def __nonzero__(self):
return bool(self.get())
def __bool__(self):
return self.__nonzero__()
class std_optional:
def __init__(self, ref):
self.ref = ref
def get(self):
assert self.__bool__()
try:
return self.ref['__val_']
except gdb.error:
return self.ref['__value_'].dereference()
def __bool__(self):
try:
return bool(self.ref['__engaged_'])
except gdb.error:
return bool(self.ref['__value_'])
class fragmented_vector:
def __init__(self, ref):
self.ref = ref
self.container_type = self.ref.type.strip_typedefs()
self.element_type = self.container_type.template_argument(0)
self.element_size_bytes = self.element_type.sizeof
def size_bytes_capacity(self):
return self.capacity() * self.element_size_bytes
def __len__(self):
return int(self.ref['_size'])
def capacity(self):
return int(self.ref['_capacity'])
def size_bytes(self):
return len(self) * self.element_size_bytes
class std_vector:
def __init__(self, ref):
self.ref = ref
self.container_type = self.ref.type.strip_typedefs()
self.element_type = self.container_type.template_argument(0)
self.element_size_bytes = self.element_type.sizeof
end_cap_type = self.ref["__end_cap_"].type.strip_typedefs()
end_cap_type = end_cap_type.template_argument(0)
end_cap_type_fmt = "std::__1::__compressed_pair_elem<{}, 0, false>"
try:
self.end_cap_type = gdb.lookup_type(
end_cap_type_fmt.format(end_cap_type))
except:
# Try converting "struct foo *" into "foo*": sometimes GDB reports the type
# one way, but expects us to give it the other way
# For example:
# std::__1::__compressed_pair_elem<seastar::shared_object*, 0, false>)
s = str(end_cap_type)
m = re.match("struct ([\w:]+) \*", s)
if m:
self.end_cap_type = gdb.lookup_type(
end_cap_type_fmt.format(m.group(1) + "*"))
else:
raise
def size_bytes(self):
return len(self) * self.element_size_bytes
def size_bytes_capacity(self):
# TODO: this is more direct
# end_cap = self.ref["__end_cap_"].address
# end_cap = end_cap.cast(self.end_cap_type.pointer())["__value_"]
# allocated = int(end_cap) - int(self.ref["__begin_"])
return self.capacity() * self.element_size_bytes
def capacity(self):
end_cap = self.ref["__end_cap_"].address
end_cap = end_cap.cast(self.end_cap_type.pointer())["__value_"]
return end_cap - self.ref["__begin_"]
def __len__(self):
return int(self.ref['__end_'] - self.ref['__begin_'])
def __iter__(self):
i = self.ref['__begin_']
end = self.ref['__end_']
while i != end:
yield i.dereference()
i += 1
def __getitem__(self, item):
return (self.ref['__begin_'] + item).dereference()
def __nonzero__(self):
return self.__len__() > 0
def __bool__(self):
return self.__nonzero__()
class absl_btree_map:
def __init__(self, ref):
self.ref = ref
def size(self):
# the size is the number of elements in the tree. absl also tracks the
# capacity of the tree since tree nodes may not all be full. when
# investigating memory usage, this could be an important difference.
return self.ref["tree_"]["size_"]
class absl_flat_hash_map:
signed_byte_t = gdb.lookup_type('int8_t')
def __init__(self, p):
self.map = p
container_type = self.map.type.strip_typedefs()
self.kt = container_type.template_argument(0)
self.vt = container_type.template_argument(1)
self._begin()
def capacity(self):
return self.map["capacity_"]
def __len__(self):
return self.map["size_"]
def _begin(self):
self.it_ctrl = self.map["ctrl_"]
self.it_slot = self.map["slots_"]
self._skip_empty_or_deleted()
def __iter__(self):
while self.it_ctrl != (self.map["ctrl_"] + self.map["capacity_"]):
value = self.it_slot["value"]
yield value["first"], value["second"]
self.it_ctrl += 1
self.it_slot += 1
self._skip_empty_or_deleted()
def _skip_empty_or_deleted(self):
while self._ctrl_value() < -1:
self.it_ctrl += 1
self.it_slot += 1
def _ctrl_value(self):
return self.it_ctrl.cast(self.signed_byte_t.pointer()).dereference()
def has_enable_lw_shared_from_this(type):
for f in type.fields():
if f.is_base_class and 'enable_lw_shared_from_this' in f.name:
return True
return False
def remove_prefix(s, prefix):
if s.startswith(prefix):
return s[len(prefix):]
return s
class seastar_lw_shared_ptr():
def __init__(self, ref):
self.ref = ref
self.elem_type = ref.type.template_argument(0)
def get(self):
if has_enable_lw_shared_from_this(self.elem_type):
return self.ref['_p'].cast(self.elem_type.pointer())
else:
type = gdb.lookup_type(
'seastar::shared_ptr_no_esft<%s>' % remove_prefix(
str(self.elem_type.unqualified()), 'class ')).pointer()
return self.ref['_p'].cast(type)['_value'].address
class seastar_shared_ptr():
def __init__(self, ref):
self.ref = ref
def get(self):
return self.ref['_p']
class seastar_sstring:
def __init__(self, ref):
self.ref = ref
def __len__(self):
if self.ref['u']['internal']['size'] >= 0:
return int(self.ref['u']['internal']['size'])
else:
return int(self.ref['u']['external']['size'])
class seastar_circular_buffer(object):
def __init__(self, ref):
self.ref = ref
def _mask(self, i):
return i & (int(self.ref['_impl']['capacity']) - 1)
def __iter__(self):
impl = self.ref['_impl']
st = impl['storage']
cap = impl['capacity']
i = impl['begin']
end = impl['end']
while i < end:
yield st[self._mask(i)]
i += 1
def size(self):
impl = self.ref['_impl']
return int(impl['end']) - int(impl['begin'])
def __len__(self):
return self.size()
def __getitem__(self, item):
impl = self.ref['_impl']
return (impl['storage'] +
self._mask(int(impl['begin']) + item)).dereference()
def external_memory_footprint(self):
impl = self.ref['_impl']
return int(
impl['capacity']) * self.ref.type.template_argument(0).sizeof
class seastar_static_vector:
def __init__(self, ref):
self.ref = ref
def __len__(self):
return int(self.ref['m_holder']['m_size'])
def __iter__(self):
t = self.ref.type.strip_typedefs()
value_type = t.template_argument(0)
try:
data = self.ref['m_holder']['storage']['data'].cast(
value_type.pointer())
except:
try:
data = self.ref['m_holder']['storage']['dummy']['dummy'].cast(
value_type.pointer()) # Scylla 3.1 compatibility
except gdb.error:
data = self.ref['m_holder']['storage']['dummy'].cast(
value_type.pointer()) # Scylla 3.0 compatibility
for i in range(self.__len__()):
yield data[i]
def __nonzero__(self):
return self.__len__() > 0
def __bool__(self):
return self.__nonzero__()
class histogram:
"""Simple histogram.
Aggregate items by their count and present them in a histogram format.
Example:
h = histogram()
h['item1'] = 20 # Set an absolute value
h.add('item2') # Equivalent to h['item2'] += 1
h.add('item2')
h.add('item3')
h.print_to_console()
Would print:
4 item1 ++++++++++++++++++++++++++++++++++++++++
2 item2 ++++
1 item1 ++
Note that the number of indicators ('+') is does not correspond to the
actual number of items, rather it is supposed to illustrate their relative
counts.
"""
_column_count = 40
def __init__(self, counts=None, print_indicators=True, formatter=None):
"""Constructor.
Params:
* counts: initial counts (default to empty).
* print_indicators: print the '+' characters to illustrate relative
count. Can be turned off when the item names are very long and would
thus make indicators unreadable.
* formatter: a callable that receives the item as its argument and is
expected to return the string to be printed in the second column.
By default, items are printed verbatim.
"""
if counts is None:
self._counts = defaultdict(int)
else:
self._counts = counts
self._print_indicators = print_indicators
def default_formatter(value):
return str(value)
if formatter is None:
self._formatter = default_formatter
else:
self._formatter = formatter
def __len__(self):
return len(self._counts)
def __nonzero__(self):
return bool(len(self))
def __getitem__(self, item):
return self._counts[item]
def __setitem__(self, item, value):
self._counts[item] = value
def add(self, item):
self._counts[item] += 1
def __str__(self):
if not self._counts:
return ''
by_counts = defaultdict(list)
for k, v in self._counts.items():
by_counts[v].append(k)
counts_sorted = list(reversed(sorted(by_counts.keys())))
max_count = counts_sorted[0]
if max_count == 0:
count_per_column = 0
else:
count_per_column = self._column_count / max_count
lines = []
for count in counts_sorted:
items = by_counts[count]
if self._print_indicators:
indicator = '+' * max(1, int(count * count_per_column))
else:
indicator = ''
for item in items:
lines.append('{:9d} {} {}'.format(count, self._formatter(item),
indicator))
return '\n'.join(lines)
def __repr__(self):
return 'histogram({})'.format(self._counts)
def print_to_console(self):
gdb.write(str(self) + '\n')
def cpus():
return int(gdb.parse_and_eval('::seastar::smp::count'))
def current_shard():
return int(gdb.parse_and_eval('\'seastar\'::local_engine->_id'))
def get_local_task_queues():
""" Return a list of task pointers for the local reactor. """
for tq_ptr in seastar_static_vector(
gdb.parse_and_eval('\'seastar\'::local_engine._task_queues')):
yield std_unique_ptr(tq_ptr).dereference()
# addr (int) -> name (str)
names = {}
def resolve(addr, cache=True, startswith=None):
if addr in names:
return names[addr]
infosym = gdb.execute('info symbol 0x%x' % (addr), False, True)
if infosym.startswith('No symbol'):
return None
name = infosym[:infosym.find('in section')]
if startswith and not name.startswith(startswith):
return None
if cache:
names[addr] = name
return name
def get_text_range():
try:
vptr_type = gdb.lookup_type('uintptr_t').pointer()
reactor_backend = gdb.parse_and_eval('seastar::local_engine->_backend')
reactor_backend = std_unique_ptr(reactor_backend).get()
# NOAH in clang it looks like things start with std::__1::unique_ptr
## 2019.1 has value member, >=3.0 has std::unique_ptr<>
#if reactor_backend.type.strip_typedefs().name.startswith('std::unique_ptr<'):
# reactor_backend = std_unique_ptr(reactor_backend).get()
#else:
# reactor_backend = gdb.parse_and_eval('&seastar::local_engine->_backend')
known_vptr = int(
reactor_backend.reinterpret_cast(vptr_type).dereference())
except Exception as e:
gdb.write(
"get_text_range(): Falling back to locating .rodata section because lookup to reactor backend to use as known vptr failed: {}\n"
.format(e))
known_vptr = None
sections = gdb.execute('info files', False, True).split('\n')
for line in sections:
if known_vptr:
if not " is ." in line:
continue
items = line.split()
start = int(items[0], 16)
end = int(items[2], 16)
if start <= known_vptr and known_vptr <= end:
return start, end
# vptrs are in .rodata section
elif line.endswith("is .rodata"):
items = line.split()
text_start = int(items[0], 16)
text_end = int(items[2], 16)
return text_start, text_end
raise Exception("Failed to find text start and end")
def find_vptrs():
cpu_mem = gdb.parse_and_eval('\'seastar::memory::cpu_mem\'')
page_size = int(gdb.parse_and_eval('\'seastar::memory::page_size\''))
mem_start = cpu_mem['memory']
vptr_type = gdb.lookup_type('uintptr_t').pointer()
pages = cpu_mem['pages']
nr_pages = int(cpu_mem['nr_pages'])
text_start, text_end = get_text_range()
def is_vptr(addr):
return addr >= text_start and addr <= text_end
idx = 0
while idx < nr_pages:
if pages[idx]['free']:
idx += pages[idx]['span_size']
continue
pool = pages[idx]['pool']
if not pool or pages[idx]['offset_in_span'] != 0:
idx += 1
continue
objsize = int(pool.dereference()['_object_size'])
span_size = pages[idx]['span_size'] * page_size
for idx2 in range(0, int(span_size / objsize) + 1):
obj_addr = mem_start + idx * page_size + idx2 * objsize
vptr = obj_addr.reinterpret_cast(vptr_type).dereference()
if is_vptr(vptr):
yield obj_addr, vptr
idx += pages[idx]['span_size']
class span(object):
"""
Represents seastar allocator's memory span
"""
def __init__(self, index, start, page):
"""
:param index: index into cpu_mem.pages of the first page of the span
:param start: memory address of the first page of the span
:param page: seastar::memory::page* for the first page of the span
"""
self.index = index
self.start = start
self.page = page
def is_free(self):
return self.page['free']
def pool(self):
"""
Returns seastar::memory::small_pool* of this span.
Valid only when is_small().
"""
return self.page['pool']
def is_small(self):
return not self.is_free() and self.page['pool']
def is_large(self):
return not self.is_free() and not self.page['pool']
def size(self):
return int(self.page['span_size'])
def used_span_size(self):
"""
Returns the number of pages at the front of the span which are used by the allocator.
Due to https://github.com/scylladb/seastar/issues/625 there may be some
pages at the end of the span which are not used by the small pool.
We try to detect this. It's not 100% accurate but should work in most cases.
Returns 0 for free spans.
"""
n_pages = 0
pool = self.page['pool']
if self.page['free']:
return 0
if not pool:
return self.page['span_size']
for idx in range(int(self.page['span_size'])):
page = self.page.address + idx
if not page['pool'] or page['pool'] != pool or page[
'offset_in_span'] != idx:
break
n_pages += 1
return n_pages
def spans():
cpu_mem = gdb.parse_and_eval('\'seastar::memory::cpu_mem\'')
page_size = int(gdb.parse_and_eval('\'seastar::memory::page_size\''))
nr_pages = int(cpu_mem['nr_pages'])
pages = cpu_mem['pages']
mem_start = int(cpu_mem['memory'])
idx = 1
while idx < nr_pages:
page = pages[idx]
span_size = int(page['span_size'])
if span_size == 0:
idx += 1
continue
last_page = pages[idx + span_size - 1]
addr = mem_start + idx * page_size
yield span(idx, addr, page)
idx += span_size
class span_checker(object):
def __init__(self):
self._page_size = int(
gdb.parse_and_eval('\'seastar::memory::page_size\''))
span_list = list(spans())
self._start_to_span = dict((s.start, s) for s in span_list)
self._starts = list(s.start for s in span_list)
def spans(self):
return self._start_to_span.values()
def get_span(self, ptr):
idx = bisect.bisect_right(self._starts, ptr)
if idx == 0:
return None
span_start = self._starts[idx - 1]
s = self._start_to_span[span_start]
if span_start + s.page['span_size'] * self._page_size <= ptr:
return None
return s
def find_storage_api(shard=None):
if shard is None:
shard = current_shard()
return gdb.parse_and_eval('debug::app')['storage']['_instances'][
'__begin_'][shard]['service']['_p']
class index_state:
def __init__(self, ref):
self.ref = ref
self.offset = fragmented_vector(self.ref["relative_offset_index"])
self.time = fragmented_vector(self.ref["relative_time_index"])
self.pos = fragmented_vector(self.ref["position_index"])
def size(self):
return int(self.offset.size_bytes() + self.time.size_bytes() +
self.pos.size_bytes())
def capacities(self):
return (int(x) for x in (self.offset.size_bytes_capacity(),
self.time.size_bytes_capacity(),
self.pos.size_bytes_capacity()))
def capacity(self):
return int(sum(self.capacities()))
def __str__(self):
s = self.size() // 1024
c = self.capacity() // 1024
p = [x // 1024 for x in self.capacities()]
return f"Size (KB) {s:4} Capacity {c:4} (Contig off={p[0]:4} time={p[1]:4} pos={p[2]:4})"
class segment_index:
def __init__(self, ref):
self.ref = ref
def name(self):
return self.ref["_name"]
def state(self):
return index_state(self.ref["_state"])
class segment_reader:
def __init__(self, ref):
self.ref = ref
self.filename = self.ref["_filename"]
def __str__(self):
return "{}".format(self.filename)
class spill_key_index:
spill_key_index_t = gdb.lookup_type("storage::internal::spill_key_index")
def __init__(self, name, ref):
self._name = name
self.ref = ref.cast(self.spill_key_index_t.pointer())
def name(self):
return self._name
def index(self):
return absl_flat_hash_map(self.ref["_midx"])
class segment:
segment_t = gdb.lookup_type("storage::segment")
segment_t_size = segment_t.sizeof
def __init__(self, ref):
self.ref = ref
def compacted_index_writer(self):
o = std_optional(self.ref["_compaction_index"])
if o:
impl = std_unique_ptr(o.get()["_impl"]).get()
name = impl["_name"]
return spill_key_index(name, impl)
def batch_cache_index(self):
o = std_optional(self.ref["_cache"])
if o:
return absl_btree_map(o.get()["_index"])
def reader(self):
return segment_reader(self.ref["_reader"])
def index(self):
return segment_index(self.ref["_idx"])
def batch_cache_index_size_bytes(self):
index_opt = std_optional(self.ref["_cache"])
if not index_opt:
return 0
tree = btree_map(index_opt.get()["_index"])
return (24 + 8) * tree.size(), tree.size()
class segment_set:
def __init__(self, ref):
self.ref = ref
def __iter__(self):
segments = seastar_circular_buffer(self.ref["_handles"])
for ptr in segments:
yield segment(seastar_lw_shared_ptr(ptr).get())
def template_arguments(gdb_type):
n = 0
while True:
try:
yield gdb_type.template_argument(n)
n += 1
except RuntimeError:
return
def get_template_arg_with_prefix(gdb_type, prefix):
for arg in template_arguments(gdb_type):
if str(arg).startswith(prefix):
return arg
def get_field_offset(gdb_type, name):
for field in gdb_type.fields():
if field.name == name:
return int(field.bitpos / 8)
def get_base_class_offset(gdb_type, base_class_name):
name_pattern = re.escape(base_class_name) + "(<.*>)?$"
for field in gdb_type.fields():
if field.is_base_class and re.match(name_pattern,
field.type.strip_typedefs().name):
return int(field.bitpos / 8)
class boost_intrusive_list:
size_t = gdb.lookup_type('size_t')
def __init__(self, list_ref, link=None):
list_type = list_ref.type.strip_typedefs()
self.node_type = list_type.template_argument(0)
rps = list_ref['data_']['root_plus_size_']
try:
self.root = rps['root_']
except gdb.error:
# Some boost versions have this instead
self.root = rps['m_header']
if link is not None:
self.link_offset = get_field_offset(self.node_type, link)
else:
member_hook = get_template_arg_with_prefix(
list_type, "boost::intrusive::member_hook")
if not member_hook:
member_hook = get_template_arg_with_prefix(
list_type, "struct boost::intrusive::member_hook")
if member_hook:
self.link_offset = member_hook.template_argument(2).cast(
self.size_t)
else:
self.link_offset = get_base_class_offset(
self.node_type, "boost::intrusive::list_base_hook")
if self.link_offset is None:
raise Exception("Class does not extend list_base_hook: " +
str(self.node_type))
def __iter__(self):
hook = self.root['next_']
while hook and hook != self.root.address:
node_ptr = hook.cast(self.size_t) - self.link_offset
yield node_ptr.cast(self.node_type.pointer()).dereference()
hook = hook['next_']
def __nonzero__(self):
return self.root['next_'] != self.root.address
def __bool__(self):
return self.__nonzero__()
def __len__(self):
return len(list(iter(self)))
class readers_cache:
def __init__(self, ref):
self.ref = ref
self.readers = boost_intrusive_list(self.ref['_readers'], "_hook")
self.in_use = boost_intrusive_list(self.ref['_in_use'], "_hook")
class disk_log_impl:
disk_log_impl_t = gdb.lookup_type("storage::disk_log_impl")
def __init__(self, ref):
self.ref = ref.cast(self.disk_log_impl_t.pointer())
def segments(self):
return segment_set(self.ref["_segs"])
def readers_cache(self):
return readers_cache(std_unique_ptr(self.ref["_readers_cache"]).get())
def find_logs(shard=None):
storage = find_storage_api(shard)
log_mgr = std_unique_ptr(storage["_log_mgr"]).dereference()
for ntp, log in absl_flat_hash_map(log_mgr["_logs"]):
impl = seastar_shared_ptr(log["handle"]["_impl"]).get()
yield ntp, disk_log_impl(impl)
class redpanda_memory(gdb.Command):
"""Summarize the state of the shard's memory.
The goal of this summary is to provide a starting point when investigating
memory issues.
The summary consists of two parts:
* A high level overview.
* A per size-class population statistics.
In an OOM situation the latter usually shows the immediate symptoms, one
or more heavily populated size classes eating up all memory. The overview
can be used to identify the subsystem that owns these problematic objects.
"""
def __init__(self):
gdb.Command.__init__(self, 'redpanda memory', gdb.COMMAND_USER,
gdb.COMPLETE_COMMAND)
def print_kvstore_memory(self):
storage = find_storage_api()
kvstore = std_unique_ptr(storage["_kvstore"]).dereference()
db = absl_flat_hash_map(kvstore["_db"])
print(f"# Key value store")
gdb.write("key-value store:\n")
gdb.write(" size: {}\n".format(len(db)))
gdb.write(" capacity: {}\n".format(db.capacity()))
gdb.write("size bytes: {}\n".format(kvstore["_probe"]["cached_bytes"]))
def print_segment_memory(self):
print(f"# Log segments")
sizes = []
capacities = []
contigs = []
for ntp, log in find_logs():
for segment in log.segments():
index = segment.index().state()
contigs += index.capacities()
size, capacity = index.size(), index.capacity()
sizes.append(size)
capacities.append(capacity)
print(f"Partition {index} @ {ntp}")
print(f"Number of segments: {len(sizes)}")
print(f"Total capacity: {sum(capacities)//1024} KB")
print("Contiguous allocations (KB)")
contig_kb_counts = Counter((x // 1024 for x in contigs))
for size, freq in contig_kb_counts.most_common():
print(f"Size {size:4} Freq {freq}")
def print_readers_cache_memory(self):
print(f"# Readers cache")
total_readers = 0
for ntp, log in find_logs():
readers = len(log.readers_cache().readers)
in_use = len(log.readers_cache().in_use)
print(f"readers: {readers}, readers_in_use: {in_use} @ {ntp}")
total_readers += in_use
total_readers += readers
print(f"Total cached readers: {total_readers}")
def invoke(self, arg, from_tty):
self.print_kvstore_memory()
self.print_segment_memory()
self.print_readers_cache_memory()
cpu_mem = gdb.parse_and_eval('\'seastar::memory::cpu_mem\'')
page_size = int(gdb.parse_and_eval('\'seastar::memory::page_size\''))
free_mem = int(cpu_mem['nr_free_pages']) * page_size
total_mem = int(cpu_mem['nr_pages']) * page_size
gdb.write(
'Used memory: {used_mem:>13}\nFree memory: {free_mem:>13}\nTotal memory: {total_mem:>12}\n\n'
.format(used_mem=total_mem - free_mem,
free_mem=free_mem,
total_mem=total_mem))
gdb.write('Small pools:\n')
small_pools = cpu_mem['small_pools']
nr = small_pools['nr_small_pools']
gdb.write(
'{objsize:>5} {span_size:>6} {use_count:>10} {memory:>12} {unused:>12} {wasted_percent:>5}\n'
.format(objsize='objsz',
span_size='spansz',
use_count='usedobj',
memory='memory',
unused='unused',
wasted_percent='wst%'))
total_small_bytes = 0
sc = span_checker()
for i in range(int(nr)):
sp = small_pools['_u']['a'][i]
object_size = int(sp['_object_size'])
span_size = int(sp['_span_sizes']['preferred']) * page_size
free_count = int(sp['_free_count'])
pages_in_use = 0
use_count = 0
for s in sc.spans():
if s.pool() == sp.address:
pages_in_use += s.size()
use_count += int(s.used_span_size() * page_size /
object_size)
memory = pages_in_use * page_size
total_small_bytes += memory
use_count -= free_count
wasted = free_count * object_size
unused = memory - use_count * object_size
wasted_percent = wasted * 100.0 / memory if memory else 0
gdb.write(
'{objsize:5} {span_size:6} {use_count:10} {memory:12} {unused:12} {wasted_percent:5.1f}\n'
.format(objsize=object_size,
span_size=span_size,
use_count=use_count,
memory=memory,
unused=unused,
wasted_percent=wasted_percent))
gdb.write('Small allocations: %d [B]\n' % total_small_bytes)
large_allocs = defaultdict(
int) # key: span size [B], value: span count
for s in sc.spans():
span_size = s.size()
if s.is_large():
large_allocs[span_size * page_size] += 1
gdb.write('Page spans:\n')
gdb.write(
'{index:5} {size:>13} {total:>13} {allocated_size:>13} {allocated_count:>7}\n'
.format(index="index",
size="size [B]",
total="free [B]",
allocated_size="large [B]",
allocated_count="[spans]"))
total_large_bytes = 0
for index in range(int(cpu_mem['nr_span_lists'])):
span_list = cpu_mem['free_spans'][index]
front = int(span_list['_front'])
pages = cpu_mem['pages']
total = 0
while front:
span = pages[front]
total += int(span['span_size'])
front = int(span['link']['_next'])
span_size = (1 << index) * page_size
allocated_size = large_allocs[span_size] * span_size
total_large_bytes += allocated_size
gdb.write(
'{index:5} {size:13} {total:13} {allocated_size:13} {allocated_count:7}\n'
.format(index=index,
size=span_size,