~tribaal/charms/trusty/nova-compute/sync-charm-helpers

« back to all changes in this revision

Viewing changes to hooks/charmhelpers/contrib/storage/linux/ceph.py

  • Committer: James Page
  • Date: 2013-10-15 12:04:13 UTC
  • mfrom: (46.1.83 nova-compute)
  • Revision ID: james.page@canonical.com-20131015120413-grclbw2ot5gbgp5r
Update of all Havana / Saucy / python-redux work:

* Full python rewrite using new OpenStack charm-helpers.

* Test coverage

* Havana support

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#
 
2
# Copyright 2012 Canonical Ltd.
 
3
#
 
4
# This file is sourced from lp:openstack-charm-helpers
 
5
#
 
6
# Authors:
 
7
#  James Page <james.page@ubuntu.com>
 
8
#  Adam Gandelman <adamg@ubuntu.com>
 
9
#
 
10
 
 
11
import os
 
12
import shutil
 
13
import json
 
14
import time
 
15
 
 
16
from subprocess import (
 
17
    check_call,
 
18
    check_output,
 
19
    CalledProcessError
 
20
)
 
21
 
 
22
from charmhelpers.core.hookenv import (
 
23
    relation_get,
 
24
    relation_ids,
 
25
    related_units,
 
26
    log,
 
27
    INFO,
 
28
    WARNING,
 
29
    ERROR
 
30
)
 
31
 
 
32
from charmhelpers.core.host import (
 
33
    mount,
 
34
    mounts,
 
35
    service_start,
 
36
    service_stop,
 
37
    service_running,
 
38
    umount,
 
39
)
 
40
 
 
41
from charmhelpers.fetch import (
 
42
    apt_install,
 
43
)
 
44
 
 
45
KEYRING = '/etc/ceph/ceph.client.{}.keyring'
 
46
KEYFILE = '/etc/ceph/ceph.client.{}.key'
 
47
 
 
48
CEPH_CONF = """[global]
 
49
 auth supported = {auth}
 
50
 keyring = {keyring}
 
51
 mon host = {mon_hosts}
 
52
"""
 
53
 
 
54
 
 
55
def install():
 
56
    ''' Basic Ceph client installation '''
 
57
    ceph_dir = "/etc/ceph"
 
58
    if not os.path.exists(ceph_dir):
 
59
        os.mkdir(ceph_dir)
 
60
    apt_install('ceph-common', fatal=True)
 
61
 
 
62
 
 
63
def rbd_exists(service, pool, rbd_img):
 
64
    ''' Check to see if a RADOS block device exists '''
 
65
    try:
 
66
        out = check_output(['rbd', 'list', '--id', service,
 
67
                            '--pool', pool])
 
68
    except CalledProcessError:
 
69
        return False
 
70
    else:
 
71
        return rbd_img in out
 
72
 
 
73
 
 
74
def create_rbd_image(service, pool, image, sizemb):
 
75
    ''' Create a new RADOS block device '''
 
76
    cmd = [
 
77
        'rbd',
 
78
        'create',
 
79
        image,
 
80
        '--size',
 
81
        str(sizemb),
 
82
        '--id',
 
83
        service,
 
84
        '--pool',
 
85
        pool
 
86
    ]
 
87
    check_call(cmd)
 
88
 
 
89
 
 
90
def pool_exists(service, name):
 
91
    ''' Check to see if a RADOS pool already exists '''
 
92
    try:
 
93
        out = check_output(['rados', '--id', service, 'lspools'])
 
94
    except CalledProcessError:
 
95
        return False
 
96
    else:
 
97
        return name in out
 
98
 
 
99
 
 
100
def get_osds(service):
 
101
    '''
 
102
    Return a list of all Ceph Object Storage Daemons
 
103
    currently in the cluster
 
104
    '''
 
105
    return json.loads(check_output(['ceph', '--id', service,
 
106
                                    'osd', 'ls', '--format=json']))
 
107
 
 
108
 
 
109
def create_pool(service, name, replicas=2):
 
110
    ''' Create a new RADOS pool '''
 
111
    if pool_exists(service, name):
 
112
        log("Ceph pool {} already exists, skipping creation".format(name),
 
113
            level=WARNING)
 
114
        return
 
115
    # Calculate the number of placement groups based
 
116
    # on upstream recommended best practices.
 
117
    pgnum = (len(get_osds(service)) * 100 / replicas)
 
118
    cmd = [
 
119
        'ceph', '--id', service,
 
120
        'osd', 'pool', 'create',
 
121
        name, str(pgnum)
 
122
    ]
 
123
    check_call(cmd)
 
124
    cmd = [
 
125
        'ceph', '--id', service,
 
126
        'osd', 'pool', 'set', name,
 
127
        'size', str(replicas)
 
128
    ]
 
129
    check_call(cmd)
 
130
 
 
131
 
 
132
def delete_pool(service, name):
 
133
    ''' Delete a RADOS pool from ceph '''
 
134
    cmd = [
 
135
        'ceph', '--id', service,
 
136
        'osd', 'pool', 'delete',
 
137
        name, '--yes-i-really-really-mean-it'
 
138
    ]
 
139
    check_call(cmd)
 
140
 
 
141
 
 
142
def _keyfile_path(service):
 
143
    return KEYFILE.format(service)
 
144
 
 
145
 
 
146
def _keyring_path(service):
 
147
    return KEYRING.format(service)
 
148
 
 
149
 
 
150
def create_keyring(service, key):
 
151
    ''' Create a new Ceph keyring containing key'''
 
152
    keyring = _keyring_path(service)
 
153
    if os.path.exists(keyring):
 
154
        log('ceph: Keyring exists at %s.' % keyring, level=WARNING)
 
155
        return
 
156
    cmd = [
 
157
        'ceph-authtool',
 
158
        keyring,
 
159
        '--create-keyring',
 
160
        '--name=client.{}'.format(service),
 
161
        '--add-key={}'.format(key)
 
162
    ]
 
163
    check_call(cmd)
 
164
    log('ceph: Created new ring at %s.' % keyring, level=INFO)
 
165
 
 
166
 
 
167
def create_key_file(service, key):
 
168
    ''' Create a file containing key '''
 
169
    keyfile = _keyfile_path(service)
 
170
    if os.path.exists(keyfile):
 
171
        log('ceph: Keyfile exists at %s.' % keyfile, level=WARNING)
 
172
        return
 
173
    with open(keyfile, 'w') as fd:
 
174
        fd.write(key)
 
175
    log('ceph: Created new keyfile at %s.' % keyfile, level=INFO)
 
176
 
 
177
 
 
178
def get_ceph_nodes():
 
179
    ''' Query named relation 'ceph' to detemine current nodes '''
 
180
    hosts = []
 
181
    for r_id in relation_ids('ceph'):
 
182
        for unit in related_units(r_id):
 
183
            hosts.append(relation_get('private-address', unit=unit, rid=r_id))
 
184
    return hosts
 
185
 
 
186
 
 
187
def configure(service, key, auth):
 
188
    ''' Perform basic configuration of Ceph '''
 
189
    create_keyring(service, key)
 
190
    create_key_file(service, key)
 
191
    hosts = get_ceph_nodes()
 
192
    with open('/etc/ceph/ceph.conf', 'w') as ceph_conf:
 
193
        ceph_conf.write(CEPH_CONF.format(auth=auth,
 
194
                                         keyring=_keyring_path(service),
 
195
                                         mon_hosts=",".join(map(str, hosts))))
 
196
    modprobe('rbd')
 
197
 
 
198
 
 
199
def image_mapped(name):
 
200
    ''' Determine whether a RADOS block device is mapped locally '''
 
201
    try:
 
202
        out = check_output(['rbd', 'showmapped'])
 
203
    except CalledProcessError:
 
204
        return False
 
205
    else:
 
206
        return name in out
 
207
 
 
208
 
 
209
def map_block_storage(service, pool, image):
 
210
    ''' Map a RADOS block device for local use '''
 
211
    cmd = [
 
212
        'rbd',
 
213
        'map',
 
214
        '{}/{}'.format(pool, image),
 
215
        '--user',
 
216
        service,
 
217
        '--secret',
 
218
        _keyfile_path(service),
 
219
    ]
 
220
    check_call(cmd)
 
221
 
 
222
 
 
223
def filesystem_mounted(fs):
 
224
    ''' Determine whether a filesytems is already mounted '''
 
225
    return fs in [f for f, m in mounts()]
 
226
 
 
227
 
 
228
def make_filesystem(blk_device, fstype='ext4', timeout=10):
 
229
    ''' Make a new filesystem on the specified block device '''
 
230
    count = 0
 
231
    e_noent = os.errno.ENOENT
 
232
    while not os.path.exists(blk_device):
 
233
        if count >= timeout:
 
234
            log('ceph: gave up waiting on block device %s' % blk_device,
 
235
                level=ERROR)
 
236
            raise IOError(e_noent, os.strerror(e_noent), blk_device)
 
237
        log('ceph: waiting for block device %s to appear' % blk_device,
 
238
            level=INFO)
 
239
        count += 1
 
240
        time.sleep(1)
 
241
    else:
 
242
        log('ceph: Formatting block device %s as filesystem %s.' %
 
243
            (blk_device, fstype), level=INFO)
 
244
        check_call(['mkfs', '-t', fstype, blk_device])
 
245
 
 
246
 
 
247
def place_data_on_block_device(blk_device, data_src_dst):
 
248
    ''' Migrate data in data_src_dst to blk_device and then remount '''
 
249
    # mount block device into /mnt
 
250
    mount(blk_device, '/mnt')
 
251
    # copy data to /mnt
 
252
    copy_files(data_src_dst, '/mnt')
 
253
    # umount block device
 
254
    umount('/mnt')
 
255
    # Grab user/group ID's from original source
 
256
    _dir = os.stat(data_src_dst)
 
257
    uid = _dir.st_uid
 
258
    gid = _dir.st_gid
 
259
    # re-mount where the data should originally be
 
260
    # TODO: persist is currently a NO-OP in core.host
 
261
    mount(blk_device, data_src_dst, persist=True)
 
262
    # ensure original ownership of new mount.
 
263
    os.chown(data_src_dst, uid, gid)
 
264
 
 
265
 
 
266
# TODO: re-use
 
267
def modprobe(module):
 
268
    ''' Load a kernel module and configure for auto-load on reboot '''
 
269
    log('ceph: Loading kernel module', level=INFO)
 
270
    cmd = ['modprobe', module]
 
271
    check_call(cmd)
 
272
    with open('/etc/modules', 'r+') as modules:
 
273
        if module not in modules.read():
 
274
            modules.write(module)
 
275
 
 
276
 
 
277
def copy_files(src, dst, symlinks=False, ignore=None):
 
278
    ''' Copy files from src to dst '''
 
279
    for item in os.listdir(src):
 
280
        s = os.path.join(src, item)
 
281
        d = os.path.join(dst, item)
 
282
        if os.path.isdir(s):
 
283
            shutil.copytree(s, d, symlinks, ignore)
 
284
        else:
 
285
            shutil.copy2(s, d)
 
286
 
 
287
 
 
288
def ensure_ceph_storage(service, pool, rbd_img, sizemb, mount_point,
 
289
                        blk_device, fstype, system_services=[]):
 
290
    """
 
291
    NOTE: This function must only be called from a single service unit for
 
292
          the same rbd_img otherwise data loss will occur.
 
293
 
 
294
    Ensures given pool and RBD image exists, is mapped to a block device,
 
295
    and the device is formatted and mounted at the given mount_point.
 
296
 
 
297
    If formatting a device for the first time, data existing at mount_point
 
298
    will be migrated to the RBD device before being re-mounted.
 
299
 
 
300
    All services listed in system_services will be stopped prior to data
 
301
    migration and restarted when complete.
 
302
    """
 
303
    # Ensure pool, RBD image, RBD mappings are in place.
 
304
    if not pool_exists(service, pool):
 
305
        log('ceph: Creating new pool {}.'.format(pool))
 
306
        create_pool(service, pool)
 
307
 
 
308
    if not rbd_exists(service, pool, rbd_img):
 
309
        log('ceph: Creating RBD image ({}).'.format(rbd_img))
 
310
        create_rbd_image(service, pool, rbd_img, sizemb)
 
311
 
 
312
    if not image_mapped(rbd_img):
 
313
        log('ceph: Mapping RBD Image {} as a Block Device.'.format(rbd_img))
 
314
        map_block_storage(service, pool, rbd_img)
 
315
 
 
316
    # make file system
 
317
    # TODO: What happens if for whatever reason this is run again and
 
318
    # the data is already in the rbd device and/or is mounted??
 
319
    # When it is mounted already, it will fail to make the fs
 
320
    # XXX: This is really sketchy!  Need to at least add an fstab entry
 
321
    #      otherwise this hook will blow away existing data if its executed
 
322
    #      after a reboot.
 
323
    if not filesystem_mounted(mount_point):
 
324
        make_filesystem(blk_device, fstype)
 
325
 
 
326
        for svc in system_services:
 
327
            if service_running(svc):
 
328
                log('ceph: Stopping services {} prior to migrating data.'
 
329
                    .format(svc))
 
330
                service_stop(svc)
 
331
 
 
332
        place_data_on_block_device(blk_device, mount_point)
 
333
 
 
334
        for svc in system_services:
 
335
            log('ceph: Starting service {} after migrating data.'
 
336
                .format(svc))
 
337
            service_start(svc)
 
338
 
 
339
 
 
340
def ensure_ceph_keyring(service, user=None, group=None):
 
341
    '''
 
342
    Ensures a ceph keyring is created for a named service
 
343
    and optionally ensures user and group ownership.
 
344
 
 
345
    Returns False if no ceph key is available in relation state.
 
346
    '''
 
347
    key = None
 
348
    for rid in relation_ids('ceph'):
 
349
        for unit in related_units(rid):
 
350
            key = relation_get('key', rid=rid, unit=unit)
 
351
            if key:
 
352
                break
 
353
    if not key:
 
354
        return False
 
355
    create_keyring(service=service, key=key)
 
356
    keyring = _keyring_path(service)
 
357
    if user and group:
 
358
        check_call(['chown', '%s.%s' % (user, group), keyring])
 
359
    return True