-
Notifications
You must be signed in to change notification settings - Fork 29
/
placementoptimizer.py
executable file
·5497 lines (4442 loc) · 227 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-2024 Jonas Jelten <[email protected]>
GPLv3 or later
"""
import argparse
import binascii
import datetime
import itertools
import io
import json
import logging
import lzma
import math
import re
import shlex
import socket
import statistics
import struct
import subprocess
import sys
import time
import uuid
from enum import Enum
from collections import defaultdict
from functools import lru_cache
from itertools import chain, zip_longest
from pprint import pformat, pprint
from typing import Optional, Callable, Dict, List, Tuple
def parse_args():
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")
cli.add_argument("--profile", action="store_true",
help=("activate the performance profiler for the balancer itself"))
sp = cli.add_subparsers(dest='mode')
sp.required = True
### parsers used in subcommands
statep = argparse.ArgumentParser(add_help=False)
statep.add_argument("--state", "-s", help="load cluster state from this jsonfile")
osdsizep = argparse.ArgumentParser(add_help=False)
osdsizep.add_argument('--osdsize', choices=['device', 'weighted', 'crush'], default="crush",
help=("what parameter to take for determining the osd size. default: %(default)s. "
"device=device_size, weighted=devsize*weight, crush=crushweight*weight"))
# upmap item filtering
upmapignorep = argparse.ArgumentParser(add_help=False)
upmapignorep.add_argument('--ignore-state-upmaps', action='store_true',
help='pretend the cluster had no upmap items at all')
# for experiments with generated movements
upmapp = argparse.ArgumentParser(add_help=False, parents=[upmapignorep])
upmapp.add_argument('--add-upmaps',
help=('after loading cluster state, simulate application of pg movements'
'from an output generated by "balance"'))
upmapp.add_argument('--emit-ignored-upmaps', action='store_true',
help='return the ignored statemaps as "reverted" when generating new upmaps (e.g. in balancing)')
predictionp = argparse.ArgumentParser(add_help=False)
predictionp.add_argument('--avail-prediction', choices=['weight', 'limiting'], default='limiting',
help=("algorithm to use for available pool size prediction. default: %(default)s\n"
"weight: use ceph's original prediction based on crush weights. "
"it's unfortunately wrong for multi-take crush rules, "
"and it doesn't respect the current pg placements at all.\n"
"limiting: determine space by finding the pool's limiting osd and extrapolate possible usage."))
usedestimatep = argparse.ArgumentParser(add_help=False)
usedestimatep.add_argument('--osdused', choices=["delta", "shardsum"], default="shardsum",
help=('how is the osd usage predicted during simulation? default: %(default)s. '
"delta: adjust the builtin osd usage report by in-move pg deltas - more accurate but doesn't account pending data deletion.\n"
"shardsum: estimate the usage by summing up all pg shardsizes - doesn't account PG metadata overhead."))
savemappingp = argparse.ArgumentParser(add_help=False)
savemappingp.add_argument("--save-mappings", help="filename to store the resulting up osdid set for all pgs (to see where things are placed)")
### subcommands
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, upmapp, predictionp, osdsizep, usedestimatep, savemappingp],
help=("show cluster properties like free pool space or OSD utilizations. "
"it shows all info for the 'acting' state by default. "
"use '--pgstate up' to look into the future and print how it will look after all movements are done."))
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('--show-max-avail', action='store_true',
help="show how much space would be available if the pool had infinity many pgs")
showsp.add_argument('--osd-fill-min', type=int, default=0,
help='minimum fill %% to show an osd, default: %(default)s%%')
showsp.add_argument('--save-upmap-progress',
help="filename to store cluster stats after each after each upmap change")
remappsp = sp.add_parser('showremapped', parents=[statep, osdsizep],
help="show current PG remaps and their progress")
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, upmapp, osdsizep, usedestimatep, savemappingp],
help="distribute PGs for better capacity and performance in your cluster")
balancep.add_argument('--output', '-o', default="-",
help="output filename for resulting movement instructions. default stdout.")
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('--source-osds',
help=("only consider these osds as movement source, separated by ',' or ' '. "
'to balance just one bucket, use "$(ceph osd ls-tree bucketname)"'))
balancep.add_argument('--pg-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('--osdfrom', choices=["fullest", "limiting", "alternate"], default="alternate",
help=('how to determine the source osd for a movement? default: %(default)s. '
"fullest=start with the fullest osd (by percent of device size). "
"limiting=start with the fullest osd that actually limits the usable pool space. "
"alternate=alternate between limiting and fullest devices"))
balancep.add_argument('--ignore-ideal-pgcounts', choices=['all', 'source', 'destination', 'none'],
default='none',
help=("don't consider balancing by placement group count on an source/destination/both OSD. "
"if you set this, the ceph's built-in balancer and this one will have a fight."))
balancep.add_argument('--ignore-pgsize-toolarge', action="store_true",
help=("don't pre-filter PGs to rule out those that will for sure not gain any space "
"- the target OSD would become fuller than the source OSD of a movement is."))
balancep.add_argument('--ignore-target-usage', action="store_true",
help=("don't ensure the target device is less used than the source after a move. "))
balancep.add_argument('--ensure-target-limits', action="store_true",
help=("make sure the target device does not become the pool's size limit after a move"))
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('--max-move-attempts', type=int, default=2,
help=("current source osd can't be emptied more, "
"try this many more other osds candidates to empty. default: %(default)s"))
balancep.add_argument('--save-timings',
help="filename to save timing information for each generated move")
pooldiffp = sp.add_parser('poolosddiff', parents=[statep, osdsizep])
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, osdsizep],
help="which OSDs repaired their stored data?")
testp = sp.add_parser('test', help="test internal stuff")
testp.add_argument('--name', '-n', help='doctest name to run')
osdmapp = sp.add_parser('osdmap', parents=[],
help="compatibility with ceph osd maps")
osdmapsp = osdmapp.add_subparsers(dest='osdmapmode')
osdmapsp.required = True
osdmapexportsp = osdmapsp.add_parser('export', parents=[statep, upmapignorep], help="create osdmap files")
osdmapexportsp.add_argument("output_file", help="osdmap filename to save to")
args = cli.parse_args()
return 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))
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()
class PGState(Enum):
"""
what pg state set to use
"""
UP = 1 # use the future planned pg assignments
ACTING = 2 # use the current data-serving pg assignments
class OSDSizeMethod(Enum):
"""
how to determine the OSD size
"""
CRUSH = 1 # use the crush size
DEVICE = 2 # use the device size
WEIGHTED = 3 # weighted device size
class OSDUsedMethod(Enum):
"""
how to determine the OSD usage size during simulation.
we don't know what the OSD will actually do for movement and cleanup,
so we have options to choose from how to estimate the new usage.
"""
# adjusting the reported osd usage report by adding fractions of currently-in-move pg sizes.
# more accurate but doesn't account pending data deletion.
DELTA = 1
# estimate the usage by summing up all pg shardsizes,
# doesn't account PG metadata.
SHARDSUM = 2
class OSDFromChoiceMethod(Enum):
"""
how to choose a osd to move data from
"""
FULLEST = 1 # use the fullest osd
LIMITING = 2 # use devices limiting the pool available space
ALTERNATE = 3 # alternate between limiting and fullest devices
class PGChoiceMethod(Enum):
"""
how to select a pg for movement
"""
# take the largest pg from the best source osd
LARGEST = 1
# take the median pg size from the best source osd
MEDIAN = 2
# determine the best pg size automatically by looking at the ideal space needed on the emptiest osd.
AUTO = 3
class PoolFreeMethod(Enum):
"""
how available pool space is predicted
"""
# use device utilization and osd weight distribution
WEIGHT = 0
# determine the limiting osd device and exact placement group availability
LIMITING = 1
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)
# in ceph reef, inf is encoded in invalid format for python's json.
rawdata = rawdata.replace(b':inf', b':Infinity')
rawdata = rawdata.decode()
return json.loads(rawdata)
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
def cephtime_to_datetime(cephtime: str) -> datetime.datetime:
"""
converts a ceph dump timestamp to python datetime.
"""
try:
# we've seen: 0.000000, seems to be an old pool :)
val = float(cephtime)
return datetime.datetime.fromtimestamp(val)
except ValueError:
# we have to insert a : in the timezone part so python is happy...
cephtime_with_fixed_timezone = cephtime[:-2] + ":" + cephtime[-2:]
return datetime.datetime.fromisoformat(cephtime_with_fixed_timezone)
def datetime_to_osdmaptime(when: datetime.datetime):
ns = when.time().microsecond * 1000
ts = when.timestamp()
sec = int(ts // 1)
# since osdmap stores real nanoseconds, we can't produce perfect results
# to reduce confusion when comparing diffs, mark the broken nanoseconds
return struct.pack("<II", sec, ns | 0xffff)
def encode_cephtime(when: str):
return datetime_to_osdmaptime(cephtime_to_datetime(when))
def encode_ipstr(ipport: str):
"""
encode an ip string for ceph's addresses
elen: u32
ss_family: u16
sockaddr_data: u8[elen-2]
returns: ceph binary bytearray
"""
ret = bytearray()
ip, port = ipport.rsplit(':', maxsplit=1)
# generated by operator<< for sockaddr in the entity_addr_t::dump json dump
addr_family = socket.AF_INET6 if '[' in ip else socket.AF_INET
# #include <netinet/in.h>
# printf("sizeof(struct sockaddr_in): %zu\n", sizeof(struct sockaddr_in));
# ->
# sizeof(struct sockaddr_in): 16
# sizeof(struct sockaddr_in6): 28
elen = 16 if addr_family == socket.AF_INET else 28
# elen: u32 sockaddr length: sizeof sockaddr_in or sockaddr_in6
ret.extend(struct.pack('<I', elen))
# ss_family: u16
ret.extend(struct.pack('<H', addr_family))
port = int(port)
# strip away the [] around the ipv6 address
if addr_family == socket.AF_INET6:
ip = re.match(r'\[([^\]]+)\]', ip).groups(1)
if not ip:
raise RuntimeError(f"invalid ip: {ip!r}")
ip_bytes = socket.inet_pton(addr_family, ip)
if addr_family == socket.AF_INET:
# struct sockaddr_in {
# u16 family; // -- omitted
# u16 sin_port;
# struct in_addr sin_addr; // u32 address
# };
# omit u16 family as first field
# add 8byte padding to fill up to sizeof(struct sockaddr)=16
# minus the omitted family (2 bytes) -> 14 bytes total size
sockaddr_data = struct.pack('!H4s8x', port, ip_bytes)
elif addr_family == socket.AF_INET6:
# struct sockaddr_in6 {
# u16 family; // -- omitted
# u16 sin6_port; // Transport layer port
# u32 sin6_flowinfo; // IPv6 flow information
# struct in6_addr sin6_addr; // IPv6 address 16 bytes
# u32 sin6_scope_id;
# };
# omit u16 family as first field
sockaddr_data = struct.pack('!HI16sI', port, 0, ip_bytes, 0)
else:
raise RuntimeError("unhandled family")
# only extend by elen - sizeof(family), since we already wrote the family
assert len(sockaddr_data) == (elen - 2)
ret.extend(sockaddr_data)
return ret
def encode_pg_t_from_pgid(pgid):
"""
given: pgid (e.g. 32.af23)
returns: ceph binary encoding of pg_t
"""
# pg_t struct
# u8 v=1, pool, seed, 'was preferred' (sic)
srcpool, srcseed = pgid.split('.')
return struct.pack('<BQIi', 1, int(srcpool), int(srcseed, 16), -1)
# 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]
def list_replace(iterator, search, replace):
ret = list()
for elem in iterator:
if elem == search:
elem = replace
ret.append(elem)
return ret
def replace_missing_osds(osdids):
"""
the "missing" osds have id 2147483647 or 0x7fffffff
replace it with -1
"""
return list_replace(osdids, 0x7fffffff, -1)
def stat_mean(iterable):
"""
calculates mean.
speedup factor ~10 compared to python's statistics.mean
"""
count = len(iterable)
if count == 0:
raise ValueError()
mean = 0
for val in iterable:
mean += val
mean /= count
return mean
def stat_variance(iterable):
"""
calculates variance.
speedup factor ~8 compared to python's statistics.variance
"""
count = len(iterable)
if count == 0:
raise ValueError("iterator length is zero")
if count == 1:
return 0
mean = 0
for val in iterable:
mean += val
mean /= count
diffsum = 0
for val in iterable:
diffsum += (val - mean) ** 2
return 1/(count-1) * diffsum
class open_or_stdout:
"""
supports '-' as filename for stdout.
usage:
with open_or_stdout(filename) as bla:
...
"""
def __init__(self, filename, mode):
if filename == "-":
self.hdl = sys.stdout
else:
self.hdl = open(filename, mode)
def __enter__(self):
return self.hdl
def __exit__(self, type, value, tb):
if self.hdl != sys.stdout:
self.hdl.close()
def moves_from_up_acting(up_osds: List[int],
acting_osds: List[int],
is_ec: bool):
"""
up_osds: planned position
acting_osds: current position
is_ec: is this an erasure coded placement
given two osd lists, return movements. whenever a shard has to be restored,
it's in the source list as -1.
return [(source_osd, ...), (target_osd, ...)]
>>> moves_from_up_acting(up_osds=[], acting_osds=[], is_ec=False)
[]
>>> moves_from_up_acting(up_osds=[], acting_osds=[], is_ec=True)
[]
>>> moves_from_up_acting(up_osds=[1, 2, 3], acting_osds=[1, 2, 3], is_ec=True)
[]
>>> moves_from_up_acting(up_osds=[1, 2, 3], acting_osds=[1, 2, 3], is_ec=False)
[]
# ec tests:
>>> moves_from_up_acting(up_osds=[10, 2, 5, 4], acting_osds=[1, 2, 3, 4], is_ec=True)
[((1,), (10,)), ((3,), (5,))]
>>> moves_from_up_acting(up_osds=[10, 2, 5, 4], acting_osds=[1, 2, -1, 4], is_ec=True)
[((1,), (10,)), ((-1,), (5,))]
# non-ec tests:
>>> moves_from_up_acting(up_osds=[397, 902, 888, 74], acting_osds=[397, 902, 888], is_ec=False)
[((-1,), (74,))]
>>> moves_from_up_acting(up_osds=[397, 902, 888, 74], acting_osds=[397, 902], is_ec=False)
[((-1, -1), (74, 888))]
>>> moves_from_up_acting(up_osds=[1, 2, 3, 4], acting_osds=[1, 3, 2], is_ec=False)
[((-1,), (4,))]
>>> moves_from_up_acting(up_osds=[1, 2, 3, 4], acting_osds=[5, 3, 2], is_ec=False)
[((-1, 5), (1, 4))]
>>> moves_from_up_acting(up_osds=[1, 2, 3, 4], acting_osds=[3, 2], is_ec=False)
[((-1, -1), (1, 4))]
"""
moves = list()
if is_ec:
# for ec, order is important.
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)
# all ups that are not yet acting
to_osds = list(ups - actings)
# all that are acting but don't stay in up.
from_osds = list(actings - ups)
missing_osds = len(to_osds) - len(from_osds)
from_osds.extend([-1] * missing_osds)
if not len(from_osds) == len(to_osds):
raise Exception(f"|from| != |to|: |{from_osds}| != |{to_osds}|")
if from_osds:
moves.append((
tuple(sorted(from_osds)),
tuple(sorted(to_osds)),
))
return moves
def remaps_merge(target_remaps: Dict[int, int],
merge_remaps: Optional[Dict[int, int]] = None,
in_place: bool = False):
"""
remove cycles and transitive remaps from a remap dict.
modifies 'target_remaps'!
if merge_remaps is given, merge those remaps onto the `target_remaps` dict.
>>> remaps_merge({})
{}
>>> remaps_merge({1: 2, 3: 4})
{1: 2, 3: 4}
>>> remaps_merge({1: 2, 2: 3})
{1: 3}
>>> remaps_merge({1: 2}, {2: 3})
{1: 3}
>>> remaps_merge({1: 2, 2: 1})
{}
>>> remaps_merge({1: 2, 2: 3, 3: 4})
{1: 4}
>>> remaps_merge({1: 2, 2: 3}, {3: 4})
{1: 4}
>>> remaps_merge({216: 205, 360: 294}, {294: 216})
{360: 205}
>>> remaps_merge({1: 2, 2: 3}, {1: 4})
{1: 4}
>>> remaps_merge({1: 2, 2: 3}, {1: 4, 4: 5})
{1: 5}
"""
ret = dict()
if in_place:
destination = target_remaps
else:
destination = target_remaps.copy()
def merge_chains(remaps):
for osd_from, osd_to in remaps.copy().items():
while True:
# given (a, b) is there (b, c)?
next_to = remaps.get(osd_to)
if next_to is not None:
if osd_from == next_to:
# symmetric: it's (a, b), (b, a)
del remaps[osd_to]
if merge_remaps is None:
# in-place operation
del remaps[next_to]
else:
# transitive: it's (a, b), (b, c) so we set (a, c) and remove (b, c)
remaps[osd_from] = next_to
del remaps[osd_to]
# follow the remap-chain
osd_to = next_to
else:
break
merge_chains(destination)
if merge_remaps is not None:
destination.update(merge_remaps)
merge_chains(destination)
if False:
# TODO: remove once confident enough the above is correct :)
for new_from, new_to in destination.items():
if new_from == new_to:
raise RuntimeError(f"somewhere something went wrong: "
f"we map from osd.{new_from} to osd.{new_to} in "
f"{destination}")
while True:
next_to = destination.get(new_to)
if next_to is not None:
raise RuntimeError(f"something went wrong: "
f"there's still transitive remaps left for {new_to}: "
f"{destination}")
else:
break
return destination
def pool_from_pg(pg):
return int(pg.split(".")[0])
def bucket_fill(id, bucket_info, parent_id=None):
"""
returns the list of all child buckets for a given id
plus for each of those, their children.
"""
bucket = bucket_info[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_info[child_item["id"]]
cid = child["id"]
if cid < 0:
new_nodes, new_ids = bucket_fill(cid, bucket_info, 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
class ClusterState:
# to detect if imported state files are incompatible
STATE_VERSION = 1
def __init__(self, statefile: Optional[str] = None,
osdsize_method: OSDSizeMethod = OSDSizeMethod.CRUSH):
self.state = dict()
self.load(statefile)
self.osdsize_method = osdsize_method
def load(self, statefile: Optional[str]):
# use cluster state from a file
if statefile:
logging.info(f"loading cluster state from file {statefile}...")
with lzma.open(statefile) as hdl:
self.state = json.load(hdl)
import_version = self.state['stateversion']
if import_version != self.STATE_VERSION:
raise RuntimeError(f"imported file stores state in version {import_version}, but we need {self.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"
self.state = dict(
stateversion=self.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()),
# ceph pg dump always echoes "dumped all" on stderr, silence that.
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
self.state["crush_class_osds"][crush_class] = class_osds
# check if the osdmap version changed meanwhile
# => we'd have inconsistent state
if self.state['osd_dump']['epoch'] != jsoncall("ceph osd dump --format json".split())['epoch']:
raise RuntimeError("Cluster topology changed during information gathering (e.g. a pg changed state). "
"Wait for things to calm down and try again")
def dump(self, output_file):
logging.info(f"cluster state dumped. now saving to {output_file}...")
with lzma.open(output_file, "wt") as hdl:
json.dump(self.state, hdl, indent='\t')
logging.warning(f"cluster state saved to {output_file}")
def export_osdmap(self, output_file, ignore_state_upmaps=False):
logging.info(f"exporting cluster state as osdmap to {output_file}...")
out = io.BytesIO()
def writeb(data, name=None):
logging.debug(strlazy(lambda: f"[{out.tell():>10x}] {binascii.hexlify(data)} {'<- %s' % name if name else ''}"))
out.write(data)
class StructLength:
"""
write a u32 length field and remember its position.
"""
def __init__(self, stream, name=None):
self.stream = stream
self.name = name or "struct"
self.len_field_pos = stream.tell()
# struct_len: u32
# fill the len hole with dummy data
writeb(struct.pack('<I', 0xbbbbbbbb), f'{self.name}_len_dummy')
def write_len(self):
struct_len = self.stream.tell() - self.len_field_pos - 4
assert struct_len >= 0
return_pos = self.stream.tell()
out.seek(self.len_field_pos)
writeb(struct.pack('<I', struct_len), f'{self.name}_len_update')
out.seek(return_pos)
class StructVersion(StructLength):
"""
like StructLength, but with additional version header fields.
"""
def __init__(self, stream, struct_v, compat_v, name=None):
name = name or "struct"
# 1+1+4 byte compat header
writeb(struct.pack('<B', struct_v), f'{name}_struct_v')
writeb(struct.pack('<B', compat_v), f'{name}_compat_v')
# length field
super().__init__(stream, name)
# 1+1+4 byte outer osdmap struct header
osdmap_struct = StructVersion(out, 8, 7, 'osdmap')
# 1+1+4 byte client data header
# struct_v bumped to 9 in d414f0b43a69f3c2db8e454d795be881496237c
osdmap_client_struct = StructVersion(out, 9, 1, 'osdmap_clientdata')
# fsid: 16 byte uuid
writeb(uuid.UUID(self.state['osd_dump']['fsid']).bytes, 'fsid')
# epoch: u32
writeb(struct.pack('<I', self.state['osd_dump']['epoch']), 'epoch')
# created: utime_t
writeb(encode_cephtime(self.state['osd_dump']['created']), 'created') # u32 sec, u32 nsec
# modified: utime_t
writeb(encode_cephtime(self.state['osd_dump']['modified']), 'modified') # u32 sec, u32 nsec
# pools: map<int64, pg_pool_t> (u32 map.size())
pools = self.state['osd_dump']['pools']
writeb(struct.pack('<I', len(pools)), 'pools_map_len')
for pool in pools:
# s64 pool id for map
writeb(struct.pack('<q', pool['pool']), 'pool_id')
# start pg_pool_t
# 1+1+4 byte compat header:
# u8 struct_v, u8 compat_v
pg_pool_t_struct = StructVersion(out, 29, 5, f'pg_pool_t_{pool["pool"]}')
# u8 type
writeb(struct.pack('<B', pool['type']), 'type')
# u8 size;
writeb(struct.pack('<B', pool['size']), 'size')
# u8 crush_rule;
writeb(struct.pack('<B', pool['crush_rule']), 'crush_rule')
# u8 object_hash;
writeb(struct.pack('<B', pool['object_hash']), 'object_hash')
# u32 pg_num;
writeb(struct.pack('<I', pool['pg_num']), 'pg_num')
# missing u32 pgp_num, reuse pg_num
writeb(struct.pack('<I', pool['pg_num']), 'pgp_num')
# legacy u32 lpg_num = 0; # localized pgs
writeb(struct.pack('<I', 0), 'lpg_num')
# legacy u32 lpgp_num = 0;
writeb(struct.pack('<I', 0), 'lpgp_num')
# u32 last_change; # epoch
writeb(struct.pack('<I', int(pool["last_change"])), 'last_change')
# u64 snapid_t snap_seq
writeb(struct.pack('<Q', pool['snap_seq']), 'snap_seq')
# u32 snap_epoch
writeb(struct.pack('<I', pool['snap_epoch']), 'snap_epoch')
# fake map<snapid_t, pool_snap_info_t>
writeb(struct.pack('<I', 0), 'snap_info_map_len')
# fake interval_set<snapid_t> removed_snaps
writeb(struct.pack('<I', 0), 'removed_snap_set_len')
# u64 auid
writeb(struct.pack('<Q', pool["auid"]), 'auid')
# u64 flags
writeb(struct.pack('<Q', pool["flags"]), 'flags')
# legacy u32 crash_replay_interval
writeb(struct.pack('<I', 0), 'crash_replay_interval')
# u8 min_size;
writeb(struct.pack('<B', pool['min_size']), 'min_size')
# u64 quota_max_bytes
writeb(struct.pack('<Q', pool["quota_max_bytes"]), 'quota_max_bytes')
# u64 quota_max_objects
writeb(struct.pack('<Q', pool["quota_max_objects"]), 'quota_max_objects')
# fake set<u64> tiers;
writeb(struct.pack('<I', 0), "tiers")
# fake s64 tier_of
writeb(struct.pack('<q', -1), "tier_of")
# fake u8 cache_mode. 0=none
writeb(struct.pack('<B', 0), "cache_mode")
# fake s64 read_tier
writeb(struct.pack('<q', -1), "read_tier")
# fake s64 write_tier
writeb(struct.pack('<q', -1), "write_tier")
# legacy map<std::string, std::string> properties;
writeb(struct.pack('<I', 0), 'properties old')
# fake hit_set_params
writeb(struct.pack('<BBI', 1, 1, 1), 'hit_set_compat_ver') # ver, compatver, structlen
writeb(struct.pack('<B', 0), 'hit_set_param_none') # hitset::params::type_none
# u32 hit_set_period
writeb(struct.pack('<I', pool['hit_set_period']), 'hit_set_period')
# u32 hit_set_count
writeb(struct.pack('<I', pool['hit_set_count']), 'hit_set_count')
# u32 stripe_width
writeb(struct.pack('<I', pool['stripe_width']), 'stripe_width')
# u64 target_max_bytes
writeb(struct.pack('<Q', pool['target_max_bytes']), 'target_max_bytes')
# u64 target_max_objects
writeb(struct.pack('<Q', pool['target_max_objects']), 'target_max_objs')
# u32 cache_target_dirty_ratio_micro
writeb(struct.pack('<I', pool['cache_target_dirty_ratio_micro']), 'cache_target_dirty_ratio')
# u32 cache_target_full_ratio_micro
writeb(struct.pack('<I', pool['cache_target_full_ratio_micro']), 'cache_target_full_ratio')
# u32 cache_min_flush_age
writeb(struct.pack('<I', pool['cache_min_flush_age']), 'cache_min_flush_age')
# u32 cache_min_evict_age
writeb(struct.pack('<I', pool['cache_min_evict_age']), 'cache_min_evict_age')
# string erasure_code_profile
writeb(struct.pack('<I', len(pool['erasure_code_profile'].encode())) + pool['erasure_code_profile'].encode(), 'ec_profile_name')
# u32 last_force_op_resend_preluminous
writeb(struct.pack('<I', int(pool['last_force_op_resend_preluminous'])), 'last_force_op_resend_preluminous')
# u32 min_read_recency_for_promote
writeb(struct.pack('<I', pool['min_read_recency_for_promote']), 'min_read_recency_for_promote')
# u64 expected_num_objects
writeb(struct.pack('<Q', pool['expected_num_objects']), 'expected_num_objects')
# u32 cache_target_dirty_high_ratio_micro
writeb(struct.pack('<I', pool['cache_target_dirty_high_ratio_micro']), 'cache_target_dirty_high_ratio_micro')
# u32 min_write_recency_for_promote
writeb(struct.pack('<I', pool['min_write_recency_for_promote']), 'min_write_recency_for_promote')
# bool(u8) use_gmt_hitset
writeb(struct.pack('<B', int(pool['use_gmt_hitset'])), 'use_gmt_hitset')
# bool(u8) fast_read
writeb(struct.pack('<B', int(pool['fast_read'])), 'fast_read')
# u32 hit_set_grade_decay_rate
writeb(struct.pack('<I', pool['hit_set_grade_decay_rate']), 'hit_set_grade_decay_rate')
# u32 hit_set_search_last_n
writeb(struct.pack('<I', pool['hit_set_search_last_n']), 'hit_set_search_last_n')
# pool_opts_t opts
pool_opts_struct = StructVersion(out, 2, 1, f'pool_{pool["pool"]}_pool_opts_t')
# pool_opts_t map<u32, boost:variant...> (len(pool['options']))
# u32 options_len
writeb(struct.pack('<I', len(pool['options'])), 'pool_opts_t_len')
# pool_opts_t::key_t
# and its string+arg variants: opt_mapping_t
option_ids = {
'scrub_min_interval': 0,
'scrub_max_interval': 1,
'deep_scrub_interval': 2,
'recovery_priority': 3,
'recovery_op_priority': 4,
'scrub_priority': 5,
'compression_mode': 6,
'compression_algorithm': 7,
'compression_required_ratio': 8,
'compression_max_blob_size': 9,
'compression_min_blob_size': 10,
'csum_type': 11,
'csum_max_block': 12,