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:
- 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()
这样做有些繁琐,所以 Rados 、 Ioctx 和 Image 类可以当上下文管理器来用,它能自动关闭(见 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 donot use callbacks.
Error codes from librbd are turned into exceptions that subclassError. Almost all methods may raise Error(the base class of all rbd exceptions), PermissionErrorand IOError, in addition to those documented for themethod.
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 0 for object size)
- **stripe_count** (_int_) – objects to stripe over before loopingRaises :
TypeErrorRaises :InvalidArgumentRaises :ImageExistsRaises :FunctionNotSupportedRaises :ArgumentOutOfRange
- create(self, ioctx, name, size, order=None, old_format=True, features=0, stripe_unit=0, stripe_count=0)
- 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 thatis accessible by old clients, but can’tuse more advanced features like layering.
- **features** (_int_) – bitmask of features to enable
- **stripe_unit** (_int_) – stripe unit in bytes (default 0 for object size)
- **stripe_count** (_int_) – objects to stripe over before loopingRaises :
ImageExistsRaises :TypeErrorRaises :InvalidArgumentRaises :FunctionNotSupported
Parameters:ioctx (rados.Ioctx) – determines which RADOS pool is readReturns:list – a list of image names
- remove(self, ioctx, name)
- Delete an RBD image. This may take a long time, since it doesnot return until every object that comprises the image hasbeen deleted. Note that all snapshots must be deleted beforethe image can be removed. If there are snapshots left,ImageHasSnapshots is raised. If the image is stillopen, 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 removeRaises :
ImageNotFound, ImageBusy,ImageHasSnapshots
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 imageRaises :
ImageNotFound, ImageExists
Returns:a tuple of (major,minor,extra) components of thelibrbd version
This class represents an RBD image. It is used to perform I/O onthe image and interact with snapshots.
Note: Any method of this class may raise ImageNotFoundif the image has been deleted.
- breaklock(_self, client, cookie)
Release a lock held by another rados client.
- Release the resources used by this image object.
After this is called, this object should not be used.
- copy(self, dest_ioctx, dest_name, features=0, order=None, stripe_unit=0, stripe_count=0)
- Copy the image to another location.
Parameters:
- **dest_ioctx** (rados.Ioctx) – determines which pool to copy into
- **dest_name** (_str_) – the name of the copy
- **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 0 for object size)
- **stripe_count** (_int_) – objects to stripe over before loopingRaises :
TypeErrorRaises :InvalidArgumentRaises :ImageExistsRaises :FunctionNotSupportedRaises :ArgumentOutOfRange
Parameters:name (str) – the name of the snapshotRaises :ImageExists
- diffiterate(_self, offset, length, from_snapshot, iterate_cb, include_parent=True, whole_object=False)
- Iterate over the changed extents of an image.
This will call iterate_cb with three arguments:
(offset, length, exists)
where the changed extent starts at offset bytes, continues forlength bytes, and is full of data (if exists is True) or zeroes(if exists is False).
If from_snapshot is None, it is interpreted as the beginningof time and this generates all allocated extents.
The end version is whatever is currently selected (via set_snap)for the image.
iterate_cb may raise an exception, which will abort the diff and will bepropagated to the caller.
Raises InvalidArgument if from_snapshot is afterthe currently set snapshot.
Raises ImageNotFound if from_snapshot is not the nameof a snapshot of the image.
Parameters:
- **offset** (_int_) – start offset in bytes
- **length** (_int_) – size of region to report on, in bytes
- **from_snapshot** (_str or None_) – starting snapshot name, or None
- **iterate_cb** (_function acception arguments for offset,length, and exists_) – function to call for each extent
- **include_parent** (_bool_) – True if full history diff should include parent
- **whole_object** (_bool_) – True if diff extents should cover whole objectRaises :
InvalidArgument, IOError,ImageNotFound
- discard(self, offset, length)
Trim the range from the image. It will be logically filledwith zeroes.
- Gets the features bitmask of the image.
Returns:int - the features bitmask of the image
Returns:int - the flags bitmask of the image
- flatten(self)
Flatten clone image (copy all blocks from parent to child)
Block until all writes are fully flushed if caching is enabled.
Drop any cached data for the image.
- Gets the status of the image exclusive lock.
Returns:bool - true if the image is exclusively locked
Parameters:name (str) – the snapshot to checkReturns:bool - whether the snapshot is protectedRaises :IOError, ImageNotFound
Returns:list - a list of (pool name, image name) tuples
Returns:dict - contains the following keys:
- tag - the tag associated with the lock (everyadditional locker must use the same tag)
-
- exclusive - boolean indicating whether the
- lock is exclusive or shared
- lockers - a list of (client, cookie, address)tuples
Returns:SnapIterator
Raises :ImageBusy if a different client or cookie locked itImageExists if the same client and cookie locked it
- lockshared(_self, cookie, tag)
- Take a shared lock on the image. The tag must matchthat of the existing lockers, if any.
Raises :ImageBusy if a different client or cookie locked itImageExists if the same client and cookie locked it
Returns:bool - whether the image uses the old RBD format
- overlap(self)
- Gets the number of overlapping bytes between the image and its parentimage. If open to a snapshot, returns the overlap between the snapshotand the parent image.
Returns:int - the overlap in bytesRaises :ImageNotFound if the image doesn’t have a parent
Returns:tuple - (poolname,imagename,snapshotname) componentsof the parent imageRaises :ImageNotFound if the image doesn’t have a parent
- protectsnap(_self, name)
- Mark a snapshot as protected. This means it can’t be deleteduntil it is unprotected.
Parameters:name (str) – the snapshot to protectRaises :IOError, ImageNotFound
- read(self, offset, length, fadvise_flags=0)
- Read data from the image. Raises InvalidArgument ifpart of the range specified is outside the image.
Parameters:
- **offset** (_int_) – the offset to start reading at
- **length** (_int_) – how many bytes to read
- **fadvise_flags** (_int_) – fadvise flags for this readReturns:
str - the data readRaises :InvalidArgument, IOError
- rebuildobject_map(_self)
Rebuilds the object map for the image HEAD or currently set snapshot
- Delete a snapshot of the image.
Parameters:name (str) – the name of the snapshotRaises :IOError, ImageBusy
Parameters:
- **srcname** (_str_) – the src name of the snapshot
- **dstname** (_str_) – the dst name of the snapshotRaises :
ImageExists
Parameters:size (int) – the new size of the image
- rollbackto_snap(_self, name)
- Revert the image to its contents at a snapshot. This is apotentially expensive operation, since it rolls back eachobject individually.
Parameters:name (str) – the snapshot to rollback toRaises :IOError
- setsnap(_self, name)
- Set the snapshot to read from. Writes will raise ReadOnlyImagewhile a snapshot is set. Pass None to unset the snapshot(reads come from the current image) , and allow writing again.
Parameters:name (str or None) – the snapshot to read from, or None to unset the snapshot
Returns:the size of the image in bytes
- stat(self)
- Get information about the image. Currently parent pool andparent name are always -1 and ‘’.
Returns:dict - contains the following keys:
- size (int) - the size of the image in bytes
- obj_size (int) - the size of each object that comprises theimage
- num_objs (int) - the number of objects in the image
- order (int) - log_2(object_size)
- block_name_prefix (str) - the prefix of the RADOS objects usedto store the image
- parent_pool (int) - deprecated
- parent_name (str) - deprecated
See also format() and features().
- stripecount(_self)
Returns the stripe count used for the image.
Returns the stripe unit used for the image.
Release a lock on the image that was locked by this rados client.
- Mark a snapshot unprotected. This allows it to be deleted ifit was protected.
Parameters:name (str) – the snapshot to unprotectRaises :IOError, ImageNotFound
- updatefeatures(_self, features, enabled)
- Updates the features bitmask of the image by enabling/disablinga single feature. The feature must support the ability to bedynamically enabled/disabled.
Parameters:
- **features** (_int_) – feature bitmask to enable/disable
- **enabled** (_bool_) – whether to enable/disable the featureRaises :
InvalidArgument
- write(self, data, offset, fadvise_flags=0)
- Write data to the image. Raises InvalidArgument ifpart of the write would fall outside the image.
Parameters:
- **data** (_bytes_) – the data to be written
- **offset** (_int_) – where to start writing data
- **fadvise_flags** (_int_) – fadvise flags for this writeReturns:
int - the number of bytes writtenRaises :IncompleteWriteError, LogicError,InvalidArgument, IOError
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