4 # Test bitmap-sync backups (incremental, differential, and partials)
6 # Copyright (c) 2019 John Snow for Red Hat, Inc.
8 # This program is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 2 of the License, or
11 # (at your option) any later version.
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with this program. If not, see <http://www.gnu.org/licenses/>.
21 # owner=jsnow@redhat.com
27 from iotests import log, qemu_img
29 SIZE = 64 * 1024 * 1024
30 GRANULARITY = 64 * 1024
34 def __init__(self, byte, offset, size=GRANULARITY):
39 def bits(self, granularity):
40 lower = self.offset // granularity
41 upper = (self.offset + self.size - 1) // granularity
42 return set(range(lower, upper + 1))
46 """Grouping of Pattern objects. Initialize with an iterable of Patterns."""
47 def __init__(self, patterns):
48 self.patterns = patterns
50 def bits(self, granularity):
51 """Calculate the unique bits dirtied by this pattern grouping"""
53 for pattern in self.patterns:
54 res |= pattern.bits(granularity)
61 Pattern('0x49', 0x0000000),
62 Pattern('0x6c', 0x0100000), # 1M
63 Pattern('0x6f', 0x2000000), # 32M
64 Pattern('0x76', 0x3ff0000)]), # 64M - 64K
66 # Batch 1: 6 clusters (3 new)
67 Pattern('0x65', 0x0000000), # Full overwrite
68 Pattern('0x77', 0x00f8000), # Partial-left (1M-32K)
69 Pattern('0x72', 0x2008000), # Partial-right (32M+32K)
70 Pattern('0x69', 0x3fe0000)]), # Adjacent-left (64M - 128K)
72 # Batch 2: 7 clusters (3 new)
73 Pattern('0x74', 0x0010000), # Adjacent-right
74 Pattern('0x69', 0x00e8000), # Partial-left (1M-96K)
75 Pattern('0x6e', 0x2018000), # Partial-right (32M+96K)
76 Pattern('0x67', 0x3fe0000,
77 2*GRANULARITY)]), # Overwrite [(64M-128K)-64M)
79 # Batch 3: 8 clusters (5 new)
80 # Carefully chosen such that nothing re-dirties the one cluster
81 # that copies out successfully before failure in Group #1.
82 Pattern('0xaa', 0x0010000,
83 3*GRANULARITY), # Overwrite and 2x Adjacent-right
84 Pattern('0xbb', 0x00d8000), # Partial-left (1M-160K)
85 Pattern('0xcc', 0x2028000), # Partial-right (32M+160K)
86 Pattern('0xdd', 0x3fc0000)]), # New; leaving a gap to the right
91 def __init__(self, granularity=GRANULARITY):
93 self.granularity = granularity
95 def dirty_bits(self, bits):
96 self._bits |= set(bits)
98 def dirty_group(self, n):
99 self.dirty_bits(GROUPS[n].bits(self.granularity))
104 def clear_bits(self, bits):
105 self._bits -= set(bits)
107 def clear_bit(self, bit):
108 self.clear_bits({bit})
110 def clear_group(self, n):
111 self.clear_bits(GROUPS[n].bits(self.granularity))
115 return sorted(self.bits)[0]
123 return len(self.bits)
125 def compare(self, qmp_bitmap):
127 Print a nice human-readable message checking that a bitmap as reported
128 by the QMP interface has as many bits set as we expect it to.
131 name = qmp_bitmap.get('name', '(anonymous)')
132 log("= Checking Bitmap {:s} =".format(name))
135 have = qmp_bitmap['count'] // qmp_bitmap['granularity']
137 log("expecting {:d} dirty sectors; have {:d}. {:s}".format(
138 want, have, "OK!" if want == have else "ERROR!"))
143 """Represents, vaguely, a drive attached to a VM.
144 Includes format, graph, and device information."""
146 def __init__(self, path, vm=None):
153 def img_create(self, fmt, size):
156 iotests.qemu_img_create('-f', self.fmt, self.path, str(self.size))
158 def create_target(self, name, fmt, size):
159 basename = os.path.basename(self.path)
160 file_node_name = "file_{}".format(basename)
163 log(vm.command('blockdev-create', job_id='bdc-file-job',
166 'filename': self.path,
169 vm.run_job('bdc-file-job')
170 log(vm.command('blockdev-add', driver='file',
171 node_name=file_node_name, filename=self.path))
173 log(vm.command('blockdev-create', job_id='bdc-fmt-job',
176 'file': file_node_name,
179 vm.run_job('bdc-fmt-job')
180 log(vm.command('blockdev-add', driver=fmt,
182 file=file_node_name))
187 def blockdev_backup(vm, device, target, sync, **kwargs):
188 # Strip any arguments explicitly nulled by the caller:
189 kwargs = {key: val for key, val in kwargs.items() if val is not None}
190 result = vm.qmp_log('blockdev-backup',
194 filter_node_name='backup-top',
198 def blockdev_backup_mktarget(drive, target_id, filepath, sync, **kwargs):
199 target_drive = Drive(filepath, vm=drive.vm)
200 target_drive.create_target(target_id, drive.fmt, drive.size)
201 blockdev_backup(drive.vm, drive.node, target_id, sync, **kwargs)
203 def reference_backup(drive, n, filepath):
204 log("--- Reference Backup #{:d} ---\n".format(n))
205 target_id = "ref_target_{:d}".format(n)
206 job_id = "ref_backup_{:d}".format(n)
207 blockdev_backup_mktarget(drive, target_id, filepath, "full",
209 drive.vm.run_job(job_id, auto_dismiss=True)
212 def backup(drive, n, filepath, sync, **kwargs):
213 log("--- Test Backup #{:d} ---\n".format(n))
214 target_id = "backup_target_{:d}".format(n)
215 job_id = "backup_{:d}".format(n)
216 kwargs.setdefault('auto-finalize', False)
217 blockdev_backup_mktarget(drive, target_id, filepath, sync,
218 job_id=job_id, **kwargs)
221 def perform_writes(drive, n, filter_node_name=None):
222 log("--- Write #{:d} ---\n".format(n))
223 for pattern in GROUPS[n].patterns:
224 cmd = "write -P{:s} 0x{:07x} 0x{:x}".format(
229 log(drive.vm.hmp_qemu_io(filter_node_name or drive.node, cmd))
230 bitmaps = drive.vm.query_bitmaps()
231 log({'bitmaps': bitmaps}, indent=2)
236 def compare_images(image, reference, baseimg=None, expected_match=True):
238 Print a nice human-readable message comparing these images.
240 expected_ret = 0 if expected_match else 1
242 assert qemu_img("rebase", "-u", "-b", baseimg, '-F', iotests.imgfmt,
244 ret = qemu_img("compare", image, reference)
245 log('qemu_img compare "{:s}" "{:s}" ==> {:s}, {:s}'.format(
247 "Identical" if ret == 0 else "Mismatch",
248 "OK!" if ret == expected_ret else "ERROR!"),
249 filters=[iotests.filter_testfiles])
251 def test_bitmap_sync(bsync_mode, msync_mode='bitmap', failure=None):
253 Test bitmap backup routines.
255 :param bsync_mode: Is the Bitmap Sync mode, and can be any of:
256 - on-success: This is the "incremental" style mode. Bitmaps are
257 synchronized to what was copied out only on success.
258 (Partial images must be discarded.)
259 - never: This is the "differential" style mode.
260 Bitmaps are never synchronized.
261 - always: This is a "best effort" style mode.
262 Bitmaps are always synchronized, regardless of failure.
263 (Partial images must be kept.)
265 :param msync_mode: The mirror sync mode to use for the first backup.
267 - bitmap: Backups based on bitmap manifest.
268 - full: Full backups.
269 - top: Full backups of the top layer only.
271 :param failure: Is the (optional) failure mode, and can be any of:
272 - None: No failure. Test the normative path. Default.
273 - simulated: Cancel the job right before it completes.
274 This also tests writes "during" the job.
275 - intermediate: This tests a job that fails mid-process and produces
276 an incomplete backup. Testing limitations prevent
277 testing competing writes.
279 with iotests.FilePath(
280 'img', 'bsync1', 'bsync2', 'fbackup0', 'fbackup1', 'fbackup2') as \
281 (img_path, bsync1, bsync2, fbackup0, fbackup1, fbackup2), \
284 mode = "Mode {:s}; Bitmap Sync {:s}".format(msync_mode, bsync_mode)
285 preposition = "with" if failure else "without"
286 cond = "{:s} {:s}".format(preposition,
287 "{:s} failure".format(failure) if failure
289 log("\n=== {:s} {:s} ===\n".format(mode, cond))
291 log('--- Preparing image & VM ---\n')
292 drive0 = Drive(img_path, vm=vm)
293 drive0.img_create(iotests.imgfmt, SIZE)
294 vm.add_device("{},id=scsi0".format(iotests.get_virtio_scsi_device()))
299 'filename': drive0.path
302 if failure == 'intermediate':
304 'driver': 'blkdebug',
305 'image': file_config,
307 'event': 'flush_to_disk',
319 'immediately': False,
324 drive0.node = 'drive0'
325 vm.qmp_log('blockdev-add',
326 filters=[iotests.filter_qmp_testfiles],
327 node_name=drive0.node,
332 # 0 - Writes and Reference Backup
333 perform_writes(drive0, 0)
334 reference_backup(drive0, 0, fbackup0)
335 log('--- Add Bitmap ---\n')
336 vm.qmp_log("block-dirty-bitmap-add", node=drive0.node,
337 name="bitmap0", granularity=GRANULARITY)
339 ebitmap = EmulatedBitmap()
341 # 1 - Writes and Reference Backup
342 bitmaps = perform_writes(drive0, 1)
343 ebitmap.dirty_group(1)
344 bitmap = vm.get_bitmap(drive0.node, 'bitmap0', bitmaps=bitmaps)
345 ebitmap.compare(bitmap)
346 reference_backup(drive0, 1, fbackup1)
348 # 1 - Test Backup (w/ Optional induced failure)
349 if failure == 'intermediate':
350 # Activate blkdebug induced failure for second-to-next read
351 log(vm.hmp_qemu_io(drive0.node, 'flush'))
353 job = backup(drive0, 1, bsync1, msync_mode,
354 bitmap="bitmap0", bitmap_mode=bsync_mode)
357 """Issue writes while the job is open to test bitmap divergence."""
358 # Note: when `failure` is 'intermediate', this isn't called.
360 bitmaps = perform_writes(drive0, 2, filter_node_name='backup-top')
361 # Named bitmap (static, should be unchanged)
362 ebitmap.compare(vm.get_bitmap(drive0.node, 'bitmap0',
364 # Anonymous bitmap (dynamic, shows new writes)
365 anonymous = EmulatedBitmap()
366 anonymous.dirty_group(2)
367 anonymous.compare(vm.get_bitmap(drive0.node, '', recording=True,
370 # Simulate the order in which this will happen:
371 # group 1 gets cleared first, then group two gets written.
372 if ((bsync_mode == 'on-success' and not failure) or
373 (bsync_mode == 'always')):
375 ebitmap.dirty_group(2)
377 vm.run_job(job, auto_dismiss=True, auto_finalize=False,
378 pre_finalize=_callback,
379 cancel=(failure == 'simulated'))
380 bitmaps = vm.query_bitmaps()
381 log({'bitmaps': bitmaps}, indent=2)
384 if bsync_mode == 'always' and failure == 'intermediate':
385 # TOP treats anything allocated as dirty, expect to see:
386 if msync_mode == 'top':
387 ebitmap.dirty_group(0)
389 # We manage to copy one sector (one bit) before the error.
390 ebitmap.clear_bit(ebitmap.first_bit)
392 # Full returns all bits set except what was copied/skipped
393 if msync_mode == 'full':
394 fail_bit = ebitmap.first_bit
396 ebitmap.dirty_bits(range(fail_bit, SIZE // GRANULARITY))
398 ebitmap.compare(vm.get_bitmap(drive0.node, 'bitmap0', bitmaps=bitmaps))
400 # 2 - Writes and Reference Backup
401 bitmaps = perform_writes(drive0, 3)
402 ebitmap.dirty_group(3)
403 ebitmap.compare(vm.get_bitmap(drive0.node, 'bitmap0', bitmaps=bitmaps))
404 reference_backup(drive0, 2, fbackup2)
406 # 2 - Bitmap Backup (In failure modes, this is a recovery.)
407 job = backup(drive0, 2, bsync2, "bitmap",
408 bitmap="bitmap0", bitmap_mode=bsync_mode)
409 vm.run_job(job, auto_dismiss=True, auto_finalize=False)
410 bitmaps = vm.query_bitmaps()
411 log({'bitmaps': bitmaps}, indent=2)
413 if bsync_mode != 'never':
415 ebitmap.compare(vm.get_bitmap(drive0.node, 'bitmap0', bitmaps=bitmaps))
417 log('--- Cleanup ---\n')
418 vm.qmp_log("block-dirty-bitmap-remove",
419 node=drive0.node, name="bitmap0")
420 bitmaps = vm.query_bitmaps()
421 log({'bitmaps': bitmaps}, indent=2)
425 log('--- Verification ---\n')
426 # 'simulated' failures will actually all pass here because we canceled
427 # while "pending". This is actually undefined behavior,
428 # don't rely on this to be true!
429 compare_images(bsync1, fbackup1, baseimg=fbackup0,
430 expected_match=failure != 'intermediate')
431 if not failure or bsync_mode == 'always':
432 # Always keep the last backup on success or when using 'always'
436 compare_images(bsync2, fbackup2, baseimg=base)
437 compare_images(img_path, fbackup2)
440 def test_backup_api():
442 Test malformed and prohibited invocations of the backup API.
444 with iotests.FilePath('img', 'bsync1') as (img_path, backup_path), \
447 log("\n=== API failure tests ===\n")
448 log('--- Preparing image & VM ---\n')
449 drive0 = Drive(img_path, vm=vm)
450 drive0.img_create(iotests.imgfmt, SIZE)
451 vm.add_device("{},id=scsi0".format(iotests.get_virtio_scsi_device()))
456 'filename': drive0.path
459 drive0.node = 'drive0'
460 vm.qmp_log('blockdev-add',
461 filters=[iotests.filter_qmp_testfiles],
462 node_name=drive0.node,
467 target0 = Drive(backup_path, vm=vm)
468 target0.create_target("backup_target", drive0.fmt, drive0.size)
471 vm.qmp_log("block-dirty-bitmap-add", node=drive0.node,
472 name="bitmap0", granularity=GRANULARITY)
475 log('-- Testing invalid QMP commands --\n')
479 None: ['on-success', 'always', 'never', None],
480 'bitmap404': ['on-success', 'always', 'never', None],
481 'bitmap0': ['always', 'never']
484 None: ['on-success', 'always', 'never', None],
485 'bitmap404': ['on-success', 'always', 'never', None],
489 None: ['on-success', 'always', 'never'],
490 'bitmap404': ['on-success', 'always', 'never', None],
491 'bitmap0': ['never', None],
494 None: ['on-success', 'always', 'never'],
495 'bitmap404': ['on-success', 'always', 'never', None],
496 'bitmap0': ['never', None],
499 None: ['on-success', 'always', 'never'],
500 'bitmap404': ['on-success', 'always', 'never', None],
501 'bitmap0': ['on-success', 'always', 'never', None],
505 # Dicts, as always, are not stably-ordered prior to 3.7, so use tuples:
506 for sync_mode in ('incremental', 'bitmap', 'full', 'top', 'none'):
507 log("-- Sync mode {:s} tests --\n".format(sync_mode))
508 for bitmap in (None, 'bitmap404', 'bitmap0'):
509 for policy in error_cases[sync_mode][bitmap]:
510 blockdev_backup(drive0.vm, drive0.node, "backup_target",
511 sync_mode, job_id='api_job',
512 bitmap=bitmap, bitmap_mode=policy)
517 for bsync_mode in ("never", "on-success", "always"):
518 for failure in ("simulated", "intermediate", None):
519 test_bitmap_sync(bsync_mode, "bitmap", failure)
521 for sync_mode in ('full', 'top'):
522 for bsync_mode in ('on-success', 'always'):
523 for failure in ('simulated', 'intermediate', None):
524 test_bitmap_sync(bsync_mode, sync_mode, failure)
528 if __name__ == '__main__':
529 iotests.script_main(main, supported_fmts=['qcow2'],
530 supported_protocols=['file'])