summaryrefslogtreecommitdiff
path: root/src/ceph-disk-prepare
blob: 74b07155ffeada3083fe7fbb282ac150b00eb7da (plain)
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
#!/usr/bin/python

import argparse
import logging
import os
import os.path
import subprocess
import sys
import tempfile
import uuid


log_name = __name__
if log_name == '__main__':
    log_name = os.path.basename(sys.argv[0])
log = logging.getLogger(log_name)


class PrepareError(Exception):
    """
    OSD preparation error
    """

    def __str__(self):
        doc = self.__doc__.strip()
        return ': '.join([doc] + [str(a) for a in self.args])


class MountError(PrepareError):
    """
    Mounting filesystem failed
    """


class UnmountError(PrepareError):
    """
    Unmounting filesystem failed
    """


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 f:
        f.write(text + '\n')
        os.fsync(f.fileno())
    os.rename(tmp, path)


CEPH_OSD_ONDISK_MAGIC = 'ceph osd volume v026'


def get_conf(cluster, variable):
    try:
        p = subprocess.Popen(
            args=[
                'ceph-conf',
                '--cluster={cluster}'.format(
                    cluster=cluster,
                    ),
                '--name=osd.',
                '--lookup',
                variable,
                ],
            stdout=subprocess.PIPE,
            close_fds=True,
            )
    except OSError as e:
        raise PrepareError('error executing ceph-conf', e)
    (out, _err) = p.communicate()
    ret = p.wait()
    if ret == 1:
        # config entry not found
        return None
    elif ret != 0:
        raise PrepareError('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_fsid(cluster):
    fsid = get_conf(cluster=cluster, variable='fsid')
    if fsid is None:
        raise PrepareError('getting cluster uuid from configuration failed')
    return fsid


# TODO depend on xfsprogs?
# TODO switch default to xfs once xfsprogs is guaranteed.
# TODO depend on btrfs-tools?
DEFAULT_FS_TYPE = 'ext4'

MOUNT_OPTIONS = dict(
    ext4='user_xattr',
    )

MKFS_ARGS = dict(
    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',
        ],
    )


def mount(
    dev,
    fstype,
    options,
    ):
    # pick best-of-breed mount options based on fs type
    if options is None:
        options = MOUNT_OPTIONS.get(fstype, '')

    # mount
    path = tempfile.mkdtemp(
        prefix='mnt.',
        dir='/var/lib/ceph/tmp',
        )
    try:
        subprocess.check_call(
            args=[
                'mount',
                '-o', options,
                '--',
                dev,
                path,
                ],
            )
    except subprocess.CalledProcessError as e:
        try:
            os.rmdir(path)
        except (OSError, IOError):
            pass
        raise MountError(e)

    return path


def unmount(
    path,
    ):
    try:
        subprocess.check_call(
            args=[
                'umount',
                '--',
                path,
                ],
            )
    except subprocess.CalledProcessError as e:
        raise UnmountError(e)

    os.rmdir(path)


def prepare(
    disk,
    fstype,
    mkfs_args,
    mount_options,
    cluster_uuid,
    ):
    """
    Prepare a disk to be used as an OSD data disk.

    The ``magic`` file is written last, so it's presence is a reliable
    indicator of the whole sequence having completed.

    WARNING: This will unconditionally overwrite anything given to
    it.
    """
    try:
        subprocess.check_call(
            args=[
                'sgdisk',
                '--zap-all',
                '--clear',
                '--mbrtogpt',
                '--largest-new=1',
                '--change-name=1:ceph data',
                '--typecode=1:89c57f98-2fe5-4dc0-89c1-f3ad0ceff2be',
                '--',
                disk,
                ],
            )
    except subprocess.CalledProcessError as e:
        raise PrepareError(e)

    dev = '{disk}1'.format(disk=disk)
    args = [
        'mkfs',
        '--type={fstype}'.format(fstype=fstype),
        ]
    args.extend(MKFS_ARGS.get(fstype, []))
    if mkfs_args is not None:
        args.extend(mkfs_args.split())
    args.extend
    args.extend([
            '--',
            dev,
            ])
    try:
        subprocess.check_call(args=args)
    except subprocess.CalledProcessError as e:
        raise PrepareError(e)

    path = mount(dev=dev, fstype=fstype, options=mount_options)
    try:
        write_one_line(path, 'ceph_fsid', cluster_uuid)
        osd_uuid = str(uuid.uuid4())
        write_one_line(path, 'fsid', osd_uuid)
        write_one_line(path, 'magic', CEPH_OSD_ONDISK_MAGIC)
    finally:
        unmount(path)

    try:
        subprocess.check_call(
            args=[
                'sgdisk',
               '--typecode=1:4fbd7e29-9d25-41b8-afd0-062c0ceff05d',
                '--',
                disk,
                ],
            )
    except subprocess.CalledProcessError as e:
        raise PrepareError(e)


def parse_args():
    parser = argparse.ArgumentParser(
        description='Prepare a disk for a Ceph OSD',
        )
    parser.add_argument(
        '-v', '--verbose',
        action='store_true', default=None,
        help='be more verbose',
        )
    parser.add_argument(
        '--cluster',
        metavar='NAME',
        help='cluster name to assign this disk to',
        )
    parser.add_argument(
        '--cluster-uuid',
        metavar='UUID',
        help='cluster uuid to assign this disk to',
        )
    parser.add_argument(
        '--fs-type',
        help='file system type to use (e.g. "ext4")',
        )
    parser.add_argument(
        'disk',
        metavar='DISK',
        help='path to OSD data disk block device',
        )
    parser.set_defaults(
        # we want to hold on to this, for later
        prog=parser.prog,
        cluster='ceph',
        )
    args = parser.parse_args()
    return args


def main():
    args = parse_args()

    loglevel = logging.INFO
    if args.verbose:
        loglevel = logging.DEBUG

    logging.basicConfig(
        level=loglevel,
        )

    try:
        if args.cluster_uuid is None:
            args.cluster_uuid = get_fsid(cluster=args.cluster)
            if args.cluster_uuid is None:
                raise PrepareError(
                    'must have fsid in config or pass --cluster--uuid=',
                    )

        if args.fs_type is None:
            args.fs_type = get_conf(
                cluster=args.cluster,
                variable='osd_fs_type',
                )
            if args.fs_type is None:
                args.fs_type = DEFAULT_FS_TYPE

        mkfs_args = get_conf(
            cluster=args.cluster,
            variable='osd_fs_mkfs_arguments_{fstype}'.format(
                fstype=args.fs_type,
                ),
            )

        mount_options = get_conf(
            cluster=args.cluster,
            variable='osd_fs_mount_options_{fstype}'.format(
                fstype=args.fs_type,
                ),
            )

        prepare(
            disk=args.disk,
            fstype=args.fs_type,
            mkfs_args=mkfs_args,
            mount_options=mount_options,
            cluster_uuid=args.cluster_uuid,
            )
    except PrepareError as e:
        print >>sys.stderr, '{prog}: {msg}'.format(
            prog=args.prog,
            msg=e,
            )
        sys.exit(1)

if __name__ == '__main__':
    main()