4 # Tests for incremental drive-backup
6 # Copyright (C) 2015 John Snow for Red Hat, Inc.
10 # This program is free software; you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 2 of the License, or
13 # (at your option) any later version.
15 # This program is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # GNU General Public License for more details.
20 # You should have received a copy of the GNU General Public License
21 # along with this program. If not, see <http://www.gnu.org/licenses/>.
26 from iotests import try_remove
29 def io_write_patterns(img, patterns):
30 for pattern in patterns:
31 iotests.qemu_io('-c', 'write -P%s %s %s' % pattern, img)
34 def transaction_action(action, **kwargs):
37 'data': dict((k.replace('_', '-'), v) for k, v in kwargs.items())
41 def transaction_bitmap_clear(node, name, **kwargs):
42 return transaction_action('block-dirty-bitmap-clear',
43 node=node, name=name, **kwargs)
46 def transaction_drive_backup(device, target, **kwargs):
47 return transaction_action('drive-backup', job_id=device, device=device,
48 target=target, **kwargs)
52 def __init__(self, name, drive):
58 def base_target(self):
59 return (self.drive['backup'], None)
61 def new_target(self, num=None):
65 base = os.path.join(iotests.test_dir,
66 "%s.%s." % (self.drive['id'], self.name))
67 suff = "%i.%s" % (num, self.drive['fmt'])
68 target = base + "inc" + suff
69 reference = base + "ref" + suff
70 self.backups.append((target, reference))
71 return (target, reference)
73 def last_target(self):
75 return self.backups[-1]
76 return self.base_target()
79 for image in self.backups.pop():
84 for backup in self.backups:
89 class TestIncrementalBackupBase(iotests.QMPTestCase):
90 def __init__(self, *args):
91 super(TestIncrementalBackupBase, self).__init__(*args)
95 self.vm = iotests.VM()
96 self.err_img = os.path.join(iotests.test_dir, 'err.%s' % iotests.imgfmt)
100 # Create a base image with a distinctive patterning
101 drive0 = self.add_node('drive0')
102 self.img_create(drive0['file'], drive0['fmt'])
103 self.vm.add_drive(drive0['file'], opts='node-name=node0')
104 self.write_default_pattern(drive0['file'])
108 def write_default_pattern(self, target):
109 io_write_patterns(target, (('0x41', 0, 512),
110 ('0xd5', '1M', '32k'),
111 ('0xdc', '32M', '124k')))
114 def add_node(self, node_id, fmt=iotests.imgfmt, path=None, backup=None):
116 path = os.path.join(iotests.test_dir, '%s.%s' % (node_id, fmt))
118 backup = os.path.join(iotests.test_dir,
119 '%s.full.backup.%s' % (node_id, fmt))
126 return self.drives[-1]
129 def img_create(self, img, fmt=iotests.imgfmt, size='64M',
130 parent=None, parentFormat=None, **kwargs):
132 for k,v in kwargs.items():
133 optargs = optargs + ['-o', '%s=%s' % (k,v)]
134 args = ['create', '-f', fmt] + optargs + [img, size]
136 if parentFormat is None:
138 args = args + ['-b', parent, '-F', parentFormat]
139 iotests.qemu_img(*args)
140 self.files.append(img)
143 def do_qmp_backup(self, error='Input/output error', **kwargs):
144 res = self.vm.qmp('drive-backup', **kwargs)
145 self.assert_qmp(res, 'return', {})
146 return self.wait_qmp_backup(kwargs['device'], error)
149 def ignore_job_status_change_events(self):
151 e = self.vm.event_wait(name="JOB_STATUS_CHANGE")
152 if e['data']['status'] == 'null':
155 def wait_qmp_backup(self, device, error='Input/output error'):
156 event = self.vm.event_wait(name="BLOCK_JOB_COMPLETED",
157 match={'data': {'device': device}})
158 self.assertNotEqual(event, None)
159 self.ignore_job_status_change_events()
162 failure = self.dictpath(event, 'data/error')
163 except AssertionError:
165 self.assert_qmp(event, 'data/offset', event['data']['len'])
169 self.assert_qmp(event, 'data/error', error)
173 def wait_qmp_backup_cancelled(self, device):
174 event = self.vm.event_wait(name='BLOCK_JOB_CANCELLED',
175 match={'data': {'device': device}})
176 self.assertNotEqual(event, None)
177 self.ignore_job_status_change_events()
180 def create_anchor_backup(self, drive=None):
182 drive = self.drives[-1]
183 res = self.do_qmp_backup(job_id=drive['id'],
184 device=drive['id'], sync='full',
185 format=drive['fmt'], target=drive['backup'])
187 self.files.append(drive['backup'])
188 return drive['backup']
191 def make_reference_backup(self, bitmap=None):
193 bitmap = self.bitmaps[-1]
194 _, reference = bitmap.last_target()
195 res = self.do_qmp_backup(job_id=bitmap.drive['id'],
196 device=bitmap.drive['id'], sync='full',
197 format=bitmap.drive['fmt'], target=reference)
201 def add_bitmap(self, name, drive, **kwargs):
202 bitmap = Bitmap(name, drive)
203 self.bitmaps.append(bitmap)
204 result = self.vm.qmp('block-dirty-bitmap-add', node=drive['id'],
205 name=bitmap.name, **kwargs)
206 self.assert_qmp(result, 'return', {})
210 def prepare_backup(self, bitmap=None, parent=None, **kwargs):
212 bitmap = self.bitmaps[-1]
214 parent, _ = bitmap.last_target()
216 target, _ = bitmap.new_target()
217 self.img_create(target, bitmap.drive['fmt'], parent=parent,
222 def create_incremental(self, bitmap=None, parent=None,
223 parentFormat=None, validate=True,
226 bitmap = self.bitmaps[-1]
228 parent, _ = bitmap.last_target()
231 target = self.prepare_backup(bitmap, parent)
232 res = self.do_qmp_backup(job_id=bitmap.drive['id'],
233 device=bitmap.drive['id'],
234 sync='incremental', bitmap=bitmap.name,
235 format=bitmap.drive['fmt'], target=target,
239 self.assertFalse(validate)
241 self.make_reference_backup(bitmap)
245 def check_backups(self):
246 for bitmap in self.bitmaps:
247 for incremental, reference in bitmap.backups:
248 self.assertTrue(iotests.compare_images(incremental, reference))
249 last = bitmap.last_target()[0]
250 self.assertTrue(iotests.compare_images(last, bitmap.drive['file']))
253 def hmp_io_writes(self, drive, patterns):
254 for pattern in patterns:
255 self.vm.hmp_qemu_io(drive, 'write -P%s %s %s' % pattern)
256 self.vm.hmp_qemu_io(drive, 'flush')
259 def do_incremental_simple(self, **kwargs):
260 self.create_anchor_backup()
261 self.add_bitmap('bitmap0', self.drives[0], **kwargs)
263 # Sanity: Create a "hollow" incremental backup
264 self.create_incremental()
265 # Three writes: One complete overwrite, one new segment,
266 # and one partial overlap.
267 self.hmp_io_writes(self.drives[0]['id'], (('0xab', 0, 512),
268 ('0xfe', '16M', '256k'),
269 ('0x64', '32736k', '64k')))
270 self.create_incremental()
271 # Three more writes, one of each kind, like above
272 self.hmp_io_writes(self.drives[0]['id'], (('0x9a', 0, 512),
273 ('0x55', '8M', '352k'),
274 ('0x78', '15872k', '1M')))
275 self.create_incremental()
282 for bitmap in self.bitmaps:
284 for filename in self.files:
289 class TestIncrementalBackup(TestIncrementalBackupBase):
290 def test_incremental_simple(self):
292 Test: Create and verify three incremental backups.
294 Create a bitmap and a full backup before VM execution begins,
295 then create a series of three incremental backups "during execution,"
296 i.e.; after IO requests begin modifying the drive.
298 return self.do_incremental_simple()
301 def test_small_granularity(self):
303 Test: Create and verify backups made with a small granularity bitmap.
305 Perform the same test as test_incremental_simple, but with a granularity
306 of only 32KiB instead of the present default of 64KiB.
308 return self.do_incremental_simple(granularity=32768)
311 def test_large_granularity(self):
313 Test: Create and verify backups made with a large granularity bitmap.
315 Perform the same test as test_incremental_simple, but with a granularity
316 of 128KiB instead of the present default of 64KiB.
318 return self.do_incremental_simple(granularity=131072)
321 def test_larger_cluster_target(self):
323 Test: Create and verify backups made to a larger cluster size target.
325 With a default granularity of 64KiB, verify that backups made to a
326 larger cluster size target of 128KiB without a backing file works.
328 drive0 = self.drives[0]
330 # Create a cluster_size=128k full backup / "anchor" backup
331 self.img_create(drive0['backup'], cluster_size='128k')
332 self.assertTrue(self.do_qmp_backup(device=drive0['id'], sync='full',
333 format=drive0['fmt'],
334 target=drive0['backup'],
337 # Create bitmap and dirty it with some new writes.
338 # overwrite [32736, 32799] which will dirty bitmap clusters at
339 # 32M-64K and 32M. 32M+64K will be left undirtied.
340 bitmap0 = self.add_bitmap('bitmap0', drive0)
341 self.hmp_io_writes(drive0['id'],
343 ('0xfe', '16M', '256k'),
344 ('0x64', '32736k', '64k')))
345 # Check the dirty bitmap stats
346 self.assertTrue(self.vm.check_bitmap_status(
347 'node0', bitmap0.name, {
350 'granularity': 65536,
354 # Prepare a cluster_size=128k backup target without a backing file.
355 (target, _) = bitmap0.new_target()
356 self.img_create(target, bitmap0.drive['fmt'], cluster_size='128k')
358 # Perform Incremental Backup
359 self.assertTrue(self.do_qmp_backup(device=bitmap0.drive['id'],
362 format=bitmap0.drive['fmt'],
365 self.make_reference_backup(bitmap0)
367 # Add the backing file, then compare and exit.
368 iotests.qemu_img('rebase', '-f', drive0['fmt'], '-u', '-b',
369 drive0['backup'], '-F', drive0['fmt'], target)
374 def test_incremental_transaction(self):
375 '''Test: Verify backups made from transactionally created bitmaps.
377 Create a bitmap "before" VM execution begins, then create a second
378 bitmap AFTER writes have already occurred. Use transactions to create
379 a full backup and synchronize both bitmaps to this backup.
380 Create an incremental backup through both bitmaps and verify that
381 both backups match the current drive0 image.
384 drive0 = self.drives[0]
385 bitmap0 = self.add_bitmap('bitmap0', drive0)
386 self.hmp_io_writes(drive0['id'], (('0xab', 0, 512),
387 ('0xfe', '16M', '256k'),
388 ('0x64', '32736k', '64k')))
389 bitmap1 = self.add_bitmap('bitmap1', drive0)
391 result = self.vm.qmp('transaction', actions=[
392 transaction_bitmap_clear(bitmap0.drive['id'], bitmap0.name),
393 transaction_bitmap_clear(bitmap1.drive['id'], bitmap1.name),
394 transaction_drive_backup(drive0['id'], drive0['backup'],
395 sync='full', format=drive0['fmt'])
397 self.assert_qmp(result, 'return', {})
398 self.wait_until_completed(drive0['id'])
399 self.files.append(drive0['backup'])
401 self.hmp_io_writes(drive0['id'], (('0x9a', 0, 512),
402 ('0x55', '8M', '352k'),
403 ('0x78', '15872k', '1M')))
404 # Both bitmaps should be correctly in sync.
405 self.create_incremental(bitmap0)
406 self.create_incremental(bitmap1)
411 def do_transaction_failure_test(self, race=False):
412 # Create a second drive, with pattern:
413 drive1 = self.add_node('drive1')
414 self.img_create(drive1['file'], drive1['fmt'])
415 io_write_patterns(drive1['file'], (('0x14', 0, 512),
416 ('0x5d', '1M', '32k'),
417 ('0xcd', '32M', '124k')))
419 # Create a blkdebug interface to this img as 'drive1'
420 result = self.vm.qmp('blockdev-add',
421 node_name=drive1['id'],
422 driver=drive1['fmt'],
424 'driver': 'blkdebug',
427 'filename': drive1['file']
430 'event': 'flush_to_disk',
438 'immediately': False,
443 self.assert_qmp(result, 'return', {})
445 # Create bitmaps and full backups for both drives
446 drive0 = self.drives[0]
447 dr0bm0 = self.add_bitmap('bitmap0', drive0)
448 dr1bm0 = self.add_bitmap('bitmap0', drive1)
449 self.create_anchor_backup(drive0)
450 self.create_anchor_backup(drive1)
451 self.assert_no_active_block_jobs()
452 self.assertFalse(self.vm.get_qmp_events(wait=False))
454 # Emulate some writes
456 self.hmp_io_writes(drive0['id'], (('0xab', 0, 512),
457 ('0xfe', '16M', '256k'),
458 ('0x64', '32736k', '64k')))
459 self.hmp_io_writes(drive1['id'], (('0xba', 0, 512),
460 ('0xef', '16M', '256k'),
461 ('0x46', '32736k', '64k')))
463 # Create incremental backup targets
464 target0 = self.prepare_backup(dr0bm0)
465 target1 = self.prepare_backup(dr1bm0)
467 # Ask for a new incremental backup per-each drive,
468 # expecting drive1's backup to fail. In the 'race' test,
469 # we expect drive1 to attempt to cancel the empty drive0 job.
471 transaction_drive_backup(drive0['id'], target0, sync='incremental',
472 format=drive0['fmt'], mode='existing',
474 transaction_drive_backup(drive1['id'], target1, sync='incremental',
475 format=drive1['fmt'], mode='existing',
478 result = self.vm.qmp('transaction', actions=transaction,
479 properties={'completion-mode': 'grouped'} )
480 self.assert_qmp(result, 'return', {})
482 # Observe that drive0's backup is cancelled and drive1 completes with
484 self.wait_qmp_backup_cancelled(drive0['id'])
485 self.assertFalse(self.wait_qmp_backup(drive1['id']))
486 error = self.vm.event_wait('BLOCK_JOB_ERROR')
487 self.assert_qmp(error, 'data', {'device': drive1['id'],
489 'operation': 'read'})
490 self.assertFalse(self.vm.get_qmp_events(wait=False))
491 self.assert_no_active_block_jobs()
493 # Delete drive0's successful target and eliminate our record of the
494 # unsuccessful drive1 target.
498 # Don't re-run the transaction, we only wanted to test the race.
502 # Re-run the same transaction:
503 target0 = self.prepare_backup(dr0bm0)
504 target1 = self.prepare_backup(dr1bm0)
506 # Re-run the exact same transaction.
507 result = self.vm.qmp('transaction', actions=transaction,
508 properties={'completion-mode':'grouped'})
509 self.assert_qmp(result, 'return', {})
511 # Both should complete successfully this time.
512 self.assertTrue(self.wait_qmp_backup(drive0['id']))
513 self.assertTrue(self.wait_qmp_backup(drive1['id']))
514 self.make_reference_backup(dr0bm0)
515 self.make_reference_backup(dr1bm0)
516 self.assertFalse(self.vm.get_qmp_events(wait=False))
517 self.assert_no_active_block_jobs()
519 # And the images should of course validate.
523 def test_transaction_failure(self):
524 '''Test: Verify backups made from a transaction that partially fails.
526 Add a second drive with its own unique pattern, and add a bitmap to each
527 drive. Use blkdebug to interfere with the backup on just one drive and
528 attempt to create a coherent incremental backup across both drives.
530 verify a failure in one but not both, then delete the failed stubs and
531 re-run the same transaction.
533 verify that both incrementals are created successfully.
535 self.do_transaction_failure_test()
537 def test_transaction_failure_race(self):
538 '''Test: Verify that transactions with jobs that have no data to
539 transfer do not cause race conditions in the cancellation of the entire
540 transaction job group.
542 self.do_transaction_failure_test(race=True)
545 def test_sync_dirty_bitmap_missing(self):
546 self.assert_no_active_block_jobs()
547 self.files.append(self.err_img)
548 result = self.vm.qmp('drive-backup', device=self.drives[0]['id'],
549 sync='incremental', format=self.drives[0]['fmt'],
551 self.assert_qmp(result, 'error/class', 'GenericError')
554 def test_sync_dirty_bitmap_not_found(self):
555 self.assert_no_active_block_jobs()
556 self.files.append(self.err_img)
557 result = self.vm.qmp('drive-backup', device=self.drives[0]['id'],
558 sync='incremental', bitmap='unknown',
559 format=self.drives[0]['fmt'], target=self.err_img)
560 self.assert_qmp(result, 'error/class', 'GenericError')
563 def test_sync_dirty_bitmap_bad_granularity(self):
565 Test: Test what happens if we provide an improper granularity.
567 The granularity must always be a power of 2.
569 self.assert_no_active_block_jobs()
570 self.assertRaises(AssertionError, self.add_bitmap,
571 'bitmap0', self.drives[0],
574 def test_growing_before_backup(self):
576 Test: Add a bitmap, truncate the image, write past the old
579 Incremental backup should not ignore dirty bits past the old
582 self.assert_no_active_block_jobs()
584 self.create_anchor_backup()
586 self.add_bitmap('bitmap0', self.drives[0])
588 res = self.vm.qmp('block_resize', device=self.drives[0]['id'],
590 self.assert_qmp(res, 'return', {})
592 # Dirty the image past the old end
593 self.vm.hmp_qemu_io(self.drives[0]['id'], 'write 64M 64k')
595 target = self.prepare_backup(size='65M')
596 self.create_incremental(target=target)
602 class TestIncrementalBackupBlkdebug(TestIncrementalBackupBase):
603 '''Incremental backup tests that utilize a BlkDebug filter on drive0.'''
606 drive0 = self.add_node('drive0')
607 self.img_create(drive0['file'], drive0['fmt'])
608 self.write_default_pattern(drive0['file'])
611 def test_incremental_failure(self):
612 '''Test: Verify backups made after a failure are correct.
614 Simulate a failure during an incremental backup block job,
615 emulate additional writes, then create another incremental backup
616 afterwards and verify that the backup created is correct.
619 drive0 = self.drives[0]
620 result = self.vm.qmp('blockdev-add',
621 node_name=drive0['id'],
622 driver=drive0['fmt'],
624 'driver': 'blkdebug',
627 'filename': drive0['file']
630 'event': 'flush_to_disk',
638 'immediately': False,
643 self.assert_qmp(result, 'return', {})
645 self.create_anchor_backup(drive0)
646 self.add_bitmap('bitmap0', drive0)
647 # Note: at this point, during a normal execution,
648 # Assume that the VM resumes and begins issuing IO requests here.
650 self.hmp_io_writes(drive0['id'], (('0xab', 0, 512),
651 ('0xfe', '16M', '256k'),
652 ('0x64', '32736k', '64k')))
654 result = self.create_incremental(validate=False)
655 self.assertFalse(result)
656 self.hmp_io_writes(drive0['id'], (('0x9a', 0, 512),
657 ('0x55', '8M', '352k'),
658 ('0x78', '15872k', '1M')))
659 self.create_incremental()
663 def test_incremental_pause(self):
665 Test an incremental backup that errors into a pause and is resumed.
668 drive0 = self.drives[0]
669 # NB: The blkdebug script here looks for a "flush, read" pattern.
670 # The flush occurs in hmp_io_writes, and the read during the block job.
671 result = self.vm.qmp('blockdev-add',
672 node_name=drive0['id'],
673 driver=drive0['fmt'],
675 'driver': 'blkdebug',
678 'filename': drive0['file']
681 'event': 'flush_to_disk',
689 'immediately': False,
693 self.assert_qmp(result, 'return', {})
694 self.create_anchor_backup(drive0)
695 bitmap = self.add_bitmap('bitmap0', drive0)
697 # Emulate guest activity
698 self.hmp_io_writes(drive0['id'], (('0xab', 0, 512),
699 ('0xfe', '16M', '256k'),
700 ('0x64', '32736k', '64k')))
702 # Bitmap Status Check
703 self.assertTrue(self.vm.check_bitmap_status(
704 drive0['id'], bitmap.name, {
706 'granularity': 65536,
712 parent, _ = bitmap.last_target()
713 target = self.prepare_backup(bitmap, parent)
714 res = self.vm.qmp('drive-backup',
715 job_id=bitmap.drive['id'],
716 device=bitmap.drive['id'],
719 format=bitmap.drive['fmt'],
722 on_source_error='stop')
723 self.assert_qmp(res, 'return', {})
726 event = self.vm.event_wait(name="BLOCK_JOB_ERROR",
727 match={"data":{"device":bitmap.drive['id']}})
728 self.assert_qmp(event, 'data', {'device': bitmap.drive['id'],
730 'operation': 'read'})
732 # Bitmap Status Check
733 self.assertTrue(self.vm.check_bitmap_status(
734 drive0['id'], bitmap.name, {
736 'granularity': 65536,
741 # Resume and check incremental backup for consistency
742 res = self.vm.qmp('block-job-resume', device=bitmap.drive['id'])
743 self.assert_qmp(res, 'return', {})
744 self.wait_qmp_backup(bitmap.drive['id'])
746 # Bitmap Status Check
747 self.assertTrue(self.vm.check_bitmap_status(
748 drive0['id'], bitmap.name, {
750 'granularity': 65536,
756 self.make_reference_backup(bitmap)
761 if __name__ == '__main__':
762 iotests.main(supported_fmts=['qcow2'],
763 supported_protocols=['file'])