~openstack-charmers/charms/trusty/nova-compute/0mq

« back to all changes in this revision

Viewing changes to hooks/charmhelpers/contrib/hahelpers/ceph.py

  • Committer: james.page at ubuntu
  • Date: 2015-03-16 14:18:05 UTC
  • mfrom: (79.2.28 nova-compute)
  • Revision ID: james.page@ubuntu.com-20150316141805-eko8x0x1gfyrqzeo
Rebase

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 commands
12
 
import os
13
 
import shutil
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
 
    ERROR
29
 
)
30
 
 
31
 
from charmhelpers.fetch import (
32
 
    apt_install,
33
 
)
34
 
 
35
 
from charmhelpers.core.host import (
36
 
    mount,
37
 
    mounts,
38
 
    service_start,
39
 
    service_stop,
40
 
    umount,
41
 
)
42
 
 
43
 
KEYRING = '/etc/ceph/ceph.client.%s.keyring'
44
 
KEYFILE = '/etc/ceph/ceph.client.%s.key'
45
 
 
46
 
CEPH_CONF = """[global]
47
 
 auth supported = %(auth)s
48
 
 keyring = %(keyring)s
49
 
 mon host = %(mon_hosts)s
50
 
"""
51
 
 
52
 
 
53
 
def running(service):
54
 
    # this local util can be dropped as soon the following branch lands
55
 
    # in lp:charm-helpers
56
 
    # https://code.launchpad.net/~gandelman-a/charm-helpers/service_running/
57
 
    try:
58
 
        output = check_output(['service', service, 'status'])
59
 
    except CalledProcessError:
60
 
        return False
61
 
    else:
62
 
        if ("start/running" in output or "is running" in output):
63
 
            return True
64
 
        else:
65
 
            return False
66
 
 
67
 
 
68
 
def install():
69
 
    ceph_dir = "/etc/ceph"
70
 
    if not os.path.isdir(ceph_dir):
71
 
        os.mkdir(ceph_dir)
72
 
    apt_install('ceph-common', fatal=True)
73
 
 
74
 
 
75
 
def rbd_exists(service, pool, rbd_img):
76
 
    (rc, out) = commands.getstatusoutput('rbd list --id %s --pool %s' %
77
 
                                         (service, pool))
78
 
    return rbd_img in out
79
 
 
80
 
 
81
 
def create_rbd_image(service, pool, image, sizemb):
82
 
    cmd = [
83
 
        'rbd',
84
 
        'create',
85
 
        image,
86
 
        '--size',
87
 
        str(sizemb),
88
 
        '--id',
89
 
        service,
90
 
        '--pool',
91
 
        pool
92
 
    ]
93
 
    check_call(cmd)
94
 
 
95
 
 
96
 
def pool_exists(service, name):
97
 
    (rc, out) = commands.getstatusoutput("rados --id %s lspools" % service)
98
 
    return name in out
99
 
 
100
 
 
101
 
def create_pool(service, name):
102
 
    cmd = [
103
 
        'rados',
104
 
        '--id',
105
 
        service,
106
 
        'mkpool',
107
 
        name
108
 
    ]
109
 
    check_call(cmd)
110
 
 
111
 
 
112
 
def keyfile_path(service):
113
 
    return KEYFILE % service
114
 
 
115
 
 
116
 
def keyring_path(service):
117
 
    return KEYRING % service
118
 
 
119
 
 
120
 
def create_keyring(service, key):
121
 
    keyring = keyring_path(service)
122
 
    if os.path.exists(keyring):
123
 
        log('ceph: Keyring exists at %s.' % keyring, level=INFO)
124
 
    cmd = [
125
 
        'ceph-authtool',
126
 
        keyring,
127
 
        '--create-keyring',
128
 
        '--name=client.%s' % service,
129
 
        '--add-key=%s' % key
130
 
    ]
131
 
    check_call(cmd)
132
 
    log('ceph: Created new ring at %s.' % keyring, level=INFO)
133
 
 
134
 
 
135
 
def create_key_file(service, key):
136
 
    # create a file containing the key
137
 
    keyfile = keyfile_path(service)
138
 
    if os.path.exists(keyfile):
139
 
        log('ceph: Keyfile exists at %s.' % keyfile, level=INFO)
140
 
    fd = open(keyfile, 'w')
141
 
    fd.write(key)
142
 
    fd.close()
143
 
    log('ceph: Created new keyfile at %s.' % keyfile, level=INFO)
144
 
 
145
 
 
146
 
def get_ceph_nodes():
147
 
    hosts = []
148
 
    for r_id in relation_ids('ceph'):
149
 
        for unit in related_units(r_id):
150
 
            hosts.append(relation_get('private-address', unit=unit, rid=r_id))
151
 
    return hosts
152
 
 
153
 
 
154
 
def configure(service, key, auth):
155
 
    create_keyring(service, key)
156
 
    create_key_file(service, key)
157
 
    hosts = get_ceph_nodes()
158
 
    mon_hosts = ",".join(map(str, hosts))
159
 
    keyring = keyring_path(service)
160
 
    with open('/etc/ceph/ceph.conf', 'w') as ceph_conf:
161
 
        ceph_conf.write(CEPH_CONF % locals())
162
 
    modprobe_kernel_module('rbd')
163
 
 
164
 
 
165
 
def image_mapped(image_name):
166
 
    (rc, out) = commands.getstatusoutput('rbd showmapped')
167
 
    return image_name in out
168
 
 
169
 
 
170
 
def map_block_storage(service, pool, image):
171
 
    cmd = [
172
 
        'rbd',
173
 
        'map',
174
 
        '%s/%s' % (pool, image),
175
 
        '--user',
176
 
        service,
177
 
        '--secret',
178
 
        keyfile_path(service),
179
 
    ]
180
 
    check_call(cmd)
181
 
 
182
 
 
183
 
def filesystem_mounted(fs):
184
 
    return fs in [f for m, f in mounts()]
185
 
 
186
 
 
187
 
def make_filesystem(blk_device, fstype='ext4', timeout=10):
188
 
    count = 0
189
 
    e_noent = os.errno.ENOENT
190
 
    while not os.path.exists(blk_device):
191
 
        if count >= timeout:
192
 
            log('ceph: gave up waiting on block device %s' % blk_device,
193
 
                level=ERROR)
194
 
            raise IOError(e_noent, os.strerror(e_noent), blk_device)
195
 
        log('ceph: waiting for block device %s to appear' % blk_device,
196
 
            level=INFO)
197
 
        count += 1
198
 
        time.sleep(1)
199
 
    else:
200
 
        log('ceph: Formatting block device %s as filesystem %s.' %
201
 
            (blk_device, fstype), level=INFO)
202
 
        check_call(['mkfs', '-t', fstype, blk_device])
203
 
 
204
 
 
205
 
def place_data_on_ceph(service, blk_device, data_src_dst, fstype='ext4'):
206
 
    # mount block device into /mnt
207
 
    mount(blk_device, '/mnt')
208
 
 
209
 
    # copy data to /mnt
210
 
    try:
211
 
        copy_files(data_src_dst, '/mnt')
212
 
    except:
213
 
        pass
214
 
 
215
 
    # umount block device
216
 
    umount('/mnt')
217
 
 
218
 
    _dir = os.stat(data_src_dst)
219
 
    uid = _dir.st_uid
220
 
    gid = _dir.st_gid
221
 
 
222
 
    # re-mount where the data should originally be
223
 
    mount(blk_device, data_src_dst, persist=True)
224
 
 
225
 
    # ensure original ownership of new mount.
226
 
    cmd = ['chown', '-R', '%s:%s' % (uid, gid), data_src_dst]
227
 
    check_call(cmd)
228
 
 
229
 
 
230
 
# TODO: re-use
231
 
def modprobe_kernel_module(module):
232
 
    log('ceph: Loading kernel module', level=INFO)
233
 
    cmd = ['modprobe', module]
234
 
    check_call(cmd)
235
 
    cmd = 'echo %s >> /etc/modules' % module
236
 
    check_call(cmd, shell=True)
237
 
 
238
 
 
239
 
def copy_files(src, dst, symlinks=False, ignore=None):
240
 
    for item in os.listdir(src):
241
 
        s = os.path.join(src, item)
242
 
        d = os.path.join(dst, item)
243
 
        if os.path.isdir(s):
244
 
            shutil.copytree(s, d, symlinks, ignore)
245
 
        else:
246
 
            shutil.copy2(s, d)
247
 
 
248
 
 
249
 
def ensure_ceph_storage(service, pool, rbd_img, sizemb, mount_point,
250
 
                        blk_device, fstype, system_services=[]):
251
 
    """
252
 
    To be called from the current cluster leader.
253
 
    Ensures given pool and RBD image exists, is mapped to a block device,
254
 
    and the device is formatted and mounted at the given mount_point.
255
 
 
256
 
    If formatting a device for the first time, data existing at mount_point
257
 
    will be migrated to the RBD device before being remounted.
258
 
 
259
 
    All services listed in system_services will be stopped prior to data
260
 
    migration and restarted when complete.
261
 
    """
262
 
    # Ensure pool, RBD image, RBD mappings are in place.
263
 
    if not pool_exists(service, pool):
264
 
        log('ceph: Creating new pool %s.' % pool, level=INFO)
265
 
        create_pool(service, pool)
266
 
 
267
 
    if not rbd_exists(service, pool, rbd_img):
268
 
        log('ceph: Creating RBD image (%s).' % rbd_img, level=INFO)
269
 
        create_rbd_image(service, pool, rbd_img, sizemb)
270
 
 
271
 
    if not image_mapped(rbd_img):
272
 
        log('ceph: Mapping RBD Image as a Block Device.', level=INFO)
273
 
        map_block_storage(service, pool, rbd_img)
274
 
 
275
 
    # make file system
276
 
    # TODO: What happens if for whatever reason this is run again and
277
 
    # the data is already in the rbd device and/or is mounted??
278
 
    # When it is mounted already, it will fail to make the fs
279
 
    # XXX: This is really sketchy!  Need to at least add an fstab entry
280
 
    #      otherwise this hook will blow away existing data if its executed
281
 
    #      after a reboot.
282
 
    if not filesystem_mounted(mount_point):
283
 
        make_filesystem(blk_device, fstype)
284
 
 
285
 
        for svc in system_services:
286
 
            if running(svc):
287
 
                log('Stopping services %s prior to migrating data.' % svc,
288
 
                    level=INFO)
289
 
                service_stop(svc)
290
 
 
291
 
        place_data_on_ceph(service, blk_device, mount_point, fstype)
292
 
 
293
 
        for svc in system_services:
294
 
            service_start(svc)