您的位置:首页 > 编程语言 > Python开发

python通过librados库通过底层的rados操作ceph的对象存储和块存储

2018-03-04 19:41 1726 查看
使用python语言调用原生接口(调用librados库来操作rados)

也就是下图中几种方式中的一种,就是图中的红色部分:



首先来说明一下:这个就相当于在客户端上操作ceph集群的底层对象存储rados,我的代码是在mon节点上执行的,也就是暂时把mon当作客户端来使用。

当然我们也可以另外使用一台主机来作为客户端,这个客户端只要能够连通ceph集群就可以,比如我也可以使用另外一台centos7的主机,只需要 yum -y install ceph即可,然后在/etc/ceph/文件夹下把mon节点/etc/ceph/下的ceph.conf文件和ceph.client.admin.keyring文件复制过去即可完成ceph客户端的配置。

下面是简单python代码示例:

#!/usr/bin/python
#encoding=utf-8
import rados, sys

cluster = rados.Rados(conffile='/etc/ceph/ceph.conf')
#用当前的这个ceph的配置文件去创建一个rados,这里主要是解析ceph.conf中的   集群配置参数。然后将这些参数的值保存在rados中。
cluster.connect()
#这里将会创建一个radosclient的结构,这里会把这个结构主要包含了几个功能模块:    消息管理模块Messager,数据处理模块Objector,finisher线程模块。

print "\n\nI/O Context and Object Operations"

print "================================="

print "\nCreating a context for the 'data' pool"

if not cluster.pool_exists('data'):

raise RuntimeError('No data pool exists')

ioctx = cluster.open_ioctx('data')
#为一个名字叫做data的存储池创建一个ioctx ,ioctx中会指明radosclient与Objector    模块,同时也会记录data的信息,包括pool的参数等。

print "\nWriting object 'school' with contents 'hello , I are from chd university!' to pool 'data'."

ioctx.write("school", "hello , I are from chd university!")

ioctx.set_xattr("school", "lang", "en_US")
print "\nWriting object 'name' with contents 'my name is lxl!' to pool 'data'."

ioctx.write("name", "my name is lxl!")

print "Writing XATTR 'lang' with value 'fr_FR' to object 'name'"

ioctx.set_xattr("name", "lang", "fr_FR")

print "\nContents of object 'school'\n------------------------"

print ioctx.read("school")

print ioctx.get_xattr("name", "lang")
print "\nContents of object 'name'\n------------------------"

print ioctx.read("name")

print "\nClosing the connection."

ioctx.close()


执行结果:



Python 示例代码2:

通过创建rbd块设备来操作rados,也就是下图中的红色部分:



rbd 是个操纵 rados 块设备( RBD )映像的工具, QEMU/KVM 通过 Linux rbd 内核驱动和 rbd 存储驱动来使用。 RBD 映像是简单的块设备,它被条带化成小块对象后存储于 RADOS 对象存储集群。条带化后的对象尺寸必须是 2 的幂。

#!/usr/bin/env python
import sys,rados,rbd
def connectceph():
cluster = rados.Rados(conffile = '/etc/ceph/ceph.conf')
cluster.connect()
ioctx = cluster.open_ioctx('rbd_test')
#使用 rbd 之前,连接到 RADOS,并打开一个 IO context (和特定 pool 相关)
#使用 rbd 之前,连接到 RADOS,并打开一个 IO context (和特定 pool 相关)

rbd_inst = rbd.RBD()
size = 40*1024**3
rbd_inst.create(ioctx,'test_i
4000
mage',size)
image = rbd.Image(ioctx,'test_image')
data = 'hello'* 300000
image.write(data,0)
image.close()
ioctx.close()
cluster.shutdown()

if __name__ == "__main__":
connectceph()


解析:使用 rbd 之前,连接到 RADOS,并打开一个 IO context (和特定 pool 相关)

cluster = rados.Rados(conffile= ‘/etc/ceph/ceph.conf’)

cluster.connect()

ioctx = cluster.open_ioctx(‘rbd_test’)

#初始化一个 RBD 对象

rbd_inst = rbd.RBD()

size = 4 * 1024**3 # 4 GiB

#创建 image

rbd_inst.create(ioctx, ‘testimage’, size)

#初始化 image 对象

image = rbd.Image(ioctx, ‘testimage’)

#准备 约14M字符的数据

data = ‘hello world !!’* 1024**2

#写入数据

image.write(data, 0)

#关闭 image 对象

image.close()

#关闭 IO Context

ioctx.close()

#关闭连接

cluster.shutdown()

可以看看执行结果:



Python示例代码3:

窗体顶端

在给定的集群上发出ceph命令并提供返回的json

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import json

from rados import Rados
from rados import Error as RadosError

class CephClusterCommand(dict):
"""
Issue a ceph command on the given cluster and provide the returned json
"""

def __init__(self, cluster, **kwargs):
dict.__init__(self)
ret, buf, err = cluster.mon_command(json.dumps(kwargs), '', timeout=5)
if ret != 0:
self['err'] = err
else:
self.update(json.loads(buf))

config={'conffile': '/etc/ceph/ceph.conf', 'conf': {}}
with Rados(**config) as cluster:
cluster_status = CephClusterCommand(cluster, prefix='status', format='json')
print cluster_status


执行结果:

{u’election_epoch’: 4, u’quorum’: [0], u’monmap’: {u’epoch’: 1, u’mons’: [{u’name’: u’node1’, u’rank’: 0, u’addr’: u’192.168.1.220:6789/0’}], u’modified’: u’2017-11-27 10:57:00.018670’, u’fsid’: u’f2891898-aa3b-4bce-8bf1-668b8cf5b45a’, u’created’: u’2017-11-27 10:57:00.018670’}, u’health’: {u’detail’: [], u’timechecks’: {u’round_status’: u’finished’, u’epoch’: 4, u’round’: 0}, u’health’: {u’health_services’: [{u’mons’: [{u’last_updated’: u’2018-03-02 09:41:42.153833’, u’name’: u’node1’, u’avail_percent’: 89, u’kb_total’: 28797196, u’kb_avail’: 25738680, u’health’: u’HEALTH_OK’, u’kb_used’: 3058516, u’store_stats’: {u’bytes_total’: 15344382, u’bytes_log’: 2031616, u’last_updated’: u’0.000000’, u’bytes_misc’: 2031632, u’bytes_sst’: 11281134}}]}]}, u’overall_status’: u’HEALTH_WARN’, u’summary’: [{u’severity’: u’HEALTH_WARN’, u’summary’: u’too many PGs per OSD (428 > max 300)’}]}, u’fsid’: u’f2891898-aa3b-4bce-8bf1-668b8cf5b45a’, u’quorum_names’: [u’node1’], u’fsmap’: {u’up:standby’: 1, u’by_rank’: [{u’status’: u’up:active’, u’filesystem_id’: 1, u’name’: u’node2’, u’rank’: 0}], u’max’: 1, u’up’: 1, u’epoch’: 6, u’in’: 1, u’id’: 1}, u’osdmap’: {u’osdmap’: {u’full’: False, u’nearfull’: False, u’num_osds’: 2, u’num_up_osds’: 2, u’epoch’: 36, u’num_in_osds’: 2, u’num_remapped_pgs’: 0}}, u’pgmap’: {u’bytes_total’: 58976657408, u’num_pgs’: 428, u’data_bytes’: 143101344, u’bytes_used’: 17297178624, u’version’: 165507, u’pgs_by_state’: [{u’count’: 428, u’state_name’: u’active+clean’}], u’bytes_avail’: 41679478784}}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息