forked from TheJJ/ceph-balancer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
placementoptimizer.py
executable file
·1603 lines (1239 loc) · 55.4 KB
/
placementoptimizer.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
"""
Ceph balancer.
(c) 2020 Jonas Jelten <[email protected]>
GPLv3 or later
"""
# some future TODOs:
# also consider the device's relative PG count
# 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
# 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 json
import logging
import shlex
import statistics
import subprocess
from collections import defaultdict
from functools import lru_cache
from pprint import pformat
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
showsp = sp.add_parser('show')
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%%')
sp.add_parser('showremapped')
balancep = sp.add_parser('balance')
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('--use-shardsize-sum', action='store_true',
help=('calculate the osd usage by summing up the pg shardsizes. '
'if not set, use the osd-fs stats, and pg shardsize deltas'))
balancep.add_argument('--largest-shard-first', action='store_true',
help='start with the largest shard on a OSD and try to move it')
balancep.add_argument('--ensure-optimal-moves', action='store_true',
help='make sure that only movements which win full shardsizes are done')
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)
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 pprintsize(size_bytes, commaplaces=1):
prefixes = ((1, 'K'), (2, 'M'), (3, 'G'), (4, 'T'), (5, 'E'), (6, '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
# this is shitty: this whole script depends on these outputs,
# but they might be inconsistent, if the cluster had changes
# between calls....
# ceph pg dump always echoes "dumped all" on stderr, silence that.
pg_dump = jsoncall("ceph pg dump --format json".split(), swallow_stderr=True)
osd_dump = jsoncall("ceph osd dump --format json".split())
osd_df_dump = jsoncall("ceph osd df --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_classes = jsoncall("ceph osd crush class ls --format json".split())
pools = dict() # poolid => props
poolnames = dict() # poolname => poolid
crushrules = dict() # ruleid => props
crushclass_osds = defaultdict(set) # crushclass => osdidset
osd_crushclass = dict() # osdid => crushclass
maxpoolnamelen = 0
maxcrushclasslen = 0
for crush_class in crush_classes:
class_osds = jsoncall(f"ceph osd crush class ls-osd {crush_class} --format json".split())
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)
for pool in 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
upmap_items = dict()
for upmap_item in 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 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 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"],
})
for pool in pool_dump:
id = pool["pool_id"]
ec_profile = pool["erasure_code_profile"]
pg_shard_size_avg = pools[id]["stored"] / pools[id]["pg_num"]
if ec_profile:
pg_shard_size_avg /= ec_profiles[ec_profile]["data_chunks"]
pools[id].update({
"erasure_code_profile": ec_profile,
"repl_type": "ec" if ec_profile else "repl",
"pg_shard_size_avg": pg_shard_size_avg
})
for rule in crush_dump["rules"]:
id = rule['rule_id']
name = rule['rule_name']
steps = rule['steps']
crushrules[id] = {
'name': name,
'steps': steps,
}
# 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)
# pg metadata
# pgid -> pg dump pgstats entry
pgs = dict()
for pg in pg_dump["pg_map"]["pg_stats"]:
pgid = pg["pgid"]
up = pg["up"]
acting = pg["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)
pgs[pgid] = pg
osds = dict()
for osd in 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"],
"pg_count_active": osd["pgs"], # pgs in the osd df view
"status": osd["status"],
}
# gather which pgs are on what osd
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
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
if osdid == 0x7fffffff:
# the "missing" osds
osdid = -1
crushclass = "-"
continue
else:
crushclass = osd_crushclass[osdid]
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,
'crush_class': crushclass,
})
if osds[osdid]['pg_count_active'] != osds[osdid]['pg_num_acting']:
raise Exception(f"on osd.{id} calculated pg num acting: "
f"{osds[id]['pg_count_active']} != {osds[id]['pg_num_acting']}")
for osd in osd_dump["osds"]:
id = osd["osd"]
osds[id].update({
"weight": osd["weight"],
"cluster_addr": osd["cluster_addr"],
"public_addr": osd["public_addr"],
"state": tuple(osd["state"]),
})
# create the crush trees
buckets = crush_dump["buckets"]
# bucketid -> bucket dict
bucket_ids_tmp = dict()
# all bucket ids of roots
bucket_root_ids = list()
for device in 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
if bucket["type_name"] == "root":
bucket_root_ids.append(id)
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=2048)
def trace_crush_root(osd, root):
"""
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:
root_ids = try_root_ids
break
if not root_ids:
raise Exception(f"crush root {root} 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:
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!r}")
topdown = list(reversed(bottomup))
return topdown
def pool_from_pg(pg):
return int(pg.split(".")[0])
@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']
pool_id = pool_from_pg(pgid)
pool = pools[pool_id]
ec_profile = pool["erasure_code_profile"]
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 find_item_type(trace, item_type, rule_depth, item_uses):
for idx, item in enumerate(trace, start=1):
if item["type_name"] == item_type:
item_uses[rule_depth][item["id"]] += 1
return idx
return None
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 rootname_from_rule(rule):
"""
return the crush root name for the given rule
"""
root_name = None
for step in rule["steps"]:
if step["op"] == "take":
root_name = step["item_name"]
break
if not root_name:
raise Exception(f"rule has no take step")
return root_name
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?")
return {nodeid for nodeid in root_ids.keys() if nodeid >= 0}
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_name = rootname_from_rule(self.rule)
# all available placement osds for this crush root
self.osd_candidates = candidates_for_root(self.root_name)
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
def prepare_crush_check(self):
"""
perform precalculations for moving this pg
"""
# 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()
# for each depth, count how often items were used
# rule_depth -> {itemid -> use count}
item_uses = defaultdict(lambda: defaultdict(lambda: 0))
# 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: x 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
#
# collect trace for each osd
tree_depth = 0
rule_depth = 0 # because we skip steps like chooseleaf_tries
rule_root_name = None
# osd -> crush-root-trace
constraining_traces = dict()
emit = False
# 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()
# gather item usages by evaluating the crush rules
for step in self.rule["steps"]:
if step["op"] == "take":
rule_root_name = step["item_name"]
# should be the same since we fetch it the exact same way
assert rule_root_name == self.root_name
# first step: try to find tracebacks for all osds that ends up in this root.
constraining_traces = dict()
for pg_osd in self.pg_osds:
trace = trace_crush_root(pg_osd, rule_root_name)
if trace is None:
raise Exception(f"no trace found for {pg_osd} in {rule_root_name}")
constraining_traces[pg_osd] = trace
# the root was "used"
item_uses[rule_depth][trace[0]["id"]] += 1
rule_tree_depth[rule_depth] = 0
tree_depth = 1
rule_depth += 1
elif step["op"].startswith("choose"):
if not constraining_traces:
raise Exception('no backtraces captured from rule (missing "take"?)')
choose_type = step["type"]
# find the new tree_depth by looking for the choosen next bucket
# increase item counter for current osd't trace
for constraining_trace in constraining_traces.values():
steps_taken = find_item_type(constraining_trace[tree_depth:], choose_type, rule_depth, item_uses)
if steps_taken is None:
raise Exception(f"could not find item type {step['type']} "
f"requested by rule step {step}")
# how many layers we went down the tree
rule_tree_depth[rule_depth] = tree_depth + steps_taken
tree_depth += steps_taken
rule_depth += 1
elif step["op"] == "emit":
emit = True
type_found = False
for constraining_trace in constraining_traces.values():
steps_taken = find_item_type(constraining_trace[tree_depth:], "osd", rule_depth, item_uses)
if steps_taken is None:
raise Exception(f"could not find item type {step['type']} "
f"requested by rule step {step}")
rule_tree_depth[rule_depth] = tree_depth + steps_taken
tree_depth += steps_taken
rule_depth += 1
# sanity checks lol
assert len(rule_tree_depth) == rule_depth
assert len(item_uses) == rule_depth
for idx, reuses in enumerate(reuses_per_step):
for item, uses in item_uses[idx].items():
assert reuses == uses
# only one emit supported so far
break
else:
pass
if not emit:
raise Exception("uuh no emit seen?")
if not constraining_traces:
raise Exception("no tree traces gathered?")
# validate item uses:
for i in range(rule_depth):
for item, uses in item_uses[i].items():
if uses != reuses_per_step[i]:
print(f"reuses: {reuses_per_step}")
print(f"item_uses: {pformat(item_uses)}")
raise Exception("counted item uses != crush item, in step {i}: "
f"{item}={uses} != {reuses_per_step[i]}")
# should still be the same, it could have changed if there were
# multiple takes
assert rule_root_name == self.root_name
self.constraining_traces = constraining_traces # osdid->crush-root-trace
self.rule_tree_depth = rule_tree_depth # rulestepid->tree_depth
self.reuses_per_step = reuses_per_step # rulestepid->allowed_item_reuses
self.item_uses = item_uses # rulestepid->{item->use_count}
def is_move_valid(self, old_osd, new_osd):
"""
verify that the given new osd does not violate the
crush rules' constraints of placement.
"""
if new_osd in self.pg_osds:
logging.debug(f" invalid: osd.{new_osd} in {self.pg_osds}")
return False
if new_osd not in self.osd_candidates:
logging.debug(f" invalid: osd.{new_osd} not in same crush root")
return False
# create trace for the replacement candidate
new_trace = trace_crush_root(new_osd, self.root_name)
if new_trace is None:
# probably not a compatible device class
logging.debug(f" no trace found for {new_osd}")
return False
# the trace we no longer consider (since we replace the osd)
old_trace = self.constraining_traces[old_osd]
overuse = False
for idx, tree_stepwidth in enumerate(self.rule_tree_depth):
use_max_allowed = self.reuses_per_step[idx]
# as we would remove the old osd trace,
# the item would no longer be occupied in the new trace
old_item = old_trace[tree_stepwidth]["id"]
# this trace now adds to the item uses:
new_item = new_trace[tree_stepwidth]["id"]
# how often is new_item used now?
# if not used at all, it's not in the dict.
uses = self.item_uses[idx].get(new_item, 0)
if old_item == new_item:
uses -= 1
# if we used it, it'd be violating crush
# (the +1 was 'optimized' by >= instead of >)
if uses >= use_max_allowed:
logging.debug(f" invalid: osd.{new_osd} violates crush: using {new_item} x {uses+1} > {use_max_allowed}")
overuse = True
break
return not overuse
def get_placement_variance(self, osd_from=None, osd_to=None):
"""
calculate the variance of weighted OSD usage
for all OSDs that are candidates for this PG
osd_from -> osd_to: how would the variance look, if
we had moved data.
"""
if osd_from or osd_to:
pg_shardsize = get_pg_shardsize(self.pg)
osds_used = list()
for osd in self.osd_candidates:
delta = 0
if osd == osd_from:
delta = -pg_shardsize
elif osd == osd_to:
delta = pg_shardsize
if osds[osd]['weight'] == 0:
# relative usage of weight 0 is impossible
continue
osd_used = self.pg_mappings.get_osd_usage(osd, add_size=delta)
osds_used.append(osd_used)
var = statistics.variance(osds_used)
return var
def filter_candidates(self, osdids):
"""
given an iterator of osd ids, return only those
entries that are in the same crush root
"""
for osdid in osdids:
if osdid not in self.osd_candidates:
continue
yield osdid
class PGMappings:
"""
PG mapping simulator
used to calculate device usage when moving around pgs.
"""
def __init__(self, pgs, osds):
# the "real" devices, just used for their "fixed" properties like
# device size
self.osds = osds
# up state: osdid -> {pg, ...}
self.osd_pgs = defaultdict(set)
# acting state: osdid -> {pg, ...}
osd_pgs_acting = defaultdict(set)
# choose the up mapping, since we wanna optimize the "future" cluster
# up pg mapping: pgid -> [up_osd, ...]
self.pg_mappings = dict()
for pg, pginfo in pgs.items():
up_osds = pginfo["up"]
self.pg_mappings[pg] = list(up_osds)
for osd in up_osds:
self.osd_pgs[osd].add(pg)
acting_osds = pginfo["acting"]
for osd in acting_osds:
osd_pgs_acting[osd].add(pg)
# pg->[(osd_from, osd_to), ...]
self.remaps = defaultdict(list)
# osdid -> used kb, based on the osd-level utilization report
self.osd_utilizations = dict()
for osdid, osd in osds.items():
# this is the current "acting" size.
# and the parts of not-yet-fully-transferred up pgs
osd_fs_used = osd['device_used']
# we want the up-size, i.e. the osd utilization when all moves
# would be finished.
# to estimate it, we need to add the shards of (up - acting)
# and remove the shards of (acting - up)
for pg in (self.osd_pgs[osdid] - osd_pgs_acting[osdid]):
shardsize = get_pg_shardsize(pg)
osd_fs_used += shardsize
# try to estimate the partially transferred size by
# the number of objects
# if you know a better way to estimate it, please fix.
pginfo = pgs[pg]
pg_objs = pginfo["stat_sum"]["num_objects"]
# estimated...
pg_obj_size = shardsize / pg_objs
moves = get_remaps(pginfo)
pg_remap_count = len(moves)
# again estimated, since we only know the total number of misplaced
# and not the per-osd count...
pg_objs_misplaced = pginfo["stat_sum"]["num_objects_misplaced"]
osd_pg_objs_misplaced = pg_objs_misplaced / pg_remap_count
# adjust fs size by average object size times estimated misplaced count.
# because this is kinda lame but it seems one can't get more info
# the balancer will work best if there are no more remapped PGs!
osd_fs_used -= int(pg_obj_size * osd_pg_objs_misplaced)
for pg in (osd_pgs_acting[osdid] - self.osd_pgs[osdid]):
osd_fs_used -= get_pg_shardsize(pg)
self.osd_utilizations[osdid] = osd_fs_used
def apply_remap(self, pg, osd_from, osd_to):
"""
simulate a remap pg from one osd to another.
this updates the mappings stored in this object.
"""
self.osd_pgs[osd_from].remove(pg)
self.osd_pgs[osd_to].add(pg)
pg_mapping = self.pg_mappings[pg]
did_remap = False
for i in range(len(pg_mapping)):
if pg_mapping[i] == osd_from:
logging.debug(f"recording move of pg={pg} from {osd_from}->{osd_to}")
pg_mapping[i] = osd_to
did_remap = True
break
if not did_remap:
raise Exception(f"did not find osd {osd_from} in pg {pg} mapping")
# adjust the tracked sizes
shard_size = get_pg_shardsize(pg)
self.osd_utilizations[osd_from] -= shard_size
self.osd_utilizations[osd_to] += shard_size
self.get_osd_shardsize_sum.cache_clear()
self.remaps[pg].append((osd_from, osd_to))
def get_mapping(self, pg):
return self.pg_mappings[pg]
def get_osd_pgs(self, osd):
return self.osd_pgs[osd]
@lru_cache(maxsize=2**18)
def get_osd_shardsize_sum(self, osd):
"""
calculate the osd usage by summing all the mapped (up) PGs shardsizes
-> we can calculate a future size
remember to clear the cache with cache_clear() when self.osd_pgs changes!
"""
used = 0
for pg in self.get_osd_pgs(osd):
used += get_pg_shardsize(pg)
return used
def get_osd_used(self, osdid):
"""
return the osd usage reported by the osd, but with added shardsizes
when pg movements were applied.
"""
return self.osd_utilizations[osdid]
def get_osd_weighted_size(self, osdid):
"""
return the weighted OSD device size
"""
osd = self.osds[osdid]
size = osd['device_size']
weight = osd['weight']