Librbd 的 Python 接口

rbd 的 python 模块为 RBD 映像提供了类似文件的访问方法。

实例:创建一映像并写入

要使用 rbd ,必须先连接 RADOS 并打开 IO 上下文:

cluster = rados.Rados(conffile='my_ceph.conf')
cluster.connect()
ioctx = cluster.open_ioctx('mypool')

然后实例化 :class:rbd.RBD 对象,用它来创建映像:

rbd_inst = rbd.RBD()
size = 4 * 1024**3  # 4 GiB
rbd_inst.create(ioctx, 'myimage', size)

要在映像上进行 I/O 操作,需实例化 :class:rbd.Image 对象:

image = rbd.Image(ioctx, 'myimage')
data = 'foo' * 200
image.write(data, 0)

上面的代码向映像前面写入了 600 字节的 foo 字符串。注意数据不能是 :type:unicode , librbd 不能如何处理大于 :c:type:char 的字符串。

最后,关闭映像、 IO 上下文、和到 RADOS 的连接。

image.close()
ioctx.close()
cluster.shutdown()

安全起见,每个调用都应该封装到单独的 :finally 块内。

cluster = rados.Rados(conffile='my_ceph_conf')
try:
    cluster.connect()
    ioctx = cluster.open_ioctx('my_pool')
    try:
        rbd_inst = rbd.RBD()
        size = 4 * 1024**3  # 4 GiB
        rbd_inst.create(ioctx, 'myimage', size)
        image = rbd.Image(ioctx, 'myimage')
        try:
            data = 'foo' * 200
            image.write(data, 0)
        finally:
            image.close()
    finally:
        ioctx.close()
finally:
    cluster.shutdown()

这样做有些繁琐,所以 RadosIoctxImage 类可以当上下文管理器来用,它能自动关闭(见 PEP 343 )。当上下文管理器用时,上面的实例可以写成:

with rados.Rados(conffile='my_ceph.conf') as cluster:
    with cluster.open_ioctx('mypool') as ioctx:
        rbd_inst = rbd.RBD()
        size = 4 * 1024**3  # 4 GiB
        rbd_inst.create(ioctx, 'myimage', size)
        with rbd.Image(ioctx, 'myimage') as image:
            data = 'foo' * 200
            image.write(data, 0)

API 参考

This module is a thin wrapper around librbd.

It currently provides all the synchronous methods of librbd that do not use callbacks.

Error codes from librbd are turned into exceptions that subclass Error. Almost all methods may raise Error (the base class of all rbd exceptions), PermissionError and IOError, in addition to those documented for the method.

class rbd.RBD

This class wraps librbd CRUD functions.

clone

Clone a parent rbd snapshot into a COW sparse child.

Parameters
  • p_ioctx – the parent context that represents the parent snap

  • p_name – the parent image name

  • p_snapname – the parent image snapshot name

  • c_ioctx – the child context that represents the new clone

  • c_name – the clone (child) name

  • features (int) – bitmask of features to enable; if set, must include layering

  • order (int) – the image is split into (2**order) byte objects

  • stripe_unit (int) – stripe unit in bytes (default None to let librbd decide)

  • stripe_count (int) – objects to stripe over before looping

  • data_pool (str) – optional separate pool for data blocks

Raises

TypeError

Raises

InvalidArgument

Raises

ImageExists

Raises

FunctionNotSupported

Raises

ArgumentOutOfRange

config_get

Get a pool-level configuration override.

Parameters
  • ioctx (rados.Ioctx) – determines which RADOS pool is read

  • key (str) – key

Returns

str - value

config_list

List pool-level config overrides.

Returns

ConfigPoolIterator

config_remove

Remove a pool-level configuration override.

Parameters
  • ioctx (rados.Ioctx) – determines which RADOS pool is read

  • key (str) – key

Returns

str - value

config_set

Get a pool-level configuration override.

Parameters
  • ioctx (rados.Ioctx) – determines which RADOS pool is read

  • key (str) – key

  • value (str) – value

create

Create an rbd image.

Parameters
  • ioctx (rados.Ioctx) – the context in which to create the image

  • name (str) – what the image is called

  • size (int) – how big the image is in bytes

  • order (int) – the image is split into (2**order) byte objects

  • old_format (bool) – whether to create an old-style image that is accessible by old clients, but can’t use more advanced features like layering.

  • features (int) – bitmask of features to enable

  • stripe_unit (int) – stripe unit in bytes (default None to let librbd decide)

  • stripe_count (int) – objects to stripe over before looping

  • data_pool (str) – optional separate pool for data blocks

Raises

ImageExists

Raises

TypeError

Raises

InvalidArgument

Raises

FunctionNotSupported

features_from_string

Get features bitmask from str, if str_features is empty, it will return RBD_FEATURES_DEFAULT.

Parameters

str_features (str) – feature str

Returns

int - the features bitmask of the image

Raises

InvalidArgument

features_to_string

Convert features bitmask to str.

Parameters

features (int) – feature bitmask

Returns

str - the features str of the image

Raises

InvalidArgument

group_create

Create a group.

Parameters
  • ioctx (rados.Ioctx) – determines which RADOS pool is used

  • name (str) – the name of the group

Raises

ObjectExists

Raises

InvalidArgument

Raises

FunctionNotSupported

group_list

List groups.

Parameters

ioctx (rados.Ioctx) – determines which RADOS pool is read

Returns

list – a list of groups names

Raises

FunctionNotSupported

group_remove

Delete an RBD group. This may take a long time, since it does not return until every image in the group has been removed from the group.

Parameters
  • ioctx (rados.Ioctx) – determines which RADOS pool the group is in

  • name (str) – the name of the group to remove

Raises

ObjectNotFound

Raises

InvalidArgument

Raises

FunctionNotSupported

group_rename

Rename an RBD group.

Parameters
  • ioctx (rados.Ioctx) – determines which RADOS pool the group is in

  • src (str) – the current name of the group

  • dest (str) – the new name of the group

Raises

ObjectExists

Raises

ObjectNotFound

Raises

InvalidArgument

Raises

FunctionNotSupported

list

List image names.

Parameters

ioctx (rados.Ioctx) – determines which RADOS pool is read

Returns

list – a list of image names

list2

Iterate over the images in the pool.

Parameters

ioctx (rados.Ioctx) – determines which RADOS pool the image is in

Returns

ImageIterator

migration_abort

Cancel a previously started but interrupted migration.

Parameters
  • ioctx (rados.Ioctx) – determines which RADOS pool the image is in

  • image_name (str) – the name of the image

  • on_progress (callback function) – optional progress callback function

Raises

ImageNotFound

migration_commit

Commit an executed RBD image migration.

Parameters
  • ioctx (rados.Ioctx) – determines which RADOS pool the image is in

  • image_name (str) – the name of the image

  • on_progress (callback function) – optional progress callback function

Raises

ImageNotFound

migration_execute

Execute a prepared RBD image migration.

Parameters
  • ioctx (rados.Ioctx) – determines which RADOS pool the image is in

  • image_name (str) – the name of the image

  • on_progress (callback function) – optional progress callback function

Raises

ImageNotFound

migration_prepare

Prepare an RBD image migration.

Parameters
  • ioctx (rados.Ioctx) – determines which RADOS pool the image is in

  • image_name – the current name of the image

  • dest_ioctx (rados.Ioctx) – determines which pool to migration into

  • dest_image_name (str) – the name of the destination image (may be the same image)

  • features (int) – bitmask of features to enable; if set, must include layering

  • order (int) – the image is split into (2**order) byte objects

  • stripe_unit (int) – stripe unit in bytes (default None to let librbd decide)

  • stripe_count (int) – objects to stripe over before looping

  • data_pool (str) – optional separate pool for data blocks

Raises

TypeError

Raises

InvalidArgument

Raises

ImageExists

Raises

FunctionNotSupported

Raises

ArgumentOutOfRange

migration_status

Return RBD image migration status.

Parameters
  • ioctx (rados.Ioctx) – determines which RADOS pool the image is in

  • image_name (str) – the name of the image

Returns

dict - contains the following keys:

  • source_pool_id (int) - source image pool id

  • source_pool_namespace (str) - source image pool namespace

  • source_image_name (str) - source image name

  • source_image_id (str) - source image id

  • dest_pool_id (int) - destination image pool id

  • dest_pool_namespace (str) - destination image pool namespace

  • dest_image_name (str) - destination image name

  • dest_image_id (str) - destination image id

  • state (int) - current migration state

  • state_description (str) - migration state description

Raises

ImageNotFound

mirror_image_info_list

Iterate over the mirror image instance ids of a pool.

Parameters
  • ioctx (rados.Ioctx) – determines which RADOS pool is read

  • mode_filter – list images in this image mirror mode

Returns

MirrorImageInfoIterator

mirror_image_instance_id_list

Iterate over the mirror image instance ids of a pool.

Parameters

ioctx (rados.Ioctx) – determines which RADOS pool is read

Returns

MirrorImageInstanceIdIterator

mirror_image_status_list

Iterate over the mirror image statuses of a pool.

Parameters

ioctx (rados.Ioctx) – determines which RADOS pool is read

Returns

MirrorImageStatusIterator

mirror_image_status_summary

Get mirror image status summary of a pool.

Parameters

ioctx (rados.Ioctx) – determines which RADOS pool is read

Returns

list - a list of (state, count) tuples

mirror_mode_get

Get pool mirror mode.

Parameters

ioctx (rados.Ioctx) – determines which RADOS pool is read

Returns

int - pool mirror mode

mirror_mode_set

Set pool mirror mode.

Parameters
  • ioctx (rados.Ioctx) – determines which RADOS pool is written

  • mirror_mode (int) – mirror mode to set

mirror_peer_add

Add mirror peer.

Parameters
  • ioctx (rados.Ioctx) – determines which RADOS pool is used

  • site_name (str) – mirror peer site name

  • client_name (str) – mirror peer client name

  • direction (int) – the direction of the mirroring

Returns

str - peer uuid

mirror_peer_bootstrap_create

Creates a new RBD mirroring bootstrap token for an external cluster.

Parameters

ioctx (rados.Ioctx) – determines which RADOS pool is written

Returns

str - bootstrap token

mirror_peer_bootstrap_import

Import a bootstrap token from an external cluster to auto-configure the mirror peer.

Parameters
  • ioctx (rados.Ioctx) – determines which RADOS pool is written

  • direction (int) – mirror peer direction

  • token (str) – bootstrap token

mirror_peer_get_attributes

Get optional mirror peer attributes

Parameters
  • ioctx (rados.Ioctx) – determines which RADOS pool is written

  • uuid (str) – uuid of the mirror peer

Returns

dict - contains the following keys:

  • mon_host (str) - monitor addresses

  • key (str) - CephX key

mirror_peer_list

Iterate over the peers of a pool.

Parameters

ioctx (rados.Ioctx) – determines which RADOS pool is read

Returns

MirrorPeerIterator

mirror_peer_remove

Remove mirror peer.

Parameters
  • ioctx (rados.Ioctx) – determines which RADOS pool is used

  • uuid (str) – peer uuid

mirror_peer_set_attributes

Set optional mirror peer attributes

Parameters
  • ioctx (rados.Ioctx) – determines which RADOS pool is written

  • uuid (str) – uuid of the mirror peer

  • attributes (dict) – ‘mon_host’ and ‘key’ attributes

mirror_peer_set_client

Set mirror peer client name

Parameters
  • ioctx (rados.Ioctx) – determines which RADOS pool is written

  • uuid (str) – uuid of the mirror peer

  • client_name (str) – client name of the mirror peer to set

mirror_peer_set_cluster
mirror_peer_set_name

Set mirror peer site name

Parameters
  • ioctx (rados.Ioctx) – determines which RADOS pool is written

  • uuid (str) – uuid of the mirror peer

  • site_name (str) – site name of the mirror peer to set

mirror_site_name_get

Get the local cluster’s friendly site name

Parameters

rados – cluster connection

Returns

str - local site name

mirror_site_name_set

Set the local cluster’s friendly site name

Parameters
  • rados – cluster connection

  • site_name – friendly site name

mirror_uuid_get

Get pool mirror uuid

Parameters

ioctx (rados.Ioctx) – determines which RADOS pool is read

Returns

ste - pool mirror uuid

namespace_create

Create an RBD namespace within a pool

Parameters
  • ioctx (rados.Ioctx) – determines which RADOS pool

  • name (str) – namespace name

namespace_exists

Verifies if a namespace exists within a pool

Parameters
  • ioctx (rados.Ioctx) – determines which RADOS pool

  • name (str) – namespace name

Returns

bool - true if namespace exists

namespace_list

List all namespaces within a pool

Parameters

ioctx (rados.Ioctx) – determines which RADOS pool

Returns

list - collection of namespace names

namespace_remove

Remove an RBD namespace from a pool

Parameters
  • ioctx (rados.Ioctx) – determines which RADOS pool

  • name (str) – namespace name

pool_init

Initialize an RBD pool :param ioctx: determines which RADOS pool :type ioctx: rados.Ioctx :param force: force init :type force: bool

pool_metadata_get

Get pool metadata for the given key.

Parameters
  • ioctx (rados.Ioctx) – determines which RADOS pool is read

  • key (str) – metadata key

Returns

str - metadata value

pool_metadata_list

List pool metadata.

Returns

PoolMetadataIterator

pool_metadata_remove

Remove pool metadata for the given key.

Parameters
  • ioctx (rados.Ioctx) – determines which RADOS pool is read

  • key (str) – metadata key

Returns

str - metadata value

pool_metadata_set

Set pool metadata for the given key.

Parameters
  • ioctx (rados.Ioctx) – determines which RADOS pool is read

  • key (str) – metadata key

  • value (str) – metadata value

pool_stats_get

Return RBD pool stats

Parameters

ioctx (rados.Ioctx) – determines which RADOS pool

Returns

dict - contains the following keys:

  • image_count (int) - image count

  • image_provisioned_bytes (int) - image total HEAD provisioned bytes

  • image_max_provisioned_bytes (int) - image total max provisioned bytes

  • image_snap_count (int) - image snap count

  • trash_count (int) - trash image count

  • trash_provisioned_bytes (int) - trash total HEAD provisioned bytes

  • trash_max_provisioned_bytes (int) - trash total max provisioned bytes

  • trash_snap_count (int) - trash snap count

remove

Delete an RBD image. This may take a long time, since it does not return until every object that comprises the image has been deleted. Note that all snapshots must be deleted before the image can be removed. If there are snapshots left, ImageHasSnapshots is raised. If the image is still open, or the watch from a crashed client has not expired, ImageBusy is raised.

Parameters
  • ioctx (rados.Ioctx) – determines which RADOS pool the image is in

  • name (str) – the name of the image to remove

  • on_progress (callback function) – optional progress callback function

Raises

ImageNotFound, ImageBusy, ImageHasSnapshots

rename

Rename an RBD image.

Parameters
  • ioctx (rados.Ioctx) – determines which RADOS pool the image is in

  • src (str) – the current name of the image

  • dest (str) – the new name of the image

Raises

ImageNotFound, ImageExists

trash_get

Retrieve RBD image info from trash.

Parameters
  • ioctx (rados.Ioctx) – determines which RADOS pool the image is in

  • image_id (str) – the id of the image to restore

Returns

dict - contains the following keys:

  • id (str) - image id

  • name (str) - image name

  • source (str) - source of deletion

  • deletion_time (datetime) - time of deletion

  • deferment_end_time (datetime) - time that an image is allowed to be removed from trash

Raises

ImageNotFound

trash_list

List all entries from trash.

Parameters

ioctx (rados.Ioctx) – determines which RADOS pool the image is in

Returns

TrashIterator

trash_move

Move an RBD image to the trash.

Parameters
  • ioctx (rados.Ioctx) – determines which RADOS pool the image is in

  • name (str) – the name of the image to remove

  • delay (int) – time delay in seconds before the image can be deleted from trash

Raises

ImageNotFound

trash_purge

Delete RBD images from trash in bulk.

By default it removes images with deferment end time less than now.

The timestamp is configurable, e.g. delete images that have expired a week ago.

If the threshold is used it deletes images until X% pool usage is met.

Parameters
  • ioctx (rados.Ioctx) – determines which RADOS pool the image is in

  • expire_ts (datetime) – timestamp for images to be considered as expired (UTC)

  • threshold (float) – percentage of pool usage to be met (0 to 1)

trash_remove

Delete an RBD image from trash. If image deferment time has not expired PermissionError is raised.

Parameters
  • ioctx (rados.Ioctx) – determines which RADOS pool the image is in

  • image_id (str) – the id of the image to remove

  • force (bool) – force remove even if deferment time has not expired

  • on_progress (callback function) – optional progress callback function

Raises

ImageNotFound, PermissionError

trash_restore

Restore an RBD image from trash.

Parameters
  • ioctx (rados.Ioctx) – determines which RADOS pool the image is in

  • image_id (str) – the id of the image to restore

  • name (str) – the new name of the restored image

Raises

ImageNotFound

version

Get the version number of the librbd C library.

Returns

a tuple of (major, minor, extra) components of the librbd version

class rbd.Image(ioctx, name=None, snapshot=None, read_only=False, image_id=None)

This class represents an RBD image. It is used to perform I/O on the image and interact with snapshots.

Note: Any method of this class may raise ImageNotFound if the image has been deleted.

close(self)

Release the resources used by this image object.

After this is called, this object should not be used.

require_not_closed(self)

Checks if the Image is not closed

Raises

InvalidArgument

class rbd.SnapIterator(Image image)

Iterator over snapshot info for an image.

Yields a dictionary containing information about a snapshot.

Keys are:

  • id (int) - numeric identifier of the snapshot

  • size (int) - size of the image at the time of snapshot (in bytes)

  • name (str) - name of the snapshot

  • namespace (int) - enum for snap namespace

  • group (dict) - optional for group namespace snapshots

  • trash (dict) - optional for trash namespace snapshots

  • mirror (dict) - optional for mirror namespace snapshots