1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
|
# libnbd Python bindings
# Copyright Red Hat
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
import nbd
import os
nbdkit = os.getenv("NBDKIT", "nbdkit")
buf = bytearray(512)
buf[10] = 1
buf[510] = 0x55
buf[511] = 0xAA
datafile = "510-pwrite.data"
with open(datafile, "wb") as f:
f.truncate(512)
h = nbd.NBD()
h.connect_command([nbdkit, "-s", "--exit-with-parent", "-v",
"file", datafile])
buf1 = nbd.Buffer.from_bytearray(buf)
cookie = h.aio_pwrite(buf1, 0, flags=nbd.CMD_FLAG_FUA)
while not h.aio_command_completed(cookie):
h.poll(-1)
buf2 = nbd.Buffer(512)
cookie = h.aio_pread(buf2, 0)
while not h.aio_command_completed(cookie):
h.poll(-1)
assert buf == buf2.to_bytearray()
# Check that .from_bytearray() defaults to copying
buf[511] = 0x55
assert buf != buf1.to_bytearray()
buf[511] = 0xAA
assert buf == buf1.to_bytearray()
with open(datafile, "rb") as f:
content = f.read()
assert buf == content
# Also check that an uninitialized buffer doesn't leak heap contents
buf3 = nbd.Buffer(512)
cookie = h.aio_pwrite(buf3, 0, flags=nbd.CMD_FLAG_FUA)
while not h.aio_command_completed(cookie):
h.poll(-1)
with open(datafile, "rb") as f:
content = f.read()
assert nbd.Buffer.from_bytearray(content).is_zero()
# It is also possible to write any buffer-like object.
# While the write is pending, the buffer cannot be resized
cookie = h.aio_pwrite(buf, 0, flags=nbd.CMD_FLAG_FUA)
try:
buf.pop()
assert False
except BufferError:
pass
while not h.aio_command_completed(cookie):
h.poll(-1)
buf.append(buf.pop())
with open(datafile, "rb") as f:
content = f.read()
assert buf == content
os.unlink(datafile)
|