-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathceph-disk
executable file
·4033 lines (3534 loc) · 119 KB
/
ceph-disk
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
#
# Copyright (C) 2015 Red Hat <[email protected]>
# Copyright (C) 2014 Inktank <[email protected]>
# Copyright (C) 2014 Cloudwatt <[email protected]>
# Copyright (C) 2014 Catalyst.net Ltd
#
# Author: Loic Dachary <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Library Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Library Public License for more details.
#
import argparse
import errno
import fcntl
import json
import logging
import os
import platform
import re
import subprocess
import stat
import sys
import tempfile
import uuid
import time
import shlex
import pwd
import grp
"""
Prepare:
- create GPT partition
- mark the partition with the ceph type uuid
- create a file system
- mark the fs as ready for ceph consumption
- entire data disk is used (one big partition)
- a new partition is added to the journal disk (so it can be easily shared)
- triggered by administrator or ceph-deploy, e.g. 'ceph-disk <data disk> [journal disk]
Activate:
- if encrypted, map the dmcrypt volume
- mount the volume in a temp location
- allocate an osd id (if needed)
- if deactived, no-op (to activate with --reactivate flag)
- remount in the correct location /var/lib/ceph/osd/$cluster-$id
- remove the deactive flag (with --reactivate flag)
- start ceph-osd
- triggered by udev when it sees the OSD gpt partition type
- triggered by admin 'ceph-disk activate <path>'
- triggered on ceph service startup with 'ceph-disk activate-all'
Deactivate:
- check partition type (support dmcrypt, mpath, normal)
- stop ceph-osd service if needed (make osd out with option --mark-out)
- remove 'ready', 'active', and INIT-specific files
- create deactive flag
- umount device and remove mount point
- if the partition type is dmcrypt, remove the data dmcrypt map.
Destroy:
- check partition type (support dmcrypt, mpath, normal)
- remove OSD from CRUSH map
- remove OSD cephx key
- deallocate OSD ID
- if the partition type is dmcrypt, remove the journal dmcrypt map.
- destroy data (with --zap option)
We rely on /dev/disk/by-partuuid to find partitions by their UUID;
this is what the journal symlink inside the osd data volume normally
points to.
activate-all relies on /dev/disk/by-parttype-uuid/$typeuuid.$uuid to
find all partitions. We install special udev rules to create these
links.
udev triggers 'ceph-disk activate <dev>' or 'ceph-disk
activate-journal <dev>' based on the partition type.
On old distros (e.g., RHEL6), the blkid installed does not recognized
GPT partition metadata and the /dev/disk/by-partuuid etc. links aren't
present. We have a horrible hack in the form of ceph-disk-udev that
parses gparted output to create the symlinks above and triggers the
'ceph-disk activate' etc commands that udev normally would do if it
knew the GPT partition type.
"""
CEPH_OSD_ONDISK_MAGIC = 'ceph osd volume v026'
JOURNAL_UUID = '45b0969e-9b03-4f30-b4c6-b4b80ceff106'
MPATH_JOURNAL_UUID = '45b0969e-8ae0-4982-bf9d-5a8d867af560'
DMCRYPT_JOURNAL_UUID = '45b0969e-9b03-4f30-b4c6-5ec00ceff106'
DMCRYPT_LUKS_JOURNAL_UUID = '45b0969e-9b03-4f30-b4c6-35865ceff106'
OSD_UUID = '4fbd7e29-9d25-41b8-afd0-062c0ceff05d'
MPATH_OSD_UUID = '4fbd7e29-8ae0-4982-bf9d-5a8d867af560'
DMCRYPT_OSD_UUID = '4fbd7e29-9d25-41b8-afd0-5ec00ceff05d'
DMCRYPT_LUKS_OSD_UUID = '4fbd7e29-9d25-41b8-afd0-35865ceff05d'
TOBE_UUID = '89c57f98-2fe5-4dc0-89c1-f3ad0ceff2be'
MPATH_TOBE_UUID = '89c57f98-8ae0-4982-bf9d-5a8d867af560'
DMCRYPT_TOBE_UUID = '89c57f98-2fe5-4dc0-89c1-5ec00ceff2be'
DMCRYPT_JOURNAL_TOBE_UUID = '89c57f98-2fe5-4dc0-89c1-35865ceff2be'
DEFAULT_FS_TYPE = 'xfs'
SYSFS = '/sys'
"""
OSD STATUS Definition
"""
OSD_STATUS_OUT_DOWN = 0
OSD_STATUS_OUT_UP = 1
OSD_STATUS_IN_DOWN = 2
OSD_STATUS_IN_UP = 3
MOUNT_OPTIONS = dict(
btrfs='noatime,user_subvol_rm_allowed',
# user_xattr is default ever since linux 2.6.39 / 3.0, but we'll
# delay a moment before removing it fully because we did have some
# issues with ext4 before the xatts-in-leveldb work, and it seemed
# that user_xattr helped
ext4='noatime,user_xattr',
xfs='noatime,inode64',
)
MKFS_ARGS = dict(
btrfs=[
# btrfs requires -f, for the same reason as xfs (see comment below)
'-f',
'-m', 'single',
'-l', '32768',
'-n', '32768',
],
xfs=[
# xfs insists on not overwriting previous fs; even if we wipe
# partition table, we often recreate it exactly the same way,
# so we'll see ghosts of filesystems past
'-f',
'-i', 'size=2048',
],
)
INIT_SYSTEMS = [
'upstart',
'sysvinit',
'systemd',
'auto',
'none',
]
STATEDIR = '/var/lib/ceph'
SYSCONFDIR = '/etc/ceph'
# only warn once about some things
warned_about = {}
# Nuke the TERM variable to avoid confusing any subprocesses we call.
# For example, libreadline will print weird control sequences for some
# TERM values.
if 'TERM' in os.environ:
del os.environ['TERM']
LOG_NAME = __name__
if LOG_NAME == '__main__':
LOG_NAME = os.path.basename(sys.argv[0])
LOG = logging.getLogger(LOG_NAME)
###### lock ########
class filelock(object):
def __init__(self, fn):
self.fn = fn
self.fd = None
def acquire(self):
assert not self.fd
self.fd = file(self.fn, 'w')
fcntl.lockf(self.fd, fcntl.LOCK_EX)
def release(self):
assert self.fd
fcntl.lockf(self.fd, fcntl.LOCK_UN)
self.fd = None
###### exceptions ########
class Error(Exception):
"""
Error
"""
def __str__(self):
doc = self.__doc__.strip()
return ': '.join([doc] + [str(a) for a in self.args])
class MountError(Error):
"""
Mounting filesystem failed
"""
class UnmountError(Error):
"""
Unmounting filesystem failed
"""
class BadMagicError(Error):
"""
Does not look like a Ceph OSD, or incompatible version
"""
class TruncatedLineError(Error):
"""
Line is truncated
"""
class TooManyLinesError(Error):
"""
Too many lines
"""
class FilesystemTypeError(Error):
"""
Cannot discover filesystem type
"""
class CephDiskException(Exception):
"""
A base exception for ceph-disk to provide custom (ad-hoc) messages that
will be caught and dealt with when main() is executed
"""
pass
class ExecutableNotFound(CephDiskException):
"""
Exception to report on executables not available in PATH
"""
pass
####### utils
def is_systemd():
"""
Detect whether systemd is running
"""
with file('/proc/1/comm', 'rb') as i:
for line in i:
if 'systemd' in line:
return True
return False
def is_upstart():
"""
Detect whether upstart is running
"""
(out, err, _) = command(['init', '--version'])
if 'upstart' in out:
return True
return False
def maybe_mkdir(*a, **kw):
"""
Creates a new directory if it doesn't exist, removes
existing symlink before creating the directory.
"""
# remove any symlink, if it is there..
if os.path.exists(*a) and stat.S_ISLNK(os.lstat(*a).st_mode):
LOG.debug('Removing old symlink at %s', *a)
os.unlink(*a)
try:
os.mkdir(*a, **kw)
except OSError, e:
if e.errno == errno.EEXIST:
pass
else:
raise
def which(executable):
"""find the location of an executable"""
if 'PATH' in os.environ:
envpath = os.environ['PATH']
else:
envpath = os.defpath
PATH = envpath.split(os.pathsep)
locations = PATH + [
'/usr/local/bin',
'/bin',
'/usr/bin',
'/usr/local/sbin',
'/usr/sbin',
'/sbin',
]
for location in locations:
executable_path = os.path.join(location, executable)
if (os.path.isfile(executable_path) and
os.access(executable_path, os.X_OK)):
return executable_path
def _get_command_executable(arguments):
"""
Return the full path for an executable, raise if the executable is not
found. If the executable has already a full path do not perform any checks.
"""
if arguments[0].startswith('/'): # an absolute path
return arguments
executable = which(arguments[0])
if not executable:
command_msg = 'Could not run command: %s' % ' '.join(arguments)
executable_msg = '%s not in path.' % arguments[0]
raise ExecutableNotFound('%s %s' % (executable_msg, command_msg))
# swap the old executable for the new one
arguments[0] = executable
return arguments
def command(arguments, **kwargs):
"""
Safely execute a ``subprocess.Popen`` call making sure that the
executable exists and raising a helpful error message
if it does not.
.. note:: This should be the prefered way of calling ``subprocess.Popen``
since it provides the caller with the safety net of making sure that
executables *will* be found and will error nicely otherwise.
This returns the output of the command and the return code of the
process in a tuple: (output, returncode).
"""
arguments = _get_command_executable(arguments)
LOG.info('Running command: %s' % ' '.join(arguments))
process = subprocess.Popen(
arguments,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
**kwargs)
out, err = process.communicate()
return out, err, process.returncode
def command_check_call(arguments):
"""
Safely execute a ``subprocess.check_call`` call making sure that the
executable exists and raising a helpful error message if it does not.
.. note:: This should be the prefered way of calling
``subprocess.check_call`` since it provides the caller with the safety net
of making sure that executables *will* be found and will error nicely
otherwise.
"""
arguments = _get_command_executable(arguments)
LOG.info('Running command: %s', ' '.join(arguments))
return subprocess.check_call(arguments)
def platform_distro():
"""
Returns a normalized, lower case string without any leading nor trailing
whitespace that represents the distribution name of the current machine.
"""
distro = platform_information()[0] or ''
return distro.strip().lower()
def platform_information():
distro, release, codename = platform.linux_distribution()
if not codename and 'debian' in distro.lower(): # this could be an empty string in Debian
debian_codenames = {
'8': 'jessie',
'7': 'wheezy',
'6': 'squeeze',
}
major_version = release.split('.')[0]
codename = debian_codenames.get(major_version, '')
# In order to support newer jessie/sid or wheezy/sid strings we test this
# if sid is buried in the minor, we should use sid anyway.
if not codename and '/' in release:
major, minor = release.split('/')
if minor == 'sid':
codename = minor
else:
codename = major
return (
str(distro).strip(),
str(release).strip(),
str(codename).strip()
)
#
# An alternative block_path implementation would be
#
# name = basename(dev)
# return /sys/devices/virtual/block/$name
#
# It is however more fragile because it relies on the fact
# that the basename of the device the user will use always
# matches the one the driver will use. On Ubuntu 14.04, for
# instance, when multipath creates a partition table on
#
# /dev/mapper/353333330000007d0 -> ../dm-0
#
# it will create partition devices named
#
# /dev/mapper/353333330000007d0-part1
#
# which is the same device as /dev/dm-1 but not a symbolic
# link to it:
#
# ubuntu@other:~$ ls -l /dev/mapper /dev/dm-1
# brw-rw---- 1 root disk 252, 1 Aug 15 17:52 /dev/dm-1
# lrwxrwxrwx 1 root root 7 Aug 15 17:52 353333330000007d0 -> ../dm-0
# brw-rw---- 1 root disk 252, 1 Aug 15 17:52 353333330000007d0-part1
#
# Using the basename in this case fails.
#
def block_path(dev):
path = os.path.realpath(dev)
rdev = os.stat(path).st_rdev
(M, m) = (os.major(rdev), os.minor(rdev))
return "{sysfs}/dev/block/{M}:{m}".format(sysfs=SYSFS, M=M, m=m)
def get_dm_uuid(dev):
uuid_path = os.path.join(block_path(dev), 'dm', 'uuid')
LOG.debug("get_dm_uuid " + dev + " uuid path is " + uuid_path)
if not os.path.exists(uuid_path):
return False
uuid = open(uuid_path, 'r').read()
LOG.debug("get_dm_uuid " + dev + " uuid is " + uuid)
return uuid
def is_mpath(dev):
"""
True if the path is managed by multipath
"""
uuid = get_dm_uuid(dev)
return (uuid and
(re.match('part\d+-mpath-', uuid) or
re.match('mpath-', uuid)))
def get_dev_name(path):
"""
get device name from path. e.g.::
/dev/sda -> sdas, /dev/cciss/c0d1 -> cciss!c0d1
a device "name" is something like::
sdb
cciss!c0d1
"""
assert path.startswith('/dev/')
base = path[5:]
return base.replace('/', '!')
def get_dev_path(name):
"""
get a path (/dev/...) from a name (cciss!c0d1)
a device "path" is something like::
/dev/sdb
/dev/cciss/c0d1
"""
return '/dev/' + name.replace('!', '/')
def get_dev_relpath(name):
"""
get a relative path to /dev from a name (cciss!c0d1)
"""
return name.replace('!', '/')
def get_dev_size(dev, size='megabytes'):
"""
Attempt to get the size of a device so that we can prevent errors
from actions to devices that are smaller, and improve error reporting.
Because we want to avoid breakage in case this approach is not robust, we
will issue a warning if we failed to get the size.
:param size: bytes or megabytes
:param dev: the device to calculate the size
"""
fd = os.open(dev, os.O_RDONLY)
dividers = {'bytes': 1, 'megabytes': 1024*1024}
try:
device_size = os.lseek(fd, 0, os.SEEK_END)
divider = dividers.get(size, 1024*1024) # default to megabytes
return device_size/divider
except Exception as error:
LOG.warning('failed to get size of %s: %s' % (dev, str(error)))
finally:
os.close(fd)
def get_partition_mpath(dev, pnum):
part_re = "part{pnum}-mpath-".format(pnum=pnum)
partitions = list_partitions_mpath(dev, part_re)
if partitions:
return partitions[0]
else:
return None
def get_partition_dev(dev, pnum):
"""
get the device name for a partition
assume that partitions are named like the base dev, with a number, and optionally
some intervening characters (like 'p'). e.g.,
sda 1 -> sda1
cciss/c0d1 1 -> cciss!c0d1p1
"""
partname = None
if is_mpath(dev):
partname = get_partition_mpath(dev, pnum)
else:
name = get_dev_name(os.path.realpath(dev))
for f in os.listdir(os.path.join('/sys/block', name)):
if f.startswith(name) and f.endswith(str(pnum)):
# we want the shortest name that starts with the base name and ends with the partition number
if not partname or len(f) < len(partname):
partname = f
if partname:
return get_dev_path(partname)
else:
raise Error('partition %d for %s does not appear to exist' % (pnum, dev))
def list_all_partitions():
"""
Return a list of devices and partitions
"""
names = os.listdir('/sys/block')
dev_part_list = {}
for name in names:
# /dev/fd0 may hang http://tracker.ceph.com/issues/6827
if re.match(r'^fd\d$', name):
continue
dev_part_list[name] = list_partitions(get_dev_path(name))
return dev_part_list
def list_partitions(dev):
dev = os.path.realpath(dev)
if is_mpath(dev):
return list_partitions_mpath(dev)
else:
return list_partitions_device(dev)
def list_partitions_mpath(dev, part_re="part\d+-mpath-"):
p = block_path(dev)
partitions = []
holders = os.path.join(p, 'holders')
for holder in os.listdir(holders):
uuid_path = os.path.join(holders, holder, 'dm', 'uuid')
uuid = open(uuid_path, 'r').read()
LOG.debug("list_partitions_mpath: " + uuid_path + " uuid = " + uuid)
if re.match(part_re, uuid):
partitions.append(holder)
return partitions
def list_partitions_device(dev):
"""
Return a list of partitions on the given device name
"""
partitions = []
basename = get_dev_name(dev)
for name in os.listdir(block_path(dev)):
if name.startswith(basename):
partitions.append(name)
return partitions
def get_partition_base(dev):
"""
Get the base device for a partition
"""
dev = os.path.realpath(dev)
if not stat.S_ISBLK(os.lstat(dev).st_mode):
raise Error('not a block device', dev)
name = get_dev_name(dev)
if os.path.exists(os.path.join('/sys/block', name)):
raise Error('not a partition', dev)
# find the base
for basename in os.listdir('/sys/block'):
if os.path.exists(os.path.join('/sys/block', basename, name)):
return get_dev_path(basename)
raise Error('no parent device for partition', dev)
def is_partition_mpath(dev):
uuid = get_dm_uuid(dev)
return bool(re.match('part\d+-mpath-', uuid))
def partnum_mpath(dev):
uuid = get_dm_uuid(dev)
return re.findall('part(\d+)-mpath-', uuid)[0]
def get_partition_base_mpath(dev):
slave_path = os.path.join(block_path(dev), 'slaves')
slaves = os.listdir(slave_path)
assert slaves
name_path = os.path.join(slave_path, slaves[0], 'dm', 'name')
name = open(name_path, 'r').read().strip()
return os.path.join('/dev/mapper', name)
def is_partition(dev):
"""
Check whether a given device path is a partition or a full disk.
"""
if is_mpath(dev):
return is_partition_mpath(dev)
dev = os.path.realpath(dev)
st = os.lstat(dev)
if not stat.S_ISBLK(st.st_mode):
raise Error('not a block device', dev)
name = get_dev_name(dev)
if os.path.exists(os.path.join('/sys/block', name)):
return False
# make sure it is a partition of something else
major = os.major(st.st_rdev)
minor = os.minor(st.st_rdev)
if os.path.exists('/sys/dev/block/%d:%d/partition' % (major, minor)):
return True
raise Error('not a disk or partition', dev)
def is_mounted(dev):
"""
Check if the given device is mounted.
"""
dev = os.path.realpath(dev)
with file('/proc/mounts', 'rb') as proc_mounts:
for line in proc_mounts:
fields = line.split()
if len(fields) < 3:
continue
mounts_dev = fields[0]
path = fields[1]
if mounts_dev.startswith('/') and os.path.exists(mounts_dev):
mounts_dev = os.path.realpath(mounts_dev)
if mounts_dev == dev:
return path
return None
def is_held(dev):
"""
Check if a device is held by another device (e.g., a dm-crypt mapping)
"""
assert os.path.exists(dev)
if is_mpath(dev):
return []
dev = os.path.realpath(dev)
base = get_dev_name(dev)
# full disk?
directory = '/sys/block/{base}/holders'.format(base=base)
if os.path.exists(directory):
return os.listdir(directory)
# partition?
part = base
while len(base):
directory = '/sys/block/{base}/{part}/holders'.format(part=part, base=base)
if os.path.exists(directory):
return os.listdir(directory)
base = base[:-1]
return []
def verify_not_in_use(dev, check_partitions=False):
"""
Verify if a given device (path) is in use (e.g. mounted or
in use by device-mapper).
:raises: Error if device is in use.
"""
assert os.path.exists(dev)
if is_mounted(dev):
raise Error('Device is mounted', dev)
holders = is_held(dev)
if holders:
raise Error('Device %s is in use by a device-mapper mapping (dm-crypt?)' % dev, ','.join(holders))
if check_partitions and not is_partition(dev):
for partname in list_partitions(dev):
partition = get_dev_path(partname)
if is_mounted(partition):
raise Error('Device is mounted', partition)
holders = is_held(partition)
if holders:
raise Error('Device %s is in use by a device-mapper mapping (dm-crypt?)' % partition, ','.join(holders))
def must_be_one_line(line):
"""
Checks if given line is really one single line.
:raises: TruncatedLineError or TooManyLinesError
:return: Content of the line, or None if line isn't valid.
"""
if line[-1:] != '\n':
raise TruncatedLineError(line)
line = line[:-1]
if '\n' in line:
raise TooManyLinesError(line)
return line
def read_one_line(parent, name):
"""
Read a file whose sole contents are a single line.
Strips the newline.
:return: Contents of the line, or None if file did not exist.
"""
path = os.path.join(parent, name)
try:
line = file(path, 'rb').read()
except IOError as e:
if e.errno == errno.ENOENT:
return None
else:
raise
try:
line = must_be_one_line(line)
except (TruncatedLineError, TooManyLinesError) as e:
raise Error(
'File is corrupt: {path}: {msg}'.format(
path=path,
msg=e,
)
)
return line
def write_one_line(parent, name, text):
"""
Write a file whose sole contents are a single line.
Adds a newline.
"""
path = os.path.join(parent, name)
tmp = '{path}.{pid}.tmp'.format(path=path, pid=os.getpid())
with file(tmp, 'wb') as tmp_file:
tmp_file.write(text + '\n')
os.fsync(tmp_file.fileno())
path_set_context(tmp)
os.rename(tmp, path)
def init_get():
"""
Get a init system using 'ceph-detect-init'
"""
init = _check_output(
args=[
'ceph-detect-init',
'--default', 'sysvinit',
],
)
init = must_be_one_line(init)
return init
def check_osd_magic(path):
"""
Check that this path has the Ceph OSD magic.
:raises: BadMagicError if this does not look like a Ceph OSD data
dir.
"""
magic = read_one_line(path, 'magic')
if magic is None:
# probably not mkfs'ed yet
raise BadMagicError(path)
if magic != CEPH_OSD_ONDISK_MAGIC:
raise BadMagicError(path)
def check_osd_id(osd_id):
"""
Ensures osd id is numeric.
"""
if not re.match(r'^[0-9]+$', osd_id):
raise Error('osd id is not numeric', osd_id)
def allocate_osd_id(
cluster,
fsid,
keyring,
):
"""
Accocates an OSD id on the given cluster.
:raises: Error if the call to allocate the OSD id fails.
:return: The allocated OSD id.
"""
LOG.debug('Allocating OSD id...')
try:
osd_id = _check_output(
args=[
'ceph',
'--cluster', cluster,
'--name', 'client.bootstrap-osd',
'--keyring', keyring,
'osd', 'create', '--concise',
fsid,
],
)
except subprocess.CalledProcessError as e:
raise Error('ceph osd create failed', e, e.output)
osd_id = must_be_one_line(osd_id)
check_osd_id(osd_id)
return osd_id
def get_osd_id(path):
"""
Gets the OSD id of the OSD at the given path.
"""
osd_id = read_one_line(path, 'whoami')
if osd_id is not None:
check_osd_id(osd_id)
return osd_id
def get_ceph_user():
try:
pwd.getpwnam('ceph')
grp.getgrnam('ceph')
return 'ceph'
except KeyError:
return 'root'
def path_set_context(path):
# restore selinux context to default policy values
if which('restorecon'):
command(
[
'restorecon', '-R',
path,
],
)
# if ceph user exists, set owner to ceph
if get_ceph_user() == 'ceph':
command(
[
'chown', '-R', 'ceph:ceph',
path,
],
)
def _check_output(args=None, **kwargs):
out, err, ret = command(args, **kwargs)
if ret:
cmd = args[0]
error = subprocess.CalledProcessError(ret, cmd)
error.output = out + err
raise error
return out
def get_conf(cluster, variable):
"""
Get the value of the given configuration variable from the
cluster.
:raises: Error if call to ceph-conf fails.
:return: The variable value or None.
"""
try:
out, err, ret = command(
[
'ceph-conf',
'--cluster={cluster}'.format(
cluster=cluster,
),
'--name=osd.',
'--lookup',
variable,
],
close_fds=True,
)
except OSError as e:
raise Error('error executing ceph-conf', e, err)
if ret == 1:
# config entry not found
return None
elif ret != 0:
raise Error('getting variable from configuration failed')
value = out.split('\n', 1)[0]
# don't differentiate between "var=" and no var set
if not value:
return None
return value
def get_conf_with_default(cluster, variable):
"""
Get a config value that is known to the C++ code.
This will fail if called on variables that are not defined in
common config options.
"""
try:
out = _check_output(
args=[
'ceph-osd',
'--cluster={cluster}'.format(
cluster=cluster,
),
'--show-config-value={variable}'.format(
variable=variable,
),
],
close_fds=True,
)
except subprocess.CalledProcessError as e:
raise Error(
'getting variable from configuration failed',
e,
)
value = str(out).split('\n', 1)[0]
return value
def get_fsid(cluster):
"""
Get the fsid of the cluster.
:return: The fsid or raises Error.
"""
fsid = get_conf_with_default(cluster=cluster, variable='fsid')
if fsid is None:
raise Error('getting cluster uuid from configuration failed')
return fsid.lower()
def get_dmcrypt_key_path(
_uuid,
key_dir,
luks
):
"""
Get path to dmcrypt key file.
:return: Path to the dmcrypt key file, callers should check for existence.
"""
if luks:
path = os.path.join(key_dir, _uuid + ".luks.key")
else:
path = os.path.join(key_dir, _uuid)
return path
def get_or_create_dmcrypt_key(