/
ceph_objectstore_tool.py
executable file
·1952 lines (1740 loc) · 85.4 KB
/
ceph_objectstore_tool.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 python
from subprocess import call
try:
from subprocess import check_output
except ImportError:
def check_output(*popenargs, **kwargs):
import subprocess
# backported from python 2.7 stdlib
process = subprocess.Popen(
stdout=subprocess.PIPE, *popenargs, **kwargs)
output, unused_err = process.communicate()
retcode = process.poll()
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
error = subprocess.CalledProcessError(retcode, cmd)
error.output = output
raise error
return output
import filecmp
import os
import subprocess
try:
from subprocess import DEVNULL
except ImportError:
subprocess.DEVNULL = open(os.devnull, "w")
import math
import time
import sys
import re
import string
import logging
import json
import tempfile
logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.WARNING)
def wait_for_health():
print "Wait for health_ok...",
tries = 0
while call("{path}/ceph health 2> /dev/null | grep -v 'HEALTH_OK\|HEALTH_WARN' > /dev/null".format(path=CEPH_BIN), shell=True) == 0:
tries += 1
if tries == 150:
raise Exception("Time exceeded to go to health")
time.sleep(1)
print "DONE"
def get_pool_id(name, nullfd):
cmd = "{path}/ceph osd pool stats {pool}".format(pool=name, path=CEPH_BIN).split()
# pool {pool} id # .... grab the 4 field
return check_output(cmd, stderr=nullfd).split()[3]
# return a list of unique PGS given an osd subdirectory
def get_osd_pgs(SUBDIR, ID):
PGS = []
if ID:
endhead = re.compile("{id}.*_head$".format(id=ID))
DIR = os.path.join(SUBDIR, "current")
PGS += [f for f in os.listdir(DIR) if os.path.isdir(os.path.join(DIR, f)) and (ID is None or endhead.match(f))]
PGS = [re.sub("_head", "", p) for p in PGS if "_head" in p]
return PGS
# return a sorted list of unique PGs given a directory
def get_pgs(DIR, ID):
OSDS = [f for f in os.listdir(DIR) if os.path.isdir(os.path.join(DIR, f)) and string.find(f, "osd") == 0]
PGS = []
for d in OSDS:
SUBDIR = os.path.join(DIR, d)
PGS += get_osd_pgs(SUBDIR, ID)
return sorted(set(PGS))
# return a sorted list of PGS a subset of ALLPGS that contain objects with prefix specified
def get_objs(ALLPGS, prefix, DIR, ID):
OSDS = [f for f in os.listdir(DIR) if os.path.isdir(os.path.join(DIR, f)) and string.find(f, "osd") == 0]
PGS = []
for d in OSDS:
DIRL2 = os.path.join(DIR, d)
SUBDIR = os.path.join(DIRL2, "current")
for p in ALLPGS:
PGDIR = p + "_head"
if not os.path.isdir(os.path.join(SUBDIR, PGDIR)):
continue
FINALDIR = os.path.join(SUBDIR, PGDIR)
# See if there are any objects there
if any(f for f in [val for _, _, fl in os.walk(FINALDIR) for val in fl] if f.startswith(prefix)):
PGS += [p]
return sorted(set(PGS))
# return a sorted list of OSDS which have data from a given PG
def get_osds(PG, DIR):
ALLOSDS = [f for f in os.listdir(DIR) if os.path.isdir(os.path.join(DIR, f)) and string.find(f, "osd") == 0]
OSDS = []
for d in ALLOSDS:
DIRL2 = os.path.join(DIR, d)
SUBDIR = os.path.join(DIRL2, "current")
PGDIR = PG + "_head"
if not os.path.isdir(os.path.join(SUBDIR, PGDIR)):
continue
OSDS += [d]
return sorted(OSDS)
def get_lines(filename):
tmpfd = open(filename, "r")
line = True
lines = []
while line:
line = tmpfd.readline().rstrip('\n')
if line:
lines += [line]
tmpfd.close()
os.unlink(filename)
return lines
def cat_file(level, filename):
if level < logging.getLogger().getEffectiveLevel():
return
print "File: " + filename
with open(filename, "r") as f:
while True:
line = f.readline().rstrip('\n')
if not line:
break
print line
print "<EOF>"
def vstart(new, opt=""):
print "vstarting....",
NEW = new and "-n" or ""
call("MON=1 OSD=4 CEPH_PORT=7400 {path}/src/vstart.sh --short -l {new} -d mon osd {opt} > /dev/null 2>&1".format(new=NEW, opt=opt, path=CEPH_ROOT), shell=True)
print "DONE"
def test_failure(cmd, errmsg, tty=False):
if tty:
try:
ttyfd = open("/dev/tty", "rw")
except Exception, e:
logging.info(str(e))
logging.info("SKIP " + cmd)
return 0
TMPFILE = r"/tmp/tmp.{pid}".format(pid=os.getpid())
tmpfd = open(TMPFILE, "w")
logging.debug(cmd)
if tty:
ret = call(cmd, shell=True, stdin=ttyfd, stdout=ttyfd, stderr=tmpfd)
ttyfd.close()
else:
ret = call(cmd, shell=True, stderr=tmpfd)
tmpfd.close()
if ret == 0:
logging.error(cmd)
logging.error("Should have failed, but got exit 0")
return 1
lines = get_lines(TMPFILE)
matched = [ l for l in lines if errmsg in l ]
if any(matched):
logging.info("Correctly failed with message \"" + matched[0] + "\"")
return 0
else:
logging.error("Bad messages to stderr \"" + str(lines) + "\"")
return 1
def get_nspace(num):
if num == 0:
return ""
return "ns{num}".format(num=num)
def verify(DATADIR, POOL, NAME_PREFIX, db):
TMPFILE = r"/tmp/tmp.{pid}".format(pid=os.getpid())
nullfd = open(os.devnull, "w")
ERRORS = 0
for rawnsfile in [f for f in os.listdir(DATADIR) if f.split('-')[1].find(NAME_PREFIX) == 0]:
nsfile = rawnsfile.split("__")[0]
clone = rawnsfile.split("__")[1]
nspace = nsfile.split("-")[0]
file = nsfile.split("-")[1]
# Skip clones
if clone != "head":
continue
path = os.path.join(DATADIR, rawnsfile)
try:
os.unlink(TMPFILE)
except:
pass
cmd = "{path}/rados -p {pool} -N '{nspace}' get {file} {out}".format(pool=POOL, file=file, out=TMPFILE, nspace=nspace, path=CEPH_BIN)
logging.debug(cmd)
call(cmd, shell=True, stdout=nullfd, stderr=nullfd)
cmd = "diff -q {src} {result}".format(src=path, result=TMPFILE)
logging.debug(cmd)
ret = call(cmd, shell=True)
if ret != 0:
logging.error("{file} data not imported properly".format(file=file))
ERRORS += 1
try:
os.unlink(TMPFILE)
except:
pass
for key, val in db[nspace][file]["xattr"].iteritems():
cmd = "{path}/rados -p {pool} -N '{nspace}' getxattr {name} {key}".format(pool=POOL, name=file, key=key, nspace=nspace, path=CEPH_BIN)
logging.debug(cmd)
getval = check_output(cmd, shell=True, stderr=nullfd)
logging.debug("getxattr {key} {val}".format(key=key, val=getval))
if getval != val:
logging.error("getxattr of key {key} returned wrong val: {get} instead of {orig}".format(key=key, get=getval, orig=val))
ERRORS += 1
continue
hdr = db[nspace][file].get("omapheader", "")
cmd = "{path}/rados -p {pool} -N '{nspace}' getomapheader {name} {file}".format(pool=POOL, name=file, nspace=nspace, file=TMPFILE, path=CEPH_BIN)
logging.debug(cmd)
ret = call(cmd, shell=True, stderr=nullfd)
if ret != 0:
logging.error("rados getomapheader returned {ret}".format(ret=ret))
ERRORS += 1
else:
getlines = get_lines(TMPFILE)
assert(len(getlines) == 0 or len(getlines) == 1)
if len(getlines) == 0:
gethdr = ""
else:
gethdr = getlines[0]
logging.debug("header: {hdr}".format(hdr=gethdr))
if gethdr != hdr:
logging.error("getomapheader returned wrong val: {get} instead of {orig}".format(get=gethdr, orig=hdr))
ERRORS += 1
for key, val in db[nspace][file]["omap"].iteritems():
cmd = "{path}/rados -p {pool} -N '{nspace}' getomapval {name} {key} {file}".format(pool=POOL, name=file, key=key, nspace=nspace, file=TMPFILE, path=CEPH_BIN)
logging.debug(cmd)
ret = call(cmd, shell=True, stderr=nullfd)
if ret != 0:
logging.error("getomapval returned {ret}".format(ret=ret))
ERRORS += 1
continue
getlines = get_lines(TMPFILE)
if len(getlines) != 1:
logging.error("Bad data from getomapval {lines}".format(lines=getlines))
ERRORS += 1
continue
getval = getlines[0]
logging.debug("getomapval {key} {val}".format(key=key, val=getval))
if getval != val:
logging.error("getomapval returned wrong val: {get} instead of {orig}".format(get=getval, orig=val))
ERRORS += 1
try:
os.unlink(TMPFILE)
except:
pass
return ERRORS
def check_journal(jsondict):
errors = 0
if 'header' not in jsondict:
logging.error("Key 'header' not in dump-journal")
errors += 1
elif 'max_size' not in jsondict['header']:
logging.error("Key 'max_size' not in dump-journal header")
errors += 1
else:
print "\tJournal max_size = {size}".format(size=jsondict['header']['max_size'])
if 'entries' not in jsondict:
logging.error("Key 'entries' not in dump-journal output")
errors += 1
elif len(jsondict['entries']) == 0:
logging.info("No entries in journal found")
else:
errors += check_journal_entries(jsondict['entries'])
return errors
def check_journal_entries(entries):
errors = 0
for enum in range(len(entries)):
if 'offset' not in entries[enum]:
logging.error("No 'offset' key in entry {e}".format(e=enum))
errors += 1
if 'seq' not in entries[enum]:
logging.error("No 'seq' key in entry {e}".format(e=enum))
errors += 1
if 'transactions' not in entries[enum]:
logging.error("No 'transactions' key in entry {e}".format(e=enum))
errors += 1
elif len(entries[enum]['transactions']) == 0:
logging.error("No transactions found in entry {e}".format(e=enum))
errors += 1
else:
errors += check_entry_transactions(entries[enum], enum)
return errors
def check_entry_transactions(entry, enum):
errors = 0
for tnum in range(len(entry['transactions'])):
if 'trans_num' not in entry['transactions'][tnum]:
logging.error("Key 'trans_num' missing from entry {e} trans {t}".format(e=enum, t=tnum))
errors += 1
elif entry['transactions'][tnum]['trans_num'] != tnum:
ft = entry['transactions'][tnum]['trans_num']
logging.error("Bad trans_num ({ft}) entry {e} trans {t}".format(ft=ft, e=enum, t=tnum))
errors += 1
if 'ops' not in entry['transactions'][tnum]:
logging.error("Key 'ops' missing from entry {e} trans {t}".format(e=enum, t=tnum))
errors += 1
else:
errors += check_transaction_ops(entry['transactions'][tnum]['ops'], enum, tnum)
return errors
def check_transaction_ops(ops, enum, tnum):
if len(ops) is 0:
logging.warning("No ops found in entry {e} trans {t}".format(e=enum, t=tnum))
errors = 0
for onum in range(len(ops)):
if 'op_num' not in ops[onum]:
logging.error("Key 'op_num' missing from entry {e} trans {t} op {o}".format(e=enum, t=tnum, o=onum))
errors += 1
elif ops[onum]['op_num'] != onum:
fo = ops[onum]['op_num']
logging.error("Bad op_num ({fo}) from entry {e} trans {t} op {o}".format(fo=fo, e=enum, t=tnum, o=onum))
errors += 1
if 'op_name' not in ops[onum]:
logging.error("Key 'op_name' missing from entry {e} trans {t} op {o}".format(e=enum, t=tnum, o=onum))
errors += 1
return errors
def test_dump_journal(CFSD_PREFIX, osds):
ERRORS = 0
pid = os.getpid()
TMPFILE = r"/tmp/tmp.{pid}".format(pid=pid)
for osd in osds:
# Test --op dump-journal by loading json
cmd = (CFSD_PREFIX + "--op dump-journal --format json").format(osd=osd)
logging.debug(cmd)
tmpfd = open(TMPFILE, "w")
ret = call(cmd, shell=True, stdout=tmpfd)
if ret != 0:
logging.error("Bad exit status {ret} from {cmd}".format(ret=ret, cmd=cmd))
ERRORS += 1
continue
tmpfd.close()
tmpfd = open(TMPFILE, "r")
jsondict = json.load(tmpfd)
tmpfd.close()
os.unlink(TMPFILE)
journal_errors = check_journal(jsondict)
if journal_errors is not 0:
logging.error(jsondict)
ERRORS += journal_errors
return ERRORS
CEPH_BUILD_DIR = os.environ.get('CEPH_BUILD_DIR')
CEPH_BIN = os.environ.get('CEPH_BIN')
CEPH_ROOT = os.environ.get('CEPH_ROOT')
if not CEPH_BUILD_DIR:
CEPH_BUILD_DIR=os.getcwd()
os.putenv('CEPH_BUILD_DIR', CEPH_BUILD_DIR)
CEPH_BIN=CEPH_BUILD_DIR
os.putenv('CEPH_BIN', CEPH_BIN)
CEPH_ROOT=os.path.dirname(CEPH_BUILD_DIR)
os.putenv('CEPH_ROOT', CEPH_ROOT)
CEPH_LIB=os.path.join(CEPH_BIN, '.libs')
os.putenv('CEPH_LIB', CEPH_LIB)
CEPH_DIR = CEPH_BUILD_DIR + "/ceph_objectstore_tool_dir"
CEPH_CONF = os.path.join(CEPH_DIR, 'ceph.conf')
def kill_daemons():
call("{path}/init-ceph -c {conf} stop osd mon > /dev/null 2>&1".format(conf=CEPH_CONF, path=CEPH_BIN), shell=True)
def check_data(DATADIR, TMPFILE, OSDDIR, SPLIT_NAME):
repcount = 0
ERRORS = 0
for rawnsfile in [f for f in os.listdir(DATADIR) if f.split('-')[1].find(SPLIT_NAME) == 0]:
nsfile = rawnsfile.split("__")[0]
clone = rawnsfile.split("__")[1]
nspace = nsfile.split("-")[0]
file = nsfile.split("-")[1] + "__" + clone
# Skip clones
if clone != "head":
continue
path = os.path.join(DATADIR, rawnsfile)
tmpfd = open(TMPFILE, "w")
cmd = "find {dir} -name '{file}_*_{nspace}_*'".format(dir=OSDDIR, file=file, nspace=nspace)
logging.debug(cmd)
ret = call(cmd, shell=True, stdout=tmpfd)
if ret:
logging.critical("INTERNAL ERROR")
return 1
tmpfd.close()
obj_locs = get_lines(TMPFILE)
if len(obj_locs) == 0:
logging.error("Can't find imported object {name}".format(name=file))
ERRORS += 1
for obj_loc in obj_locs:
# For btrfs skip snap_* dirs
if re.search("/snap_[0-9]*/", obj_loc) is not None:
continue
repcount += 1
cmd = "diff -q {src} {obj_loc}".format(src=path, obj_loc=obj_loc)
logging.debug(cmd)
ret = call(cmd, shell=True)
if ret != 0:
logging.error("{file} data not imported properly into {obj}".format(file=file, obj=obj_loc))
ERRORS += 1
return ERRORS, repcount
def set_osd_weight(CFSD_PREFIX, osd_ids, osd_path, weight):
# change the weight of osd.0 to math.pi in the newest osdmap of given osd
osdmap_file = tempfile.NamedTemporaryFile(delete=True)
cmd = (CFSD_PREFIX + "--op get-osdmap --file {osdmap_file}").format(osd=osd_path,
osdmap_file=osdmap_file.name)
output = check_output(cmd, shell=True)
epoch = int(re.findall('#(\d+)', output)[0])
new_crush_file = tempfile.NamedTemporaryFile(delete=True)
old_crush_file = tempfile.NamedTemporaryFile(delete=True)
ret = call("{path}/osdmaptool --export-crush {crush_file} {osdmap_file}".format(osdmap_file=osdmap_file.name,
crush_file=old_crush_file.name, path=CEPH_BIN),
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
shell=True)
assert(ret == 0)
for osd_id in osd_ids:
cmd = "{path}/crushtool -i {crush_file} --reweight-item osd.{osd} {weight} -o {new_crush_file}".format(osd=osd_id,
crush_file=old_crush_file.name,
weight=weight,
new_crush_file=new_crush_file.name, path=CEPH_BIN)
ret = call(cmd, stdout=subprocess.DEVNULL, shell=True)
assert(ret == 0)
old_crush_file, new_crush_file = new_crush_file, old_crush_file
# change them back, since we don't need to preapre for another round
old_crush_file, new_crush_file = new_crush_file, old_crush_file
old_crush_file.close()
ret = call("{path}/osdmaptool --import-crush {crush_file} {osdmap_file}".format(osdmap_file=osdmap_file.name,
crush_file=new_crush_file.name, path=CEPH_BIN),
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
shell=True)
assert(ret == 0)
# Minimum test of --dry-run by using it, but not checking anything
cmd = CFSD_PREFIX + "--op set-osdmap --file {osdmap_file} --epoch {epoch} --force --dry-run"
cmd = cmd.format(osd=osd_path, osdmap_file=osdmap_file.name, epoch=epoch)
ret = call(cmd, stdout=subprocess.DEVNULL, shell=True)
assert(ret == 0)
# osdmaptool increases the epoch of the changed osdmap, so we need to force the tool
# to use use a different epoch than the one in osdmap
cmd = CFSD_PREFIX + "--op set-osdmap --file {osdmap_file} --epoch {epoch} --force"
cmd = cmd.format(osd=osd_path, osdmap_file=osdmap_file.name, epoch=epoch)
ret = call(cmd, stdout=subprocess.DEVNULL, shell=True)
return ret == 0
def get_osd_weights(CFSD_PREFIX, osd_ids, osd_path):
osdmap_file = tempfile.NamedTemporaryFile(delete=True)
cmd = (CFSD_PREFIX + "--op get-osdmap --file {osdmap_file}").format(osd=osd_path,
osdmap_file=osdmap_file.name)
ret = call(cmd, stdout=subprocess.DEVNULL, shell=True)
if ret != 0:
return None
# we have to read the weights from the crush map, even we can query the weights using
# osdmaptool, but please keep in mind, they are different:
# item weights in crush map versus weight associated with each osd in osdmap
crush_file = tempfile.NamedTemporaryFile(delete=True)
ret = call("{path}/osdmaptool --export-crush {crush_file} {osdmap_file}".format(osdmap_file=osdmap_file.name,
crush_file=crush_file.name, path=CEPH_BIN),
stdout=subprocess.DEVNULL,
shell=True)
assert(ret == 0)
output = check_output("{path}/crushtool --tree -i {crush_file} | tail -n {num_osd}".format(crush_file=crush_file.name,
num_osd=len(osd_ids), path=CEPH_BIN),
stderr=subprocess.DEVNULL,
shell=True)
weights = []
for line in output.strip().split('\n'):
osd_id, weight, osd_name = re.split('\s+', line)
weights.append(float(weight))
return weights
def test_get_set_osdmap(CFSD_PREFIX, osd_ids, osd_paths):
print "Testing get-osdmap and set-osdmap"
errors = 0
kill_daemons()
weight = 1 / math.e # just some magic number in [0, 1]
changed = []
for osd_path in osd_paths:
if set_osd_weight(CFSD_PREFIX, osd_ids, osd_path, weight):
changed.append(osd_path)
else:
logging.warning("Failed to change the weights: {0}".format(osd_path))
# i am pissed off if none of the store gets changed
if not changed:
errors += 1
for osd_path in changed:
weights = get_osd_weights(CFSD_PREFIX, osd_ids, osd_path)
if not weights:
errors += 1
continue
if any(abs(w - weight) > 1e-5 for w in weights):
logging.warning("Weight is not changed: {0} != {1}".format(weights, weight))
errors += 1
return errors
def test_get_set_inc_osdmap(CFSD_PREFIX, osd_path):
# incrementals are not used unless we need to build an MOSDMap to update
# OSD's peers, so an obvious way to test it is simply overwrite an epoch
# with a different copy, and read it back to see if it matches.
kill_daemons()
file_e2 = tempfile.NamedTemporaryFile(delete=True)
cmd = (CFSD_PREFIX + "--op get-inc-osdmap --file {file}").format(osd=osd_path,
file=file_e2.name)
output = check_output(cmd, shell=True)
epoch = int(re.findall('#(\d+)', output)[0])
# backup e1 incremental before overwriting it
epoch -= 1
file_e1_backup = tempfile.NamedTemporaryFile(delete=True)
cmd = CFSD_PREFIX + "--op get-inc-osdmap --epoch {epoch} --file {file}"
ret = call(cmd.format(osd=osd_path, epoch=epoch, file=file_e1_backup.name), shell=True)
if ret: return 1
# overwrite e1 with e2
cmd = CFSD_PREFIX + "--op set-inc-osdmap --force --epoch {epoch} --file {file}"
ret = call(cmd.format(osd=osd_path, epoch=epoch, file=file_e2.name), shell=True)
if ret: return 1
# Use dry-run to set back to e1 which shouldn't happen
cmd = CFSD_PREFIX + "--op set-inc-osdmap --dry-run --epoch {epoch} --file {file}"
ret = call(cmd.format(osd=osd_path, epoch=epoch, file=file_e1_backup.name), shell=True)
if ret: return 1
# read from e1
file_e1_read = tempfile.NamedTemporaryFile(delete=True)
cmd = CFSD_PREFIX + "--op get-inc-osdmap --epoch {epoch} --file {file}"
ret = call(cmd.format(osd=osd_path, epoch=epoch, file=file_e1_read.name), shell=True)
if ret: return 1
errors = 0
try:
if not filecmp.cmp(file_e2.name, file_e1_read.name, shallow=False):
logging.error("{{get,set}}-inc-osdmap mismatch {0} != {1}".format(file_e2.name, file_e1_read.name))
errors += 1
finally:
# revert the change with file_e1_backup
cmd = CFSD_PREFIX + "--op set-inc-osdmap --epoch {epoch} --file {file}"
ret = call(cmd.format(osd=osd_path, epoch=epoch, file=file_e1_backup.name), shell=True)
if ret:
logging.error("Failed to revert the changed inc-osdmap")
errors += 1
return errors
def test_removeall(CFSD_PREFIX, db, OBJREPPGS, REP_POOL, CEPH_BIN, OSDDIR):
# Test removeall
errors=0
print "Test removeall"
kill_daemons()
for nspace in db.keys():
for basename in db[nspace].keys():
JSON = db[nspace][basename]['json']
for pg in OBJREPPGS:
OSDS = get_osds(pg, OSDDIR)
for osd in OSDS:
DIR = os.path.join(OSDDIR, os.path.join(osd, os.path.join("current", "{pg}_head".format(pg=pg))))
fnames = [f for f in os.listdir(DIR) if os.path.isfile(os.path.join(DIR, f))
and f.split("_")[0] == basename and f.split("_")[4] == nspace]
if not fnames:
continue
cmd = (CFSD_PREFIX + " --force --dry-run '{json}' remove").format(osd=osd, json=JSON)
logging.debug(cmd)
ret = call(cmd, shell=True)
if ret != 0:
logging.error("remove with --force failed for {json}".format(json=JSON))
errors += 1
cmd = (CFSD_PREFIX + " --dry-run '{json}' removeall").format(osd=osd, json=JSON)
logging.debug(cmd)
ret = call(cmd, shell=True)
if ret != 0:
logging.error("removeall failed for {json}".format(json=JSON))
errors += 1
cmd = (CFSD_PREFIX + " '{json}' removeall").format(osd=osd, json=JSON)
logging.debug(cmd)
ret = call(cmd, shell=True)
if ret != 0:
logging.error("removeall failed for {json}".format(json=JSON))
errors += 1
vstart(new=False)
wait_for_health()
cmd = "{path}/rados -p {pool} rmsnap snap1".format(pool=REP_POOL, path=CEPH_BIN)
logging.debug(cmd)
ret = call(cmd, shell=True)
if ret != 0:
logging.error("rados rmsnap failed")
errors += 1
time.sleep(2)
wait_for_health()
return errors
def main(argv):
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
if len(argv) > 1 and argv[1] == "debug":
nullfd = sys.stdout
else:
nullfd = open(os.devnull, "w")
call("rm -fr {dir}; mkdir {dir}".format(dir=CEPH_DIR), shell=True)
os.environ["CEPH_DIR"] = CEPH_DIR
OSDDIR = os.path.join(CEPH_DIR, "dev")
REP_POOL = "rep_pool"
REP_NAME = "REPobject"
EC_POOL = "ec_pool"
EC_NAME = "ECobject"
if len(argv) > 0 and argv[0] == 'large':
PG_COUNT = 12
NUM_REP_OBJECTS = 800
NUM_EC_OBJECTS = 12
NUM_NSPACES = 4
# Larger data sets for first object per namespace
DATALINECOUNT = 50000
# Number of objects to do xattr/omap testing on
ATTR_OBJS = 10
else:
PG_COUNT = 4
NUM_REP_OBJECTS = 2
NUM_EC_OBJECTS = 2
NUM_NSPACES = 2
# Larger data sets for first object per namespace
DATALINECOUNT = 10
# Number of objects to do xattr/omap testing on
ATTR_OBJS = 2
ERRORS = 0
pid = os.getpid()
TESTDIR = "/tmp/test.{pid}".format(pid=pid)
DATADIR = "/tmp/data.{pid}".format(pid=pid)
CFSD_PREFIX = CEPH_BIN + "/ceph-objectstore-tool --data-path " + OSDDIR + "/{osd} "
PROFNAME = "testecprofile"
os.environ['CEPH_CONF'] = CEPH_CONF
vstart(new=True)
wait_for_health()
cmd = "{path}/ceph osd pool create {pool} {pg} {pg} replicated".format(pool=REP_POOL, pg=PG_COUNT, path=CEPH_BIN)
logging.debug(cmd)
call(cmd, shell=True, stdout=nullfd, stderr=nullfd)
REPID = get_pool_id(REP_POOL, nullfd)
print "Created Replicated pool #{repid}".format(repid=REPID)
cmd = "{path}/ceph osd erasure-code-profile set {prof} ruleset-failure-domain=osd".format(prof=PROFNAME, path=CEPH_BIN)
logging.debug(cmd)
call(cmd, shell=True, stdout=nullfd, stderr=nullfd)
cmd = "{path}/ceph osd erasure-code-profile get {prof}".format(prof=PROFNAME, path=CEPH_BIN)
logging.debug(cmd)
call(cmd, shell=True, stdout=nullfd, stderr=nullfd)
cmd = "{path}/ceph osd pool create {pool} {pg} {pg} erasure {prof}".format(pool=EC_POOL, prof=PROFNAME, pg=PG_COUNT, path=CEPH_BIN)
logging.debug(cmd)
call(cmd, shell=True, stdout=nullfd, stderr=nullfd)
ECID = get_pool_id(EC_POOL, nullfd)
print "Created Erasure coded pool #{ecid}".format(ecid=ECID)
print "Creating {objs} objects in replicated pool".format(objs=(NUM_REP_OBJECTS*NUM_NSPACES))
cmd = "mkdir -p {datadir}".format(datadir=DATADIR)
logging.debug(cmd)
call(cmd, shell=True)
db = {}
objects = range(1, NUM_REP_OBJECTS + 1)
nspaces = range(NUM_NSPACES)
for n in nspaces:
nspace = get_nspace(n)
db[nspace] = {}
for i in objects:
NAME = REP_NAME + "{num}".format(num=i)
LNAME = nspace + "-" + NAME
DDNAME = os.path.join(DATADIR, LNAME)
DDNAME += "__head"
cmd = "rm -f " + DDNAME
logging.debug(cmd)
call(cmd, shell=True)
if i == 1:
dataline = range(DATALINECOUNT)
else:
dataline = range(1)
fd = open(DDNAME, "w")
data = "This is the replicated data for " + LNAME + "\n"
for _ in dataline:
fd.write(data)
fd.close()
cmd = "{path}/rados -p {pool} -N '{nspace}' put {name} {ddname}".format(pool=REP_POOL, name=NAME, ddname=DDNAME, nspace=nspace, path=CEPH_BIN)
logging.debug(cmd)
ret = call(cmd, shell=True, stderr=nullfd)
if ret != 0:
logging.critical("Rados put command failed with {ret}".format(ret=ret))
return 1
db[nspace][NAME] = {}
if i < ATTR_OBJS + 1:
keys = range(i)
else:
keys = range(0)
db[nspace][NAME]["xattr"] = {}
for k in keys:
if k == 0:
continue
mykey = "key{i}-{k}".format(i=i, k=k)
myval = "val{i}-{k}".format(i=i, k=k)
cmd = "{path}/rados -p {pool} -N '{nspace}' setxattr {name} {key} {val}".format(pool=REP_POOL, name=NAME, key=mykey, val=myval, nspace=nspace, path=CEPH_BIN)
logging.debug(cmd)
ret = call(cmd, shell=True)
if ret != 0:
logging.error("setxattr failed with {ret}".format(ret=ret))
ERRORS += 1
db[nspace][NAME]["xattr"][mykey] = myval
# Create omap header in all objects but REPobject1
if i < ATTR_OBJS + 1 and i != 1:
myhdr = "hdr{i}".format(i=i)
cmd = "{path}/rados -p {pool} -N '{nspace}' setomapheader {name} {hdr}".format(pool=REP_POOL, name=NAME, hdr=myhdr, nspace=nspace, path=CEPH_BIN)
logging.debug(cmd)
ret = call(cmd, shell=True)
if ret != 0:
logging.critical("setomapheader failed with {ret}".format(ret=ret))
ERRORS += 1
db[nspace][NAME]["omapheader"] = myhdr
db[nspace][NAME]["omap"] = {}
for k in keys:
if k == 0:
continue
mykey = "okey{i}-{k}".format(i=i, k=k)
myval = "oval{i}-{k}".format(i=i, k=k)
cmd = "{path}/rados -p {pool} -N '{nspace}' setomapval {name} {key} {val}".format(pool=REP_POOL, name=NAME, key=mykey, val=myval, nspace=nspace, path=CEPH_BIN)
logging.debug(cmd)
ret = call(cmd, shell=True)
if ret != 0:
logging.critical("setomapval failed with {ret}".format(ret=ret))
db[nspace][NAME]["omap"][mykey] = myval
# Create some clones
cmd = "{path}/rados -p {pool} mksnap snap1".format(pool=REP_POOL, path=CEPH_BIN)
logging.debug(cmd)
call(cmd, shell=True)
objects = range(1, NUM_REP_OBJECTS + 1)
nspaces = range(NUM_NSPACES)
for n in nspaces:
nspace = get_nspace(n)
for i in objects:
NAME = REP_NAME + "{num}".format(num=i)
LNAME = nspace + "-" + NAME
DDNAME = os.path.join(DATADIR, LNAME)
# First clone
CLONENAME = DDNAME + "__1"
DDNAME += "__head"
cmd = "mv -f " + DDNAME + " " + CLONENAME
logging.debug(cmd)
call(cmd, shell=True)
if i == 1:
dataline = range(DATALINECOUNT)
else:
dataline = range(1)
fd = open(DDNAME, "w")
data = "This is the replicated data after a snapshot for " + LNAME + "\n"
for _ in dataline:
fd.write(data)
fd.close()
cmd = "{path}/rados -p {pool} -N '{nspace}' put {name} {ddname}".format(pool=REP_POOL, name=NAME, ddname=DDNAME, nspace=nspace, path=CEPH_BIN)
logging.debug(cmd)
ret = call(cmd, shell=True, stderr=nullfd)
if ret != 0:
logging.critical("Rados put command failed with {ret}".format(ret=ret))
return 1
print "Creating {objs} objects in erasure coded pool".format(objs=(NUM_EC_OBJECTS*NUM_NSPACES))
objects = range(1, NUM_EC_OBJECTS + 1)
nspaces = range(NUM_NSPACES)
for n in nspaces:
nspace = get_nspace(n)
for i in objects:
NAME = EC_NAME + "{num}".format(num=i)
LNAME = nspace + "-" + NAME
DDNAME = os.path.join(DATADIR, LNAME)
DDNAME += "__head"
cmd = "rm -f " + DDNAME
logging.debug(cmd)
call(cmd, shell=True)
if i == 1:
dataline = range(DATALINECOUNT)
else:
dataline = range(1)
fd = open(DDNAME, "w")
data = "This is the erasure coded data for " + LNAME + "\n"
for j in dataline:
fd.write(data)
fd.close()
cmd = "{path}/rados -p {pool} -N '{nspace}' put {name} {ddname}".format(pool=EC_POOL, name=NAME, ddname=DDNAME, nspace=nspace, path=CEPH_BIN)
logging.debug(cmd)
ret = call(cmd, shell=True, stderr=nullfd)
if ret != 0:
logging.critical("Erasure coded pool creation failed with {ret}".format(ret=ret))
return 1
db[nspace][NAME] = {}
db[nspace][NAME]["xattr"] = {}
if i < ATTR_OBJS + 1:
keys = range(i)
else:
keys = range(0)
for k in keys:
if k == 0:
continue
mykey = "key{i}-{k}".format(i=i, k=k)
myval = "val{i}-{k}".format(i=i, k=k)
cmd = "{path}/rados -p {pool} -N '{nspace}' setxattr {name} {key} {val}".format(pool=EC_POOL, name=NAME, key=mykey, val=myval, nspace=nspace, path=CEPH_BIN)
logging.debug(cmd)
ret = call(cmd, shell=True)
if ret != 0:
logging.error("setxattr failed with {ret}".format(ret=ret))
ERRORS += 1
db[nspace][NAME]["xattr"][mykey] = myval
# Omap isn't supported in EC pools
db[nspace][NAME]["omap"] = {}
logging.debug(db)
kill_daemons()
if ERRORS:
logging.critical("Unable to set up test")
return 1
ALLREPPGS = get_pgs(OSDDIR, REPID)
logging.debug(ALLREPPGS)
ALLECPGS = get_pgs(OSDDIR, ECID)
logging.debug(ALLECPGS)
OBJREPPGS = get_objs(ALLREPPGS, REP_NAME, OSDDIR, REPID)
logging.debug(OBJREPPGS)
OBJECPGS = get_objs(ALLECPGS, EC_NAME, OSDDIR, ECID)
logging.debug(OBJECPGS)
ONEPG = ALLREPPGS[0]
logging.debug(ONEPG)
osds = get_osds(ONEPG, OSDDIR)
ONEOSD = osds[0]
logging.debug(ONEOSD)
print "Test invalid parameters"
# On export can't use stdout to a terminal
cmd = (CFSD_PREFIX + "--op export --pgid {pg}").format(osd=ONEOSD, pg=ONEPG)
ERRORS += test_failure(cmd, "stdout is a tty and no --file filename specified", tty=True)
# On export can't use stdout to a terminal
cmd = (CFSD_PREFIX + "--op export --pgid {pg} --file -").format(osd=ONEOSD, pg=ONEPG)
ERRORS += test_failure(cmd, "stdout is a tty and no --file filename specified", tty=True)
# Prep a valid ec export file for import failure tests
ONEECPG = ALLECPGS[0]
osds = get_osds(ONEECPG, OSDDIR)
ONEECOSD = osds[0]
OTHERFILE = "/tmp/foo.{pid}".format(pid=pid)
cmd = (CFSD_PREFIX + "--op export --pgid {pg} --file {file}").format(osd=ONEECOSD, pg=ONEECPG, file=OTHERFILE)
logging.debug(cmd)
call(cmd, shell=True, stdout=nullfd, stderr=nullfd)
# On import can't specify a different shard
BADPG = ONEECPG.split('s')[0] + "s10"
cmd = (CFSD_PREFIX + "--op import --pgid {pg} --file {file}").format(osd=ONEECOSD, pg=BADPG, file=OTHERFILE)
ERRORS += test_failure(cmd, "Can't specify a different shard, must be")
os.unlink(OTHERFILE)
# Prep a valid export file for import failure tests
OTHERFILE = "/tmp/foo.{pid}".format(pid=pid)
cmd = (CFSD_PREFIX + "--op export --pgid {pg} --file {file}").format(osd=ONEOSD, pg=ONEPG, file=OTHERFILE)
logging.debug(cmd)
call(cmd, shell=True, stdout=nullfd, stderr=nullfd)
# On import can't specify a PG with a non-existent pool
cmd = (CFSD_PREFIX + "--op import --pgid {pg} --file {file}").format(osd=ONEOSD, pg="10.0", file=OTHERFILE)
ERRORS += test_failure(cmd, "Can't specify a different pgid pool, must be")
# On import can't specify shard for a replicated export
cmd = (CFSD_PREFIX + "--op import --pgid {pg}s0 --file {file}").format(osd=ONEOSD, pg=ONEPG, file=OTHERFILE)
ERRORS += test_failure(cmd, "Can't specify a sharded pgid with a non-sharded export")
# On import can't specify a PG with a bad seed
TMPPG="{pool}.80".format(pool=REPID)
cmd = (CFSD_PREFIX + "--op import --pgid {pg} --file {file}").format(osd=ONEOSD, pg=TMPPG, file=OTHERFILE)
ERRORS += test_failure(cmd, "Illegal pgid, the seed is larger than current pg_num")
os.unlink(OTHERFILE)
cmd = (CFSD_PREFIX + "--op import --file {FOO}").format(osd=ONEOSD, FOO=OTHERFILE)
ERRORS += test_failure(cmd, "file: {FOO}: No such file or directory".format(FOO=OTHERFILE))
cmd = "{path}/ceph-objectstore-tool --data-path BAD_DATA_PATH --op list".format(osd=ONEOSD, path=CEPH_BIN)
ERRORS += test_failure(cmd, "data-path: BAD_DATA_PATH: No such file or directory")
cmd = "{path}/ceph-objectstore-tool --journal-path BAD_JOURNAL_PATH --op dump-journal".format(path=CEPH_BIN)
ERRORS += test_failure(cmd, "journal-path: BAD_JOURNAL_PATH: (2) No such file or directory")
# On import can't use stdin from a terminal
cmd = (CFSD_PREFIX + "--op import --pgid {pg}").format(osd=ONEOSD, pg=ONEPG)
ERRORS += test_failure(cmd, "stdin is a tty and no --file filename specified", tty=True)
# On import can't use stdin from a terminal
cmd = (CFSD_PREFIX + "--op import --pgid {pg} --file -").format(osd=ONEOSD, pg=ONEPG)
ERRORS += test_failure(cmd, "stdin is a tty and no --file filename specified", tty=True)
# Specify a bad --type
os.mkdir(OSDDIR + "/fakeosd")
cmd = ("{path}/ceph-objectstore-tool --data-path " + OSDDIR + "/{osd} --type foobar --op list --pgid {pg}").format(osd="fakeosd", pg=ONEPG, path=CEPH_BIN)
ERRORS += test_failure(cmd, "Unable to create store of type foobar")
# Don't specify a data-path
cmd = "{path}/ceph-objectstore-tool --type memstore --op list --pgid {pg}".format(dir=OSDDIR, osd=ONEOSD, pg=ONEPG, path=CEPH_BIN)
ERRORS += test_failure(cmd, "Must provide --data-path")
cmd = (CFSD_PREFIX + "--op remove").format(osd=ONEOSD)
ERRORS += test_failure(cmd, "Must provide pgid")
# Don't secify a --op nor object command
cmd = CFSD_PREFIX.format(osd=ONEOSD)
ERRORS += test_failure(cmd, "Must provide --op or object command...")
# Specify a bad --op command
cmd = (CFSD_PREFIX + "--op oops").format(osd=ONEOSD)
ERRORS += test_failure(cmd, "Must provide --op (info, log, remove, mkfs, fsck, export, import, list, fix-lost, list-pgs, rm-past-intervals, dump-journal, dump-super, meta-list, get-osdmap, set-osdmap, get-inc-osdmap, set-inc-osdmap, mark-complete)")
# Provide just the object param not a command
cmd = (CFSD_PREFIX + "object").format(osd=ONEOSD)
ERRORS += test_failure(cmd, "Invalid syntax, missing command")
# Provide an object name that doesn't exist
cmd = (CFSD_PREFIX + "NON_OBJECT get-bytes").format(osd=ONEOSD)
ERRORS += test_failure(cmd, "No object id 'NON_OBJECT' found")
# Provide an invalid object command
cmd = (CFSD_PREFIX + "--pgid {pg} '' notacommand").format(osd=ONEOSD, pg=ONEPG)
ERRORS += test_failure(cmd, "Unknown object command 'notacommand'")
cmd = (CFSD_PREFIX + "foo list-omap").format(osd=ONEOSD, pg=ONEPG)
ERRORS += test_failure(cmd, "No object id 'foo' found or invalid JSON specified")
cmd = (CFSD_PREFIX + "'{{\"oid\":\"obj4\",\"key\":\"\",\"snapid\":-1,\"hash\":2826278768,\"max\":0,\"pool\":1,\"namespace\":\"\"}}' list-omap").format(osd=ONEOSD, pg=ONEPG)
ERRORS += test_failure(cmd, "Without --pgid the object '{\"oid\":\"obj4\",\"key\":\"\",\"snapid\":-1,\"hash\":2826278768,\"max\":0,\"pool\":1,\"namespace\":\"\"}' must be a JSON array")
cmd = (CFSD_PREFIX + "'[]' list-omap").format(osd=ONEOSD, pg=ONEPG)
ERRORS += test_failure(cmd, "Object '[]' must be a JSON array with 2 elements")
cmd = (CFSD_PREFIX + "'[\"1.0\"]' list-omap").format(osd=ONEOSD, pg=ONEPG)
ERRORS += test_failure(cmd, "Object '[\"1.0\"]' must be a JSON array with 2 elements")