forked from TheJJ/ceph-balancer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplacementoptimizer.py
More file actions
executable file
·2557 lines (2027 loc) · 96.2 KB
/
placementoptimizer.py
File metadata and controls
executable file
·2557 lines (2027 loc) · 96.2 KB
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
"""
Ceph balancer.
(c) 2020-2022 Jonas Jelten <jj@sft.lol>
GPLv3 or later
"""
# some future TODOs to include in the optimization:
# maximum movement limits
# recommendations for pg num
# respect OMAP_BYTES and OMAP_KEYS for a pg
# don't touch a pool with decreasing pg_num
# a new mode that tries to eliminate upmap_items
# when considering an OSD for emptying, try pending PGs first
# ability to select pgs explicitly for better placement (move a backfill_tofull pg somewhere else)
# even "better" algorithm:
# get osdmap and crushmap
# calculate constraints weighted by device
# get current utilization weighted by device
# create z3 equation using these constraints
# transform result to upmap items
import argparse
import itertools
import json
import logging
import lzma
import shlex
import statistics
import subprocess
import datetime
from collections import defaultdict
from functools import lru_cache
from pprint import pformat, pprint
cli = argparse.ArgumentParser()
cli.add_argument("-v", "--verbose", action="count", default=0,
help="increase program verbosity")
cli.add_argument("-q", "--quiet", action="count", default=0,
help="decrease program verbosity")
sp = cli.add_subparsers(dest='mode')
sp.required=True
statep = argparse.ArgumentParser(add_help=False)
statep.add_argument("--state", "-s", help="load cluster state from this jsonfile")
gathersp = sp.add_parser('gather', help="only gather cluster information, i.e. generate a state file")
gathersp.add_argument("output_file", help="file to store cluster balancing information to")
showsp = sp.add_parser('show', parents=[statep])
showsp.add_argument('--only-crushclass',
help="only display devices of this crushclass")
showsp.add_argument('--sort-shardsize', action='store_true',
help="sort the pool overview by shardsize")
showsp.add_argument('--osds', action='store_true',
help="show info about all the osds instead of just the pool overview")
showsp.add_argument('--format', choices=['plain', 'json'], default='plain',
help="output formatting: plain or json. default: %(default)s")
showsp.add_argument('--pgstate', choices=['up', 'acting'], default='acting',
help="which PG state to consider: up (planned) or acting (active). default: %(default)s")
showsp.add_argument('--per-pool-count', action='store_true',
help="in text formatting mode, show how many pgs for each pool are mapped")
showsp.add_argument('--normalize-pg-count', action='store_true',
help="normalize the pg count by disk size")
showsp.add_argument('--sort-pg-count', type=int,
help="sort osds by pg count of given pool id")
showsp.add_argument('--sort-utilization', action='store_true',
help="sort osds by utilization")
showsp.add_argument('--use-weighted-utilization', action='store_true',
help="calculate osd utilization by weighting device size")
showsp.add_argument('--use-shardsize-sum', action='store_true',
help="calculate osd utilization by adding all PG shards on it")
showsp.add_argument('--osd-fill-min', type=int, default=0,
help='minimum fill %% to show an osd, default: %(default)s%%')
remappsp = sp.add_parser('showremapped', parents=[statep])
remappsp.add_argument('--by-osd', action='store_true',
help="group the results by osd")
remappsp.add_argument('--osds',
help="only look at these osds when using --by-osd, comma separated")
balancep = sp.add_parser('balance', parents=[statep])
balancep.add_argument('--max-pg-moves', '-m', type=int, default=10,
help='maximum number of pg movements to find, default: %(default)s')
balancep.add_argument('--only-pool',
help='comma separated list of pool names to consider for balancing')
balancep.add_argument('--only-poolid',
help='comma separated list of pool ids to consider for balancing')
balancep.add_argument('--only-crushclass',
help='comma separated list of crush classes to balance')
balancep.add_argument('--osdused', choices=["delta", "shardsum"], default="shardsum",
help=('how is the osd usage predicted? default: %(default)s. '
"delta=adjusting the osd usage report by pending pg deltas, more accurate but doesn't account pending data deletion. "
"shardsum=estimate the usage by summing up all pg shardsizes, doesn't account PG metadata."))
balancep.add_argument('--pg-size-choice', choices=['largest', 'median', 'auto'],
default='largest',
help=('method to select a PG move candidate on a OSD based on its size. '
'auto tries to determine the best PG size by looking at '
'the currently emptiest OSD. '
'default: %(default)s'))
balancep.add_argument('--ensure-optimal-moves', action='store_true',
help='make sure that only movements which win full shardsizes are done')
balancep.add_argument('--ensure-variance-decrease', action='store_true',
help='make sure that only movements which decrease the fill rate variance are performed')
balancep.add_argument('--osdsize', choices=['device', 'weighted', 'crush'], default="crush",
help="what parameter to take for determining the osd size. weighted=devsize*weight, crush=crushweight*weight")
balancep.add_argument('--max-full-move-attempts', type=int, default=1,
help="when the fullest osd can't be emptied more, "
"try this many more osds in descending fullness order.")
balancep.add_argument('--source-osds',
help="only consider these osds as movement source, separated by ','")
pooldiffp = sp.add_parser('poolosddiff', parents=[statep])
pooldiffp.add_argument('--pgstate', choices=['up', 'acting'], default="acting",
help="what pg set to take, up or acting (default acting).")
pooldiffp.add_argument('pool1',
help="use this pool for finding involved osds")
pooldiffp.add_argument('pool2',
help="compare to this pool which osds are involved")
sp.add_parser('repairstats', parents=[statep])
args = cli.parse_args()
def log_setup(setting, default=1):
"""
Perform setup for the logger.
Run before any logging.log thingy is called.
if setting is 0: the default is used, which is WARNING.
else: setting + default is used.
"""
levels = (logging.ERROR, logging.WARNING, logging.INFO,
logging.DEBUG, logging.NOTSET)
factor = clamp(default + setting, 0, len(levels) - 1)
level = levels[factor]
logging.basicConfig(level=level, format="[%(asctime)s] %(message)s")
logging.captureWarnings(True)
def clamp(number, smallest, largest):
""" return number but limit it to the inclusive given value range """
return max(smallest, min(number, largest))
log_setup(args.verbose - args.quiet)
class strlazy:
"""
to be used like this: logging.debug("rolf %s", strlazy(lambda: do_something()))
so do_something is only called when the debug message is actually printed
do_something could also be an f-string.
"""
def __init__(self, fun):
self.fun = fun
def __str__(self):
return self.fun()
def jsoncall(cmd, swallow_stderr=False):
if not isinstance(cmd, list):
raise ValueError("need cmd as list")
stderrval = subprocess.DEVNULL if swallow_stderr else None
rawdata = subprocess.check_output(cmd, stderr=stderrval)
return json.loads(rawdata.decode())
def pformatsize(size_bytes, commaplaces=1):
prefixes = ((1, 'K'), (2, 'M'), (3, 'G'), (4, 'T'), (5, 'P'), (6, 'E'), (7, 'Z'))
for exp, name in prefixes:
if abs(size_bytes) >= 1024 ** exp and abs(size_bytes) < 1024 ** (exp + 1):
new_size = size_bytes / 1024 ** exp
fstring = "%%.%df%%s" % commaplaces
return fstring % (new_size, name)
return "%.1fB" % size_bytes
# to detect if imported state files are outdated
STATE_VERSION = 1
# use cluster state from a file
if args.mode != "gather" and args.state:
logging.info(f"loading cluster state from file {args.state}...")
with lzma.open(args.state) as hdl:
CLUSTER_STATE = json.load(hdl)
import_version = CLUSTER_STATE['stateversion']
if import_version != STATE_VERSION:
raise Exception(f"imported file stores state in version {import_version}, but we need {STATE_VERSION}")
else:
logging.info(f"gathering cluster state via ceph api...")
# this is shitty: this whole script depends on these outputs,
# but they might be inconsistent, if the cluster had changes
# between calls....
# it would be really nice if we could "start a transaction"
# ceph pg dump always echoes "dumped all" on stderr, silence that.
CLUSTER_STATE = dict(
stateversion=STATE_VERSION,
timestamp=datetime.datetime.now().isoformat(),
versions=jsoncall("ceph versions --format=json".split()),
health_detail=jsoncall("ceph health detail --format=json".split()),
osd_dump=jsoncall("ceph osd dump --format json".split()),
pg_dump=jsoncall("ceph pg dump --format json".split(), swallow_stderr=True),
osd_df_dump=jsoncall("ceph osd df --format json".split()),
osd_df_tree_dump=jsoncall("ceph osd df tree --format json".split()),
df_dump=jsoncall("ceph df detail --format json".split()),
pool_dump=jsoncall("ceph osd pool ls detail --format json".split()),
crush_dump=jsoncall("ceph osd crush dump --format json".split()),
crush_class_osds=dict(),
)
crush_classes = jsoncall("ceph osd crush class ls --format json".split())
for crush_class in crush_classes:
class_osds = jsoncall(f"ceph osd crush class ls-osd {crush_class} --format json".split())
if not class_osds:
continue
CLUSTER_STATE["crush_class_osds"][crush_class] = class_osds
# check if the osdmap version changed meanwhile
# => we'd have inconsistent state
if CLUSTER_STATE['osd_dump']['epoch'] != jsoncall("ceph osd dump --format json".split())['epoch']:
raise Exception("Cluster topology changed during information gathering (e.g. a pg changed state). "
"Wait for things to calm down and try again")
# to dump the state
if args.mode == 'gather':
logging.info(f"cluster state dumped. now saving to {args.output_file}...")
with lzma.open(args.output_file, "wt") as hdl:
json.dump(CLUSTER_STATE, hdl, indent='\t')
logging.warn(f"cluster state saved to {args.output_file}")
exit(0)
pools = dict() # poolid => props
poolnames = dict() # poolname => poolid
crushrules = dict() # ruleid => props
crushclass_osds = defaultdict(set) # crushclass => osdidset
crushclasses_usage = dict() # crushclass => percent_used
osd_crushclass = dict() # osdid => crushclass
maxpoolnamelen = 0
maxcrushclasslen = 0
for crush_class, class_osds in CLUSTER_STATE["crush_class_osds"].items():
if not class_osds:
continue
crushclass_osds[crush_class].update(class_osds)
for osdid in class_osds:
osd_crushclass[osdid] = crush_class
if len(crush_class) > maxcrushclasslen:
maxcrushclasslen = len(crush_class)
# there's more stats, but raw is probably ok
class_df_stats = CLUSTER_STATE["df_dump"]["stats_by_class"][crush_class]
crushclasses_usage[crush_class] = class_df_stats["total_used_raw_ratio"] * 100
for pool in CLUSTER_STATE["osd_dump"]["pools"]:
id = pool["pool"]
name = pool["pool_name"]
pools[id] = {
'name': name,
'crush_rule': pool["crush_rule"],
'pg_num': pool["pg_num"], # current pgs before merge
'pgp_num': pool["pg_placement_num"], # actual placed pg count
'pg_num_target': pool["pg_num_target"], # target pg num
'size': pool["size"],
'min_size': pool["min_size"],
}
if len(name) > maxpoolnamelen:
maxpoolnamelen = len(name)
poolnames[name] = id
# current crush placement overrides
# map pgid -> [(from, to), ...]
upmap_items = dict()
for upmap_item in CLUSTER_STATE["osd_dump"]["pg_upmap_items"]:
remaps = list()
for remap in upmap_item["mappings"]:
remaps.append((remap["from"], remap["to"]))
upmap_items[upmap_item["pgid"]] = list(sorted(remaps))
ec_profiles = dict()
for ec_profile, ec_spec in CLUSTER_STATE["osd_dump"]["erasure_code_profiles"].items():
ec_profiles[ec_profile] = {
"data_chunks": int(ec_spec["k"]),
"coding_chunks": int(ec_spec["m"]),
}
for pool in CLUSTER_STATE["df_dump"]["pools"]:
id = pool["id"]
pools[id].update({
"stored": pool["stats"]["stored"], # actually stored data
"objects": pool["stats"]["objects"], # number of pool objects
"used": pool["stats"]["bytes_used"], # including redundant data
"store_avail": pool["stats"]["max_avail"], # available storage amount
"percent_used": pool["stats"]["percent_used"],
"quota_bytes": pool["stats"]["quota_bytes"],
"quota_objects": pool["stats"]["quota_objects"],
})
# definition from `struct pg_pool_t`:
# enum {
# TYPE_REPLICATED = 1, // replication
# //TYPE_RAID4 = 2, // raid4 (never implemented)
# TYPE_ERASURE = 3, // erasure-coded
# };
def pool_repl_type(typeid):
return {
1: "repl",
3: "ec",
}[typeid]
for pool in CLUSTER_STATE["pool_dump"]:
id = pool["pool_id"]
pool_type = pool_repl_type(pool["type"])
ec_profile = pool["erasure_code_profile"]
pg_shard_size_avg = pools[id]["stored"] / pools[id]["pg_num"]
if pool_type == "ec":
pg_shard_size_avg /= ec_profiles[ec_profile]["data_chunks"]
pools[id].update({
"erasure_code_profile": ec_profile if pool_type == "ec" else None,
"repl_type": pool_type,
"pg_shard_size_avg": pg_shard_size_avg,
})
for rule in CLUSTER_STATE["crush_dump"]["rules"]:
id = rule['rule_id']
name = rule['rule_name']
steps = rule['steps']
crushrules[id] = {
'name': name,
'steps': steps,
}
def list_replace(iterator, search, replace):
ret = list()
for elem in iterator:
if elem == search:
elem = replace
ret.append(elem)
return ret
def pool_from_pg(pg):
return int(pg.split(".")[0])
@lru_cache(maxsize=2**17)
def pg_ec_profile(pg):
pool_id = pool_from_pg(pg)
pool = pools[pool_id]
return pool["erasure_code_profile"]
@lru_cache(maxsize=2**17)
def pg_is_ec(pg):
pool_id = pool_from_pg(pg)
pool = pools[pool_id]
return pool["repl_type"] == "ec"
def get_remaps(pginfo):
"""
given the pginfo structure, compare up and acting sets
return which osds are source and target for pg movements.
return [((osd_from, ...), (osd_to, ..)), ...]
"""
up_osds = list_replace(pginfo["up"], 0x7fffffff, -1)
acting_osds = list_replace(pginfo["acting"], 0x7fffffff, -1)
is_ec = pg_is_ec(pginfo["pgid"])
moves = list()
if is_ec:
for up_osd, acting_osd in zip(up_osds, acting_osds):
if up_osd != acting_osd:
moves.append(((acting_osd,), (up_osd,)))
else:
ups = set(up_osds)
actings = set(acting_osds)
from_osds = actings - ups
to_osds = ups - actings
moves.append(
(
tuple(sorted(from_osds)),
tuple(sorted(to_osds)),
)
)
return moves
# map osd -> pgs on it
osd_mappings = defaultdict(
lambda: {'up': set(), 'primary': set(), 'acting': set()}
)
# map pg -> osds involved
pg_osds_up = defaultdict(set)
pg_osds_acting = defaultdict(set)
# osdid => {to: {pgid -> osdid}, from: {pgid -> osdid}}
osd_actions = defaultdict(lambda: defaultdict(dict))
# pg metadata
# pgid -> pg dump pgstats entry
pgs = dict()
for pginfo in CLUSTER_STATE["pg_dump"]["pg_map"]["pg_stats"]:
if pginfo["state"] in ("unknown",):
# skip pgs with no active osds
continue
pgid = pginfo["pgid"]
up = pginfo["up"]
acting = pginfo["acting"]
primary = acting[0]
pg_osds_up[pgid] = up
pg_osds_acting[pgid] = acting
osd_mappings[primary]['primary'].add(pgid)
for osd in up:
osd_mappings[osd]['up'].add(pgid)
for osd in acting:
osd_mappings[osd]['acting'].add(pgid)
# track all remapped pgs
pgstate = pginfo["state"].split("+")
if "remapped" in pgstate:
for osds_from, osds_to in get_remaps(pginfo):
for osd_from, osd_to in zip(osds_from, osds_to):
osd_actions[osd_from]["to"][pgid] = osd_to
osd_actions[osd_to]["from"][pgid] = osd_from
pgs[pgid] = pginfo
osds = dict()
for osd in CLUSTER_STATE["osd_df_dump"]["nodes"]:
id = osd["id"]
osds[id] = {
"device_size": osd["kb"] * 1024,
"device_used": osd["kb_used"] * 1024,
"device_used_data": osd["kb_used_data"] * 1024,
"device_used_meta": osd["kb_used_meta"] * 1024,
"device_available": osd["kb_avail"] * 1024,
"utilization": osd["utilization"],
"crush_weight": osd["crush_weight"],
"status": osd["status"],
}
# osds used by a pool:
# pool_id -> {osdid}
pool_osds_up = defaultdict(set)
pool_osds_acting = defaultdict(set)
# gather which pgs are on what osd
# and which pools have which osds
for osdid, osd in osd_mappings.items():
osd_pools_up = set()
osd_pools_acting = set()
pgs_up = set()
pgs_acting = set()
pg_count_up = defaultdict(int)
pg_count_acting = defaultdict(int)
for pg in osd['up']:
poolid = int(pg.split('.', maxsplit=1)[0])
osd_pools_up.add(poolid)
pgs_up.add(pg)
pg_count_up[poolid] += 1
pool_osds_up[poolid].add(osdid)
for pg in osd['acting']:
poolid = int(pg.split('.', maxsplit=1)[0])
osd_pools_acting.add(poolid)
pgs_acting.add(pg)
pg_count_acting[poolid] += 1
pool_osds_acting[poolid].add(osdid)
if osdid == 0x7fffffff:
# the "missing" osds
continue
osds[osdid].update({
'pools_up': list(sorted(osd_pools_up)),
'pools_acting': list(sorted(osd_pools_acting)),
'pg_count_up': pg_count_up,
'pg_count_acting': pg_count_acting,
'pg_num_up': len(pgs_up),
'pgs_up': pgs_up,
'pg_num_acting': len(pgs_acting),
'pgs_acting': pgs_acting,
})
for osd in CLUSTER_STATE["osd_dump"]["osds"]:
osdid = osd["osd"]
crushclass = osd_crushclass.get(osdid)
osds[osdid].update({
"weight": osd["weight"],
"cluster_addr": osd["cluster_addr"],
"public_addr": osd["public_addr"],
"state": tuple(osd["state"]),
'crush_class': crushclass,
})
for osd_info in CLUSTER_STATE["pg_dump"]["pg_map"]["osd_stats"]:
osds[osd_info['osd']]['stats'] = osd_info
osd_stats_sum = CLUSTER_STATE["pg_dump"]["pg_map"]["osd_stats_sum"]
# create the crush trees
buckets = CLUSTER_STATE["crush_dump"]["buckets"]
# bucketid -> bucket dict
bucket_ids_tmp = dict()
# all bucket ids of roots
bucket_root_ids = list()
for device in CLUSTER_STATE["crush_dump"]["devices"]:
id = device["id"]
assert id >= 0
bucket_ids_tmp[id] = device
for bucket in buckets:
id = bucket["id"]
assert id < 0
bucket_ids_tmp[id] = bucket
# collect all root buckets
if bucket["type_name"] == "root":
bucket_root_ids.append(id)
# get osd crush weights
for item in bucket["items"]:
item_id = item["id"]
# it's an osd
if item_id >= 0:
# json-crushweight is in 64-gbyte blocks apparently
size = (item["weight"] / 64) * 1024 ** 3
osds[item_id].update({
"crush_weight": size,
})
# find osd host name
for node in CLUSTER_STATE["osd_df_tree_dump"]["nodes"]:
if node['type'] == "host":
for osdid in node['children']:
osds[osdid]["host_name"] = node['name']
def bucket_fill(id, parent_id=None):
"""
returns the list of all child buckets for a given id
plus for each of those, their children.
"""
bucket = bucket_ids_tmp[id]
children = list()
ids = dict()
this_bucket = {
"id": id,
"name": bucket["name"],
"type_name": bucket["type_name"],
"weight": bucket["weight"],
"parent": parent_id,
"children": children,
}
ids[id] = this_bucket
for child_item in bucket["items"]:
child = bucket_ids_tmp[child_item["id"]]
cid = child["id"]
if cid < 0:
new_nodes, new_ids = bucket_fill(cid, id)
ids.update(new_ids)
children.extend(new_nodes)
else:
# it's a device
new_node = {
"id": cid,
"name": child["name"],
"type_name": "osd",
"class": child["class"],
"parent": id,
}
ids[cid] = new_node
children.append(new_node)
return this_bucket, ids
# populare all roots
bucket_roots = list()
for root_bucket_id in bucket_root_ids:
bucket_tree, bucket_ids = bucket_fill(root_bucket_id)
bucket_roots.append((bucket_tree, bucket_ids))
del bucket_ids_tmp
@lru_cache(maxsize=2 ** 14)
def trace_crush_root(osd, root_name):
"""
in the given root, trace back all items from the osd up to the root
"""
found = False
for root_bucket, try_root_ids in bucket_roots:
if root_bucket["name"] == root_name:
root_ids = try_root_ids
break
if not root_ids:
raise Exception(f"crush root {root_name} not known?")
try_node_in_root = root_ids.get(osd)
if try_node_in_root is None:
# osd is not part of this root, i.e. wrong device class
return None
node_id = try_node_in_root["id"]
assert node_id == osd
# walk from leaf (osd) to the tree root
bottomup = list()
while True:
if node_id is None:
# we reached the root
break
bottomup.append({
"id": node_id,
"type_name": root_ids[node_id]["type_name"],
})
if root_ids[node_id]["name"] == root_name:
found = True
break
node_id = root_ids[node_id]["parent"]
if not found:
raise Exception(f"could not find a crush-path from osd={osd} to {root_name!r}")
topdown = list(reversed(bottomup))
return topdown
@lru_cache(maxsize=2**20)
def get_pg_shardsize(pgid):
pg_stats = pgs[pgid]['stat_sum']
shard_size = pg_stats['num_bytes']
shard_size += pg_stats['num_omap_bytes']
ec_profile = pg_ec_profile(pgid)
if ec_profile:
shard_size /= ec_profiles[ec_profile]["data_chunks"]
# omap is not supported on EC pools (yet)
# when it is, check how the omap data is spread (replica or also ec?)
return shard_size
def rule_for_pg(pg):
"""
get the crush rule for a pg.
"""
pool = pools[pool_from_pg(move_pg)]
crushruleid = pool['crush_rule']
return crushrules[crushruleid]
def root_uses_from_rule(rule, pool_size):
"""
rule: crush rule id
pool_size: number of osds in one pg
return {root_name: choice_count} for the given crush rule.
the choose-step nums are processed in order:
val ==0: remaining_pool_size
val < 0: remaining_pool_size - val
val > 0: val
"""
chosen = 0
# rootname -> number of chooses for this root
root_usages = defaultdict(int)
root_candidate = None
root_chosen = None
root_use_num = None
for step in rule["steps"]:
if step["op"] == "take":
root_candidate = step["item_name"]
elif step["op"].startswith("choose"):
# TODO: maybe "osd" type can be renamed, fetch it dynamically
if root_candidate and (step["op"].startswith("chooseleaf")
or step["type"] == "osd"):
root_chosen = root_candidate
root_use_num = step["num"]
elif step["op"] == "emit":
if root_chosen:
if root_use_num == 0:
root_use_num = pool_size
elif root_use_num < 0:
root_use_num = pool_size - root_use_num
elif root_use_num > 0:
pass # = root_use_num
# limit to pool size
if root_use_num > pool_size - chosen:
root_use_num = pool_size - chosen
root_usages[root_chosen] += root_use_num
chosen += root_use_num
root_candidate = None
root_chosen = None
root_use_num = None
if chosen == pool_size:
break
if not root_usages:
raise Exception(f"rule chooses no roots")
return root_usages
def rootweights_from_rule(rule, pool_size):
"""
given a crush rule and a pool size (involved osds in a pg),
calculate the weights crush-roots are chosen for each pg.
"""
root_usages = root_uses_from_rule(rule, pool_size)
# normalize the weights:
weight_sum = sum(root_usages.values())
# TODO: handle `default` root
# -> distribute it to the other involved roots
root_weights = dict()
for root_name, root_usage in root_usages.items():
root_weights[root_name] = root_usage / weight_sum
return root_weights
def candidates_for_root(root_name):
"""
get the set of all osds where a crush rule could place shards.
"""
for root_bucket, try_root_ids in bucket_roots:
if root_bucket["name"] == root_name:
root_ids = try_root_ids
break
if not root_ids:
raise Exception(f"crush root {root} not known?")
ret = set()
for nodeid in root_ids.keys():
if (nodeid >= 0 and
osds[nodeid]['weight'] != 0 and
osds[nodeid]['crush_weight'] != 0):
ret.add(nodeid)
return ret
class PGMoveChecker:
"""
for the given rule and utilized pg_osds,
create a checker that can verify osd replacements are valid.
"""
def __init__(self, pg_mappings, move_pg):
# which pg to relocate
self.pg = move_pg
self.pool = pools[pool_from_pg(move_pg)]
self.pool_size = self.pool["size"]
self.rule = crushrules[self.pool['crush_rule']]
# crush root name for the pg
self.root_names = root_uses_from_rule(self.rule, self.pool_size).keys()
# all available placement osds for this crush root
self.osd_candidates = set()
for root_name in self.root_names:
for osdid in candidates_for_root(root_name):
self.osd_candidates.add(osdid)
self.pg_mappings = pg_mappings # current pg->[osd] mapping state
self.pg_osds = pg_mappings.get_mapping(move_pg) # acting osds managing this pg
def get_osd_candidates(self):
"""
return all possible candidate OSDs for the PG to relocate.
"""
return self.osd_candidates
@staticmethod
def use_item_type(trace, item_type, rule_depth, item_uses):
"""
given a trace (part), walk forward, until a given item type is found.
increase its use.
"""
for idx, item in enumerate(trace):
if item["type_name"] == item_type:
item_id = item["id"]
cur_item_uses = item_uses[rule_depth].get(item_id, 0)
cur_item_uses += 1
item_uses[rule_depth][item_id] = cur_item_uses
return idx
return None
def prepare_crush_check(self):
"""
perform precalculations for moving this pg
"""
logging.debug(strlazy(lambda: f"prepare crush check for pg {self.pg} currently up={self.pg_osds}"))
logging.debug(strlazy(lambda: f"rule:\n{pformat(self.rule)}"))
# ruledepth -> allowed number of bucket reuse
reuses_per_step = []
fanout_cum = 1
# calculate how often one bucket layer can be reused
# this is the crush-constraint, set up by the rule
for step in reversed(self.rule["steps"]):
if step["op"] == "take":
num = 1
elif step["op"].startswith("choose"):
num = step["num"]
elif step["op"] == "emit":
num = 1
else:
continue
reuses_per_step.append(fanout_cum)
if num <= 0:
num += self.pool_size
fanout_cum *= num
reuses_per_step.reverse()
logging.debug(strlazy(lambda: f"allowed reuses per rule step, starting at root: {pformat(reuses_per_step)}"))
# for each depth, count how often items were used
# rule_depth -> {itemid -> use count}
item_uses = defaultdict(dict)
# example: 2+2 ec -> size=4
#
# root __________-9______________________________
# rack: _____-7_______ _________-8_____ ___-10____
# host: -1 -2 -3 -4 -5 -6 -11 -12
# osd: 1 2 | 3 4 | 5 6 | 7 8 | 9 10 | 11 12 | 13 14 | 15 16
# _ _ _ _
#
# take root
# choose 2 racks
# chooseleaf 2 hosts
#
# fanout: rule step's num = selections below bucket
# [1, 2, 2]
#
# inverse aggregation, starting with 1
# reuses_per_step = [4, 2, 1]
#
# current pg=[2, 4, 7, 9]
#
# Now: replace_osd 2
#
# traces from root down to osd:
# 2: [-9, -7, -1, 2]
# 4: [-9, -7, -2, 4]
# 7: [-9, -8, -4, 7]
# 9: [-9, -8, -5, 9]
#
# use counts - per rule depth.
# {0: {-9: 4}, 1: {-7: 2, -8: 2}, 2: {-1: 1, -2: 1, -4: 1, -5: 1}}
#
# from this use count, subtract the trace of the replaced osd
#
# now eliminate candidates:
# * GET TRACE FROM THEM
# * check use counts against reuses_per_step
#
# 1 -> -9 used 3<4, -7 used 1<2, -1 used 0<1 -> ok
# 2 -> replaced..
# 3 -> -9 used 3<4, -7 used 1<2, -2 used 1<1 -> fail
# 4 -> keep, not replaced
# 5 -> -9 used 3<4, -7 used 1<2, -3 used 0<1 -> ok
# 6 -> -9 used 3<4, -7 used 1<2, -3 used 0<1 -> ok
# 7 -> keep, not replaced
# 8 -> -9 used 3<4, -8 used 2<2, -4 used 1<1 -> fail
# ...
#
# replacement candidates for 2: 1, 5, 6, 13 14 15 16
#
# did we encounter an emit?
emit = False
# collect trace for each osd.
# osd -> crush-root-trace
constraining_traces = dict()
# how far down the crush hierarchy have we stepped
# 1 = root depth
tree_depth = 0
# at what rule position is our processing
# since we skip steps like set_chooseleaf_tries
rule_depth = 0
# rule_depth -> tree_depth to next rule (what tree layer is this rule step)
# because "choose" steps may skip layers in the crush hierarchy
rule_tree_depth = dict()
current_item_type = None
# gather item usages by evaluating the crush rules
for step in self.rule["steps"]:
if step["op"].startswith("set_"):
continue
logging.debug(strlazy(lambda: f"processing crush step {step} with tree_depth={tree_depth}, "
f"rule_depth={rule_depth}, item_uses={item_uses}"))
if step["op"] == "take":
rule_root_name = step["item_name"]
# should be known already since we fetch it the exact same way
assert rule_root_name in self.root_names
# first step: try to find tracebacks for all osds that ends up in this root.
# we collect root-traces of all acting osds of the pg we wanna check for.
constraining_traces = dict()