-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathceph_manager.py
3193 lines (2930 loc) · 120 KB
/
ceph_manager.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
"""
ceph manager -- Thrasher and CephManager objects
"""
from functools import wraps
import contextlib
import errno
import random
import signal
import time
import gevent
import base64
import json
import logging
import threading
import traceback
import os
import shlex
from io import BytesIO, StringIO
from subprocess import DEVNULL
from teuthology import misc as teuthology
from tasks.scrub import Scrubber
from tasks.util.rados import cmd_erasure_code_profile
from tasks.util import get_remote
from teuthology.contextutil import safe_while
from teuthology.orchestra.remote import Remote
from teuthology.orchestra import run
from teuthology.exceptions import CommandFailedError
from tasks.thrasher import Thrasher
DEFAULT_CONF_PATH = '/etc/ceph/ceph.conf'
log = logging.getLogger(__name__)
# this is for cephadm clusters
def shell(ctx, cluster_name, remote, args, name=None, **kwargs):
extra_args = []
if name:
extra_args = ['-n', name]
return remote.run(
args=[
'sudo',
ctx.cephadm,
'--image', ctx.ceph[cluster_name].image,
'shell',
] + extra_args + [
'--fsid', ctx.ceph[cluster_name].fsid,
'--',
] + args,
**kwargs
)
# this is for rook clusters
def toolbox(ctx, cluster_name, args, **kwargs):
return ctx.rook[cluster_name].remote.run(
args=[
'kubectl',
'-n', 'rook-ceph',
'exec',
ctx.rook[cluster_name].toolbox,
'--',
] + args,
**kwargs
)
def write_conf(ctx, conf_path=DEFAULT_CONF_PATH, cluster='ceph'):
conf_fp = BytesIO()
ctx.ceph[cluster].conf.write(conf_fp)
conf_fp.seek(0)
writes = ctx.cluster.run(
args=[
'sudo', 'mkdir', '-p', '/etc/ceph', run.Raw('&&'),
'sudo', 'chmod', '0755', '/etc/ceph', run.Raw('&&'),
'sudo', 'tee', conf_path, run.Raw('&&'),
'sudo', 'chmod', '0644', conf_path,
run.Raw('>'), '/dev/null',
],
stdin=run.PIPE,
wait=False)
teuthology.feed_many_stdins_and_close(conf_fp, writes)
run.wait(writes)
def get_valgrind_args(testdir, name, preamble, v, exit_on_first_error=True, cd=True):
"""
Build a command line for running valgrind.
testdir - test results directory
name - name of daemon (for naming hte log file)
preamble - stuff we should run before valgrind
v - valgrind arguments
"""
if v is None:
return preamble
if not isinstance(v, list):
v = [v]
# https://tracker.ceph.com/issues/44362
preamble.extend([
'env', 'OPENSSL_ia32cap=~0x1000000000000000',
])
val_path = '/var/log/ceph/valgrind'
if '--tool=memcheck' in v or '--tool=helgrind' in v:
extra_args = [
'valgrind',
'--trace-children=no',
'--child-silent-after-fork=yes',
'--soname-synonyms=somalloc=*tcmalloc*',
'--num-callers=50',
'--suppressions={tdir}/valgrind.supp'.format(tdir=testdir),
'--xml=yes',
'--xml-file={vdir}/{n}.log'.format(vdir=val_path, n=name),
'--time-stamp=yes',
'--vgdb=yes',
]
else:
extra_args = [
'valgrind',
'--trace-children=no',
'--child-silent-after-fork=yes',
'--soname-synonyms=somalloc=*tcmalloc*',
'--suppressions={tdir}/valgrind.supp'.format(tdir=testdir),
'--log-file={vdir}/{n}.log'.format(vdir=val_path, n=name),
'--time-stamp=yes',
'--vgdb=yes',
]
if exit_on_first_error:
extra_args.extend([
# at least Valgrind 3.14 is required
'--exit-on-first-error=yes',
'--error-exitcode=42',
])
args = []
if cd:
args += ['cd', testdir, run.Raw('&&')]
args += preamble + extra_args + v
log.debug('running %s under valgrind with args %s', name, args)
return args
def mount_osd_data(ctx, remote, cluster, osd):
"""
Mount a remote OSD
:param ctx: Context
:param remote: Remote site
:param cluster: name of ceph cluster
:param osd: Osd name
"""
log.debug('Mounting data for osd.{o} on {r}'.format(o=osd, r=remote))
role = "{0}.osd.{1}".format(cluster, osd)
alt_role = role if cluster != 'ceph' else "osd.{0}".format(osd)
if remote in ctx.disk_config.remote_to_roles_to_dev:
if alt_role in ctx.disk_config.remote_to_roles_to_dev[remote]:
role = alt_role
if role not in ctx.disk_config.remote_to_roles_to_dev[remote]:
return
dev = ctx.disk_config.remote_to_roles_to_dev[remote][role]
mount_options = ctx.disk_config.\
remote_to_roles_to_dev_mount_options[remote][role]
fstype = ctx.disk_config.remote_to_roles_to_dev_fstype[remote][role]
mnt = os.path.join('/var/lib/ceph/osd', '{0}-{1}'.format(cluster, osd))
log.info('Mounting osd.{o}: dev: {n}, cluster: {c}'
'mountpoint: {p}, type: {t}, options: {v}'.format(
o=osd, n=remote.name, p=mnt, t=fstype, v=mount_options,
c=cluster))
remote.run(
args=[
'sudo',
'mount',
'-t', fstype,
'-o', ','.join(mount_options),
dev,
mnt,
]
)
def log_exc(func):
@wraps(func)
def wrapper(self):
try:
return func(self)
except:
self.log(traceback.format_exc())
raise
return wrapper
class PoolType:
REPLICATED = 1
ERASURE_CODED = 3
class OSDThrasher(Thrasher):
"""
Object used to thrash Ceph
"""
def __init__(self, manager, config, name, logger):
super(OSDThrasher, self).__init__()
self.ceph_manager = manager
self.cluster = manager.cluster
self.ceph_manager.wait_for_clean()
osd_status = self.ceph_manager.get_osd_status()
self.in_osds = osd_status['in']
self.live_osds = osd_status['live']
self.out_osds = osd_status['out']
self.dead_osds = osd_status['dead']
self.stopping = False
self.logger = logger
self.config = config
self.name = name
self.revive_timeout = self.config.get("revive_timeout", 360)
self.pools_to_fix_pgp_num = set()
if self.config.get('powercycle'):
self.revive_timeout += 120
self.clean_wait = self.config.get('clean_wait', 0)
self.minin = self.config.get("min_in", 4)
self.chance_move_pg = self.config.get('chance_move_pg', 1.0)
self.sighup_delay = self.config.get('sighup_delay')
self.optrack_toggle_delay = self.config.get('optrack_toggle_delay')
self.dump_ops_enable = self.config.get('dump_ops_enable')
self.noscrub_toggle_delay = self.config.get('noscrub_toggle_delay')
self.chance_thrash_cluster_full = self.config.get('chance_thrash_cluster_full', .05)
self.chance_thrash_pg_upmap = self.config.get('chance_thrash_pg_upmap', 1.0)
self.chance_thrash_pg_upmap_items = self.config.get('chance_thrash_pg_upmap', 1.0)
self.random_eio = self.config.get('random_eio')
self.chance_force_recovery = self.config.get('chance_force_recovery', 0.3)
num_osds = self.in_osds + self.out_osds
self.max_pgs = self.config.get("max_pgs_per_pool_osd", 1200) * len(num_osds)
self.min_pgs = self.config.get("min_pgs_per_pool_osd", 1) * len(num_osds)
if self.config is None:
self.config = dict()
# prevent monitor from auto-marking things out while thrasher runs
# try both old and new tell syntax, in case we are testing old code
self.saved_options = []
# assuming that the default settings do not vary from one daemon to
# another
first_mon = teuthology.get_first_mon(manager.ctx, self.config).split('.')
opts = [('mon', 'mon_osd_down_out_interval', 0)]
#why do we disable marking an OSD out automatically? :/
for service, opt, new_value in opts:
old_value = manager.get_config(first_mon[0],
first_mon[1],
opt)
self.saved_options.append((service, opt, old_value))
manager.inject_args(service, '*', opt, new_value)
# initialize ceph_objectstore_tool property - must be done before
# do_thrash is spawned - http://tracker.ceph.com/issues/18799
if (self.config.get('powercycle') or
not self.cmd_exists_on_osds("ceph-objectstore-tool") or
self.config.get('disable_objectstore_tool_tests', False)):
self.ceph_objectstore_tool = False
if self.config.get('powercycle'):
self.log("Unable to test ceph-objectstore-tool, "
"powercycle testing")
else:
self.log("Unable to test ceph-objectstore-tool, "
"not available on all OSD nodes")
else:
self.ceph_objectstore_tool = \
self.config.get('ceph_objectstore_tool', True)
# spawn do_thrash
self.thread = gevent.spawn(self.do_thrash)
if self.sighup_delay:
self.sighup_thread = gevent.spawn(self.do_sighup)
if self.optrack_toggle_delay:
self.optrack_toggle_thread = gevent.spawn(self.do_optrack_toggle)
if self.dump_ops_enable == "true":
self.dump_ops_thread = gevent.spawn(self.do_dump_ops)
if self.noscrub_toggle_delay:
self.noscrub_toggle_thread = gevent.spawn(self.do_noscrub_toggle)
def log(self, msg, *args, **kwargs):
self.logger.info(msg, *args, **kwargs)
def cmd_exists_on_osds(self, cmd):
if self.ceph_manager.cephadm or self.ceph_manager.rook:
return True
allremotes = self.ceph_manager.ctx.cluster.only(\
teuthology.is_type('osd', self.cluster)).remotes.keys()
allremotes = list(set(allremotes))
for remote in allremotes:
proc = remote.run(args=['type', cmd], wait=True,
check_status=False, stdout=BytesIO(),
stderr=BytesIO())
if proc.exitstatus != 0:
return False;
return True;
def run_ceph_objectstore_tool(self, remote, osd, cmd):
if self.ceph_manager.cephadm:
return shell(
self.ceph_manager.ctx, self.ceph_manager.cluster, remote,
args=['ceph-objectstore-tool', '--err-to-stderr'] + cmd,
name=osd,
wait=True, check_status=False,
stdout=StringIO(),
stderr=StringIO())
elif self.ceph_manager.rook:
assert False, 'not implemented'
else:
return remote.run(
args=['sudo', 'adjust-ulimits', 'ceph-objectstore-tool', '--err-to-stderr'] + cmd,
wait=True, check_status=False,
stdout=StringIO(),
stderr=StringIO())
def run_ceph_bluestore_tool(self, remote, osd, cmd):
if self.ceph_manager.cephadm:
return shell(
self.ceph_manager.ctx, self.ceph_manager.cluster, remote,
args=['ceph-bluestore-tool', '--err-to-stderr'] + cmd,
name=osd,
wait=True, check_status=False,
stdout=StringIO(),
stderr=StringIO())
elif self.ceph_manager.rook:
assert False, 'not implemented'
else:
return remote.run(
args=['sudo', 'ceph-bluestore-tool', '--err-to-stderr'] + cmd,
wait=True, check_status=False,
stdout=StringIO(),
stderr=StringIO())
def kill_osd(self, osd=None, mark_down=False, mark_out=False):
"""
:param osd: Osd to be killed.
:mark_down: Mark down if true.
:mark_out: Mark out if true.
"""
if osd is None:
osd = random.choice(self.live_osds)
self.log("Killing osd %s, live_osds are %s" % (str(osd),
str(self.live_osds)))
self.live_osds.remove(osd)
self.dead_osds.append(osd)
self.ceph_manager.kill_osd(osd)
if mark_down:
self.ceph_manager.mark_down_osd(osd)
if mark_out and osd in self.in_osds:
self.out_osd(osd)
if self.ceph_objectstore_tool:
self.log("Testing ceph-objectstore-tool on down osd.%s" % osd)
remote = self.ceph_manager.find_remote('osd', osd)
FSPATH = self.ceph_manager.get_filepath()
JPATH = os.path.join(FSPATH, "journal")
exp_osd = imp_osd = osd
self.log('remote for osd %s is %s' % (osd, remote))
exp_remote = imp_remote = remote
# If an older osd is available we'll move a pg from there
if (len(self.dead_osds) > 1 and
random.random() < self.chance_move_pg):
exp_osd = random.choice(self.dead_osds[:-1])
exp_remote = self.ceph_manager.find_remote('osd', exp_osd)
self.log('remote for exp osd %s is %s' % (exp_osd, exp_remote))
prefix = [
'--no-mon-config',
'--log-file=/var/log/ceph/objectstore_tool.$pid.log',
]
if self.ceph_manager.rook:
assert False, 'not implemented'
if not self.ceph_manager.cephadm:
# ceph-objectstore-tool might be temporarily absent during an
# upgrade - see http://tracker.ceph.com/issues/18014
with safe_while(sleep=15, tries=40, action="type ceph-objectstore-tool") as proceed:
while proceed():
proc = exp_remote.run(args=['type', 'ceph-objectstore-tool'],
wait=True, check_status=False, stdout=BytesIO(),
stderr=BytesIO())
if proc.exitstatus == 0:
break
log.debug("ceph-objectstore-tool binary not present, trying again")
# ceph-objectstore-tool might bogusly fail with "OSD has the store locked"
# see http://tracker.ceph.com/issues/19556
with safe_while(sleep=15, tries=40, action="ceph-objectstore-tool --op list-pgs") as proceed:
while proceed():
proc = self.run_ceph_objectstore_tool(
exp_remote, 'osd.%s' % exp_osd,
prefix + [
'--data-path', FSPATH.format(id=exp_osd),
'--journal-path', JPATH.format(id=exp_osd),
'--op', 'list-pgs',
])
if proc.exitstatus == 0:
break
elif (proc.exitstatus == 1 and
proc.stderr.getvalue() == "OSD has the store locked"):
continue
else:
raise Exception("ceph-objectstore-tool: "
"exp list-pgs failure with status {ret}".
format(ret=proc.exitstatus))
pgs = proc.stdout.getvalue().split('\n')[:-1]
if len(pgs) == 0:
self.log("No PGs found for osd.{osd}".format(osd=exp_osd))
return
pg = random.choice(pgs)
#exp_path = teuthology.get_testdir(self.ceph_manager.ctx)
#exp_path = os.path.join(exp_path, '{0}.data'.format(self.cluster))
exp_path = os.path.join('/var/log/ceph', # available inside 'shell' container
"exp.{pg}.{id}".format(
pg=pg,
id=exp_osd))
if self.ceph_manager.cephadm:
exp_host_path = os.path.join(
'/var/log/ceph',
self.ceph_manager.ctx.ceph[self.ceph_manager.cluster].fsid,
"exp.{pg}.{id}".format(
pg=pg,
id=exp_osd))
else:
exp_host_path = exp_path
# export
# Can't use new export-remove op since this is part of upgrade testing
proc = self.run_ceph_objectstore_tool(
exp_remote, 'osd.%s' % exp_osd,
prefix + [
'--data-path', FSPATH.format(id=exp_osd),
'--journal-path', JPATH.format(id=exp_osd),
'--op', 'export',
'--pgid', pg,
'--file', exp_path,
])
if proc.exitstatus:
raise Exception("ceph-objectstore-tool: "
"export failure with status {ret}".
format(ret=proc.exitstatus))
# remove
proc = self.run_ceph_objectstore_tool(
exp_remote, 'osd.%s' % exp_osd,
prefix + [
'--data-path', FSPATH.format(id=exp_osd),
'--journal-path', JPATH.format(id=exp_osd),
'--force',
'--op', 'remove',
'--pgid', pg,
])
if proc.exitstatus:
raise Exception("ceph-objectstore-tool: "
"remove failure with status {ret}".
format(ret=proc.exitstatus))
# If there are at least 2 dead osds we might move the pg
if exp_osd != imp_osd:
# If pg isn't already on this osd, then we will move it there
proc = self.run_ceph_objectstore_tool(
imp_remote,
'osd.%s' % imp_osd,
prefix + [
'--data-path', FSPATH.format(id=imp_osd),
'--journal-path', JPATH.format(id=imp_osd),
'--op', 'list-pgs',
])
if proc.exitstatus:
raise Exception("ceph-objectstore-tool: "
"imp list-pgs failure with status {ret}".
format(ret=proc.exitstatus))
pgs = proc.stdout.getvalue().split('\n')[:-1]
if pg not in pgs:
self.log("Moving pg {pg} from osd.{fosd} to osd.{tosd}".
format(pg=pg, fosd=exp_osd, tosd=imp_osd))
if imp_remote != exp_remote:
# Copy export file to the other machine
self.log("Transfer export file from {srem} to {trem}".
format(srem=exp_remote, trem=imp_remote))
# just in case an upgrade make /var/log/ceph unreadable by non-root,
exp_remote.run(args=['sudo', 'chmod', '777',
'/var/log/ceph'])
imp_remote.run(args=['sudo', 'chmod', '777',
'/var/log/ceph'])
tmpexport = Remote.get_file(exp_remote, exp_host_path,
sudo=True)
if exp_host_path != exp_path:
# push to /var/log/ceph, then rename (we can't
# chmod 777 the /var/log/ceph/$fsid mountpoint)
Remote.put_file(imp_remote, tmpexport, exp_path)
imp_remote.run(args=[
'sudo', 'mv', exp_path, exp_host_path])
else:
Remote.put_file(imp_remote, tmpexport, exp_host_path)
os.remove(tmpexport)
else:
# Can't move the pg after all
imp_osd = exp_osd
imp_remote = exp_remote
# import
proc = self.run_ceph_objectstore_tool(
imp_remote, 'osd.%s' % imp_osd,
[
'--data-path', FSPATH.format(id=imp_osd),
'--journal-path', JPATH.format(id=imp_osd),
'--log-file=/var/log/ceph/objectstore_tool.$pid.log',
'--op', 'import',
'--file', exp_path,
])
if proc.exitstatus == 1:
bogosity = "The OSD you are using is older than the exported PG"
if bogosity in proc.stderr.getvalue():
self.log("OSD older than exported PG"
"...ignored")
elif proc.exitstatus == 10:
self.log("Pool went away before processing an import"
"...ignored")
elif proc.exitstatus == 11:
self.log("Attempt to import an incompatible export"
"...ignored")
elif proc.exitstatus == 12:
# this should be safe to ignore because we only ever move 1
# copy of the pg at a time, and merge is only initiated when
# all replicas are peered and happy. /me crosses fingers
self.log("PG merged on target"
"...ignored")
elif proc.exitstatus:
raise Exception("ceph-objectstore-tool: "
"import failure with status {ret}".
format(ret=proc.exitstatus))
cmd = "sudo rm -f {file}".format(file=exp_host_path)
exp_remote.run(args=cmd)
if imp_remote != exp_remote:
imp_remote.run(args=cmd)
# apply low split settings to each pool
if not self.ceph_manager.cephadm:
for pool in self.ceph_manager.list_pools():
cmd = ("CEPH_ARGS='--filestore-merge-threshold 1 "
"--filestore-split-multiple 1' sudo -E "
+ 'ceph-objectstore-tool '
+ ' '.join(prefix + [
'--data-path', FSPATH.format(id=imp_osd),
'--journal-path', JPATH.format(id=imp_osd),
])
+ " --op apply-layout-settings --pool " + pool).format(id=osd)
proc = imp_remote.run(args=cmd,
wait=True, check_status=False,
stderr=StringIO())
if 'Couldn\'t find pool' in proc.stderr.getvalue():
continue
if proc.exitstatus:
raise Exception("ceph-objectstore-tool apply-layout-settings"
" failed with {status}".format(status=proc.exitstatus))
def blackhole_kill_osd(self, osd=None):
"""
If all else fails, kill the osd.
:param osd: Osd to be killed.
"""
if osd is None:
osd = random.choice(self.live_osds)
self.log("Blackholing and then killing osd %s, live_osds are %s" %
(str(osd), str(self.live_osds)))
self.live_osds.remove(osd)
self.dead_osds.append(osd)
self.ceph_manager.blackhole_kill_osd(osd)
def revive_osd(self, osd=None, skip_admin_check=False):
"""
Revive the osd.
:param osd: Osd to be revived.
"""
if osd is None:
osd = random.choice(self.dead_osds)
self.log("Reviving osd %s" % (str(osd),))
self.ceph_manager.revive_osd(
osd,
self.revive_timeout,
skip_admin_check=skip_admin_check)
self.dead_osds.remove(osd)
self.live_osds.append(osd)
if self.random_eio > 0 and osd == self.rerrosd:
self.ceph_manager.set_config(self.rerrosd,
filestore_debug_random_read_err = self.random_eio)
self.ceph_manager.set_config(self.rerrosd,
bluestore_debug_random_read_err = self.random_eio)
def out_osd(self, osd=None):
"""
Mark the osd out
:param osd: Osd to be marked.
"""
if osd is None:
osd = random.choice(self.in_osds)
self.log("Removing osd %s, in_osds are: %s" %
(str(osd), str(self.in_osds)))
self.ceph_manager.mark_out_osd(osd)
self.in_osds.remove(osd)
self.out_osds.append(osd)
def in_osd(self, osd=None):
"""
Mark the osd out
:param osd: Osd to be marked.
"""
if osd is None:
osd = random.choice(self.out_osds)
if osd in self.dead_osds:
return self.revive_osd(osd)
self.log("Adding osd %s" % (str(osd),))
self.out_osds.remove(osd)
self.in_osds.append(osd)
self.ceph_manager.mark_in_osd(osd)
self.log("Added osd %s" % (str(osd),))
def reweight_osd_or_by_util(self, osd=None):
"""
Reweight an osd that is in
:param osd: Osd to be marked.
"""
if osd is not None or random.choice([True, False]):
if osd is None:
osd = random.choice(self.in_osds)
val = random.uniform(.1, 1.0)
self.log("Reweighting osd %s to %s" % (str(osd), str(val)))
self.ceph_manager.raw_cluster_cmd('osd', 'reweight',
str(osd), str(val))
else:
# do it several times, the option space is large
for i in range(5):
options = {
'max_change': random.choice(['0.05', '1.0', '3.0']),
'overage': random.choice(['110', '1000']),
'type': random.choice([
'reweight-by-utilization',
'test-reweight-by-utilization']),
}
self.log("Reweighting by: %s"%(str(options),))
self.ceph_manager.raw_cluster_cmd(
'osd',
options['type'],
options['overage'],
options['max_change'])
def primary_affinity(self, osd=None):
if osd is None:
osd = random.choice(self.in_osds)
if random.random() >= .5:
pa = random.random()
elif random.random() >= .5:
pa = 1
else:
pa = 0
self.log('Setting osd %s primary_affinity to %f' % (str(osd), pa))
self.ceph_manager.raw_cluster_cmd('osd', 'primary-affinity',
str(osd), str(pa))
def thrash_cluster_full(self):
"""
Set and unset cluster full condition
"""
self.log('Setting full ratio to .001')
self.ceph_manager.raw_cluster_cmd('osd', 'set-full-ratio', '.001')
time.sleep(1)
self.log('Setting full ratio back to .95')
self.ceph_manager.raw_cluster_cmd('osd', 'set-full-ratio', '.95')
def thrash_pg_upmap(self):
"""
Install or remove random pg_upmap entries in OSDMap
"""
from random import shuffle
out = self.ceph_manager.raw_cluster_cmd('osd', 'dump', '-f', 'json-pretty')
j = json.loads(out)
self.log('j is %s' % j)
try:
if random.random() >= .3:
pgs = self.ceph_manager.get_pg_stats()
if not pgs:
return
pg = random.choice(pgs)
pgid = str(pg['pgid'])
poolid = int(pgid.split('.')[0])
sizes = [x['size'] for x in j['pools'] if x['pool'] == poolid]
if len(sizes) == 0:
return
n = sizes[0]
osds = self.in_osds + self.out_osds
shuffle(osds)
osds = osds[0:n]
self.log('Setting %s to %s' % (pgid, osds))
cmd = ['osd', 'pg-upmap', pgid] + [str(x) for x in osds]
self.log('cmd %s' % cmd)
self.ceph_manager.raw_cluster_cmd(*cmd)
else:
m = j['pg_upmap']
if len(m) > 0:
shuffle(m)
pg = m[0]['pgid']
self.log('Clearing pg_upmap on %s' % pg)
self.ceph_manager.raw_cluster_cmd(
'osd',
'rm-pg-upmap',
pg)
else:
self.log('No pg_upmap entries; doing nothing')
except CommandFailedError:
self.log('Failed to rm-pg-upmap, ignoring')
def thrash_pg_upmap_items(self):
"""
Install or remove random pg_upmap_items entries in OSDMap
"""
from random import shuffle
out = self.ceph_manager.raw_cluster_cmd('osd', 'dump', '-f', 'json-pretty')
j = json.loads(out)
self.log('j is %s' % j)
try:
if random.random() >= .3:
pgs = self.ceph_manager.get_pg_stats()
if not pgs:
return
pg = random.choice(pgs)
pgid = str(pg['pgid'])
poolid = int(pgid.split('.')[0])
sizes = [x['size'] for x in j['pools'] if x['pool'] == poolid]
if len(sizes) == 0:
return
n = sizes[0]
osds = self.in_osds + self.out_osds
shuffle(osds)
osds = osds[0:n*2]
self.log('Setting %s to %s' % (pgid, osds))
cmd = ['osd', 'pg-upmap-items', pgid] + [str(x) for x in osds]
self.log('cmd %s' % cmd)
self.ceph_manager.raw_cluster_cmd(*cmd)
else:
m = j['pg_upmap_items']
if len(m) > 0:
shuffle(m)
pg = m[0]['pgid']
self.log('Clearing pg_upmap on %s' % pg)
self.ceph_manager.raw_cluster_cmd(
'osd',
'rm-pg-upmap-items',
pg)
else:
self.log('No pg_upmap entries; doing nothing')
except CommandFailedError:
self.log('Failed to rm-pg-upmap-items, ignoring')
def force_recovery(self):
"""
Force recovery on some of PGs
"""
backfill = random.random() >= 0.5
j = self.ceph_manager.get_pgids_to_force(backfill)
if j:
try:
if backfill:
self.ceph_manager.raw_cluster_cmd('pg', 'force-backfill', *j)
else:
self.ceph_manager.raw_cluster_cmd('pg', 'force-recovery', *j)
except CommandFailedError:
self.log('Failed to force backfill|recovery, ignoring')
def cancel_force_recovery(self):
"""
Force recovery on some of PGs
"""
backfill = random.random() >= 0.5
j = self.ceph_manager.get_pgids_to_cancel_force(backfill)
if j:
try:
if backfill:
self.ceph_manager.raw_cluster_cmd('pg', 'cancel-force-backfill', *j)
else:
self.ceph_manager.raw_cluster_cmd('pg', 'cancel-force-recovery', *j)
except CommandFailedError:
self.log('Failed to force backfill|recovery, ignoring')
def force_cancel_recovery(self):
"""
Force or cancel forcing recovery
"""
if random.random() >= 0.4:
self.force_recovery()
else:
self.cancel_force_recovery()
def all_up(self):
"""
Make sure all osds are up and not out.
"""
while len(self.dead_osds) > 0:
self.log("reviving osd")
self.revive_osd()
while len(self.out_osds) > 0:
self.log("inning osd")
self.in_osd()
def all_up_in(self):
"""
Make sure all osds are up and fully in.
"""
self.all_up();
for osd in self.live_osds:
self.ceph_manager.raw_cluster_cmd('osd', 'reweight',
str(osd), str(1))
self.ceph_manager.raw_cluster_cmd('osd', 'primary-affinity',
str(osd), str(1))
def do_join(self):
"""
Break out of this Ceph loop
"""
self.stopping = True
self.thread.get()
if self.sighup_delay:
self.log("joining the do_sighup greenlet")
self.sighup_thread.get()
if self.optrack_toggle_delay:
self.log("joining the do_optrack_toggle greenlet")
self.optrack_toggle_thread.join()
if self.dump_ops_enable == "true":
self.log("joining the do_dump_ops greenlet")
self.dump_ops_thread.join()
if self.noscrub_toggle_delay:
self.log("joining the do_noscrub_toggle greenlet")
self.noscrub_toggle_thread.join()
def grow_pool(self):
"""
Increase the size of the pool
"""
pool = self.ceph_manager.get_pool()
if pool is None:
return
self.log("Growing pool %s" % (pool,))
if self.ceph_manager.expand_pool(pool,
self.config.get('pool_grow_by', 10),
self.max_pgs):
self.pools_to_fix_pgp_num.add(pool)
def shrink_pool(self):
"""
Decrease the size of the pool
"""
pool = self.ceph_manager.get_pool()
if pool is None:
return
_ = self.ceph_manager.get_pool_pg_num(pool)
self.log("Shrinking pool %s" % (pool,))
if self.ceph_manager.contract_pool(
pool,
self.config.get('pool_shrink_by', 10),
self.min_pgs):
self.pools_to_fix_pgp_num.add(pool)
def fix_pgp_num(self, pool=None):
"""
Fix number of pgs in pool.
"""
if pool is None:
pool = self.ceph_manager.get_pool()
if not pool:
return
force = False
else:
force = True
self.log("fixing pg num pool %s" % (pool,))
if self.ceph_manager.set_pool_pgpnum(pool, force):
self.pools_to_fix_pgp_num.discard(pool)
def test_pool_min_size(self):
"""
Loop to selectively push PGs below their min_size and test that recovery
still occurs.
"""
self.log("test_pool_min_size")
self.all_up()
self.ceph_manager.wait_for_recovery(
timeout=self.config.get('timeout')
)
minout = int(self.config.get("min_out", 1))
minlive = int(self.config.get("min_live", 2))
mindead = int(self.config.get("min_dead", 1))
self.log("doing min_size thrashing")
self.ceph_manager.wait_for_clean(timeout=60)
assert self.ceph_manager.is_clean(), \
'not clean before minsize thrashing starts'
while not self.stopping:
# look up k and m from all the pools on each loop, in case it
# changes as the cluster runs
k = 0
m = 99
has_pools = False
pools_json = self.ceph_manager.get_osd_dump_json()['pools']
for pool_json in pools_json:
pool = pool_json['pool_name']
has_pools = True
pool_type = pool_json['type'] # 1 for rep, 3 for ec
min_size = pool_json['min_size']
self.log("pool {pool} min_size is {min_size}".format(pool=pool,min_size=min_size))
try:
ec_profile = self.ceph_manager.get_pool_property(pool, 'erasure_code_profile')
if pool_type != PoolType.ERASURE_CODED:
continue
ec_profile = pool_json['erasure_code_profile']
ec_profile_json = self.ceph_manager.raw_cluster_cmd(
'osd',
'erasure-code-profile',
'get',
ec_profile,
'--format=json')
ec_json = json.loads(ec_profile_json)
local_k = int(ec_json['k'])
local_m = int(ec_json['m'])
self.log("pool {pool} local_k={k} local_m={m}".format(pool=pool,
k=local_k, m=local_m))
if local_k > k:
self.log("setting k={local_k} from previous {k}".format(local_k=local_k, k=k))
k = local_k
if local_m < m:
self.log("setting m={local_m} from previous {m}".format(local_m=local_m, m=m))
m = local_m
except CommandFailedError:
self.log("failed to read erasure_code_profile. %s was likely removed", pool)
continue
if has_pools :
self.log("using k={k}, m={m}".format(k=k,m=m))
else:
self.log("No pools yet, waiting")
time.sleep(5)
continue
if minout > len(self.out_osds): # kill OSDs and mark out
self.log("forced to out an osd")
self.kill_osd(mark_out=True)
continue
elif mindead > len(self.dead_osds): # kill OSDs but force timeout
self.log("forced to kill an osd")
self.kill_osd()
continue
else: # make mostly-random choice to kill or revive OSDs
minup = max(minlive, k)
rand_val = random.uniform(0, 1)
self.log("choosing based on number of live OSDs and rand val {rand}".\
format(rand=rand_val))
if len(self.live_osds) > minup+1 and rand_val < 0.5:
# chose to knock out as many OSDs as we can w/out downing PGs
most_killable = min(len(self.live_osds) - minup, m)
self.log("chose to kill {n} OSDs".format(n=most_killable))
for i in range(1, most_killable):
self.kill_osd(mark_out=True)
time.sleep(10)
# try a few times since there might be a concurrent pool
# creation or deletion
with safe_while(
sleep=5, tries=5,
action='check for active or peered') as proceed:
while proceed():
if self.ceph_manager.all_active_or_peered():
break
self.log('not all PGs are active or peered')
else: # chose to revive OSDs, bring up a random fraction of the dead ones
self.log("chose to revive osds")
for i in range(1, int(rand_val * len(self.dead_osds))):
self.revive_osd(i)
# let PGs repair themselves or our next knockout might kill one
self.ceph_manager.wait_for_clean(timeout=self.config.get('timeout'))
# / while not self.stopping
self.all_up_in()
self.ceph_manager.wait_for_recovery(
timeout=self.config.get('timeout')
)
def inject_pause(self, conf_key, duration, check_after, should_be_down):
"""
Pause injection testing. Check for osd being down when finished.
"""
the_one = random.choice(self.live_osds)
self.log("inject_pause on {osd}".format(osd=the_one))
self.log(
"Testing {key} pause injection for duration {duration}".format(
key=conf_key,
duration=duration
))
self.log(
"Checking after {after}, should_be_down={shouldbedown}".format(