xref: /openbmc/qemu/tests/qemu-iotests/257 (revision a242b19e80faa95fd5856fca2d4115e853d465b1)
1903cb1bfSPhilippe Mathieu-Daudé#!/usr/bin/env python3
2dfdc48d5SJohn Snow#
3dfdc48d5SJohn Snow# Test bitmap-sync backups (incremental, differential, and partials)
4dfdc48d5SJohn Snow#
5dfdc48d5SJohn Snow# Copyright (c) 2019 John Snow for Red Hat, Inc.
6dfdc48d5SJohn Snow#
7dfdc48d5SJohn Snow# This program is free software; you can redistribute it and/or modify
8dfdc48d5SJohn Snow# it under the terms of the GNU General Public License as published by
9dfdc48d5SJohn Snow# the Free Software Foundation; either version 2 of the License, or
10dfdc48d5SJohn Snow# (at your option) any later version.
11dfdc48d5SJohn Snow#
12dfdc48d5SJohn Snow# This program is distributed in the hope that it will be useful,
13dfdc48d5SJohn Snow# but WITHOUT ANY WARRANTY; without even the implied warranty of
14dfdc48d5SJohn Snow# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15dfdc48d5SJohn Snow# GNU General Public License for more details.
16dfdc48d5SJohn Snow#
17dfdc48d5SJohn Snow# You should have received a copy of the GNU General Public License
18dfdc48d5SJohn Snow# along with this program.  If not, see <http://www.gnu.org/licenses/>.
19dfdc48d5SJohn Snow#
20dfdc48d5SJohn Snow# owner=jsnow@redhat.com
21dfdc48d5SJohn Snow
22dfdc48d5SJohn Snowimport math
23dfdc48d5SJohn Snowimport os
24dfdc48d5SJohn Snow
25dfdc48d5SJohn Snowimport iotests
26dfdc48d5SJohn Snowfrom iotests import log, qemu_img
27dfdc48d5SJohn Snow
28dfdc48d5SJohn SnowSIZE = 64 * 1024 * 1024
29dfdc48d5SJohn SnowGRANULARITY = 64 * 1024
30dfdc48d5SJohn Snow
31b0a32befSJohn Snow
32b0a32befSJohn Snowclass Pattern:
33b0a32befSJohn Snow    def __init__(self, byte, offset, size=GRANULARITY):
34b0a32befSJohn Snow        self.byte = byte
35b0a32befSJohn Snow        self.offset = offset
36b0a32befSJohn Snow        self.size = size
37b0a32befSJohn Snow
38b0a32befSJohn Snow    def bits(self, granularity):
39b0a32befSJohn Snow        lower = self.offset // granularity
40b0a32befSJohn Snow        upper = (self.offset + self.size - 1) // granularity
41b0a32befSJohn Snow        return set(range(lower, upper + 1))
42b0a32befSJohn Snow
43dfdc48d5SJohn Snow
44dfdc48d5SJohn Snowclass PatternGroup:
45dfdc48d5SJohn Snow    """Grouping of Pattern objects. Initialize with an iterable of Patterns."""
46dfdc48d5SJohn Snow    def __init__(self, patterns):
47dfdc48d5SJohn Snow        self.patterns = patterns
48dfdc48d5SJohn Snow
49dfdc48d5SJohn Snow    def bits(self, granularity):
50dfdc48d5SJohn Snow        """Calculate the unique bits dirtied by this pattern grouping"""
51dfdc48d5SJohn Snow        res = set()
52dfdc48d5SJohn Snow        for pattern in self.patterns:
53b0a32befSJohn Snow            res |= pattern.bits(granularity)
54dfdc48d5SJohn Snow        return res
55dfdc48d5SJohn Snow
56b0a32befSJohn Snow
57dfdc48d5SJohn SnowGROUPS = [
58dfdc48d5SJohn Snow    PatternGroup([
59dfdc48d5SJohn Snow        # Batch 0: 4 clusters
60b0a32befSJohn Snow        Pattern('0x49', 0x0000000),
61b0a32befSJohn Snow        Pattern('0x6c', 0x0100000),   # 1M
62b0a32befSJohn Snow        Pattern('0x6f', 0x2000000),   # 32M
63b0a32befSJohn Snow        Pattern('0x76', 0x3ff0000)]), # 64M - 64K
64dfdc48d5SJohn Snow    PatternGroup([
65dfdc48d5SJohn Snow        # Batch 1: 6 clusters (3 new)
66b0a32befSJohn Snow        Pattern('0x65', 0x0000000),   # Full overwrite
67b0a32befSJohn Snow        Pattern('0x77', 0x00f8000),   # Partial-left (1M-32K)
68b0a32befSJohn Snow        Pattern('0x72', 0x2008000),   # Partial-right (32M+32K)
69b0a32befSJohn Snow        Pattern('0x69', 0x3fe0000)]), # Adjacent-left (64M - 128K)
70dfdc48d5SJohn Snow    PatternGroup([
71dfdc48d5SJohn Snow        # Batch 2: 7 clusters (3 new)
72b0a32befSJohn Snow        Pattern('0x74', 0x0010000),   # Adjacent-right
73b0a32befSJohn Snow        Pattern('0x69', 0x00e8000),   # Partial-left  (1M-96K)
74b0a32befSJohn Snow        Pattern('0x6e', 0x2018000),   # Partial-right (32M+96K)
75b0a32befSJohn Snow        Pattern('0x67', 0x3fe0000,
76dfdc48d5SJohn Snow                2*GRANULARITY)]),     # Overwrite [(64M-128K)-64M)
77dfdc48d5SJohn Snow    PatternGroup([
78dfdc48d5SJohn Snow        # Batch 3: 8 clusters (5 new)
79dfdc48d5SJohn Snow        # Carefully chosen such that nothing re-dirties the one cluster
80dfdc48d5SJohn Snow        # that copies out successfully before failure in Group #1.
81b0a32befSJohn Snow        Pattern('0xaa', 0x0010000,
82dfdc48d5SJohn Snow                3*GRANULARITY),       # Overwrite and 2x Adjacent-right
83b0a32befSJohn Snow        Pattern('0xbb', 0x00d8000),   # Partial-left (1M-160K)
84b0a32befSJohn Snow        Pattern('0xcc', 0x2028000),   # Partial-right (32M+160K)
85b0a32befSJohn Snow        Pattern('0xdd', 0x3fc0000)]), # New; leaving a gap to the right
86dfdc48d5SJohn Snow]
87dfdc48d5SJohn Snow
8832afa5a1SJohn Snow
8932afa5a1SJohn Snowclass EmulatedBitmap:
9032afa5a1SJohn Snow    def __init__(self, granularity=GRANULARITY):
9132afa5a1SJohn Snow        self._bits = set()
9232afa5a1SJohn Snow        self.granularity = granularity
9332afa5a1SJohn Snow
9432afa5a1SJohn Snow    def dirty_bits(self, bits):
9532afa5a1SJohn Snow        self._bits |= set(bits)
9632afa5a1SJohn Snow
9732afa5a1SJohn Snow    def dirty_group(self, n):
9832afa5a1SJohn Snow        self.dirty_bits(GROUPS[n].bits(self.granularity))
9932afa5a1SJohn Snow
10032afa5a1SJohn Snow    def clear(self):
10132afa5a1SJohn Snow        self._bits = set()
10232afa5a1SJohn Snow
10332afa5a1SJohn Snow    def clear_bits(self, bits):
10432afa5a1SJohn Snow        self._bits -= set(bits)
10532afa5a1SJohn Snow
10632afa5a1SJohn Snow    def clear_bit(self, bit):
10732afa5a1SJohn Snow        self.clear_bits({bit})
10832afa5a1SJohn Snow
10932afa5a1SJohn Snow    def clear_group(self, n):
11032afa5a1SJohn Snow        self.clear_bits(GROUPS[n].bits(self.granularity))
11132afa5a1SJohn Snow
11232afa5a1SJohn Snow    @property
11332afa5a1SJohn Snow    def first_bit(self):
11432afa5a1SJohn Snow        return sorted(self.bits)[0]
11532afa5a1SJohn Snow
11632afa5a1SJohn Snow    @property
11732afa5a1SJohn Snow    def bits(self):
11832afa5a1SJohn Snow        return self._bits
11932afa5a1SJohn Snow
12032afa5a1SJohn Snow    @property
12132afa5a1SJohn Snow    def count(self):
12232afa5a1SJohn Snow        return len(self.bits)
12332afa5a1SJohn Snow
12432afa5a1SJohn Snow    def compare(self, qmp_bitmap):
12532afa5a1SJohn Snow        """
12632afa5a1SJohn Snow        Print a nice human-readable message checking that a bitmap as reported
12732afa5a1SJohn Snow        by the QMP interface has as many bits set as we expect it to.
12832afa5a1SJohn Snow        """
12932afa5a1SJohn Snow
13032afa5a1SJohn Snow        name = qmp_bitmap.get('name', '(anonymous)')
13132afa5a1SJohn Snow        log("= Checking Bitmap {:s} =".format(name))
13232afa5a1SJohn Snow
13332afa5a1SJohn Snow        want = self.count
13432afa5a1SJohn Snow        have = qmp_bitmap['count'] // qmp_bitmap['granularity']
13532afa5a1SJohn Snow
13632afa5a1SJohn Snow        log("expecting {:d} dirty sectors; have {:d}. {:s}".format(
13732afa5a1SJohn Snow            want, have, "OK!" if want == have else "ERROR!"))
13832afa5a1SJohn Snow        log('')
13932afa5a1SJohn Snow
14032afa5a1SJohn Snow
141dfdc48d5SJohn Snowclass Drive:
142dfdc48d5SJohn Snow    """Represents, vaguely, a drive attached to a VM.
143dfdc48d5SJohn Snow    Includes format, graph, and device information."""
144dfdc48d5SJohn Snow
145dfdc48d5SJohn Snow    def __init__(self, path, vm=None):
146dfdc48d5SJohn Snow        self.path = path
147dfdc48d5SJohn Snow        self.vm = vm
148dfdc48d5SJohn Snow        self.fmt = None
149dfdc48d5SJohn Snow        self.size = None
150dfdc48d5SJohn Snow        self.node = None
151dfdc48d5SJohn Snow
152dfdc48d5SJohn Snow    def img_create(self, fmt, size):
153dfdc48d5SJohn Snow        self.fmt = fmt
154dfdc48d5SJohn Snow        self.size = size
155dfdc48d5SJohn Snow        iotests.qemu_img_create('-f', self.fmt, self.path, str(self.size))
156dfdc48d5SJohn Snow
157dfdc48d5SJohn Snow    def create_target(self, name, fmt, size):
158dfdc48d5SJohn Snow        basename = os.path.basename(self.path)
159dfdc48d5SJohn Snow        file_node_name = "file_{}".format(basename)
160dfdc48d5SJohn Snow        vm = self.vm
161dfdc48d5SJohn Snow
162dfdc48d5SJohn Snow        log(vm.command('blockdev-create', job_id='bdc-file-job',
163dfdc48d5SJohn Snow                       options={
164dfdc48d5SJohn Snow                           'driver': 'file',
165dfdc48d5SJohn Snow                           'filename': self.path,
166dfdc48d5SJohn Snow                           'size': 0,
167dfdc48d5SJohn Snow                       }))
168dfdc48d5SJohn Snow        vm.run_job('bdc-file-job')
169dfdc48d5SJohn Snow        log(vm.command('blockdev-add', driver='file',
170dfdc48d5SJohn Snow                       node_name=file_node_name, filename=self.path))
171dfdc48d5SJohn Snow
172dfdc48d5SJohn Snow        log(vm.command('blockdev-create', job_id='bdc-fmt-job',
173dfdc48d5SJohn Snow                       options={
174dfdc48d5SJohn Snow                           'driver': fmt,
175dfdc48d5SJohn Snow                           'file': file_node_name,
176dfdc48d5SJohn Snow                           'size': size,
177dfdc48d5SJohn Snow                       }))
178dfdc48d5SJohn Snow        vm.run_job('bdc-fmt-job')
179dfdc48d5SJohn Snow        log(vm.command('blockdev-add', driver=fmt,
180dfdc48d5SJohn Snow                       node_name=name,
181dfdc48d5SJohn Snow                       file=file_node_name))
182dfdc48d5SJohn Snow        self.fmt = fmt
183dfdc48d5SJohn Snow        self.size = size
184dfdc48d5SJohn Snow        self.node = name
185dfdc48d5SJohn Snow
1860af2a09cSJohn Snowdef blockdev_backup(vm, device, target, sync, **kwargs):
1870af2a09cSJohn Snow    # Strip any arguments explicitly nulled by the caller:
1880af2a09cSJohn Snow    kwargs = {key: val for key, val in kwargs.items() if val is not None}
1890af2a09cSJohn Snow    result = vm.qmp_log('blockdev-backup',
1900af2a09cSJohn Snow                        device=device,
1910af2a09cSJohn Snow                        target=target,
1920af2a09cSJohn Snow                        sync=sync,
19300e30f05SVladimir Sementsov-Ogievskiy                        filter_node_name='backup-top',
1940af2a09cSJohn Snow                        **kwargs)
1950af2a09cSJohn Snow    return result
1960af2a09cSJohn Snow
1970af2a09cSJohn Snowdef blockdev_backup_mktarget(drive, target_id, filepath, sync, **kwargs):
1980af2a09cSJohn Snow    target_drive = Drive(filepath, vm=drive.vm)
1990af2a09cSJohn Snow    target_drive.create_target(target_id, drive.fmt, drive.size)
200f1648454SVladimir Sementsov-Ogievskiy    blockdev_backup(drive.vm, drive.node, target_id, sync, **kwargs)
2010af2a09cSJohn Snow
202dfdc48d5SJohn Snowdef reference_backup(drive, n, filepath):
203dfdc48d5SJohn Snow    log("--- Reference Backup #{:d} ---\n".format(n))
204dfdc48d5SJohn Snow    target_id = "ref_target_{:d}".format(n)
205dfdc48d5SJohn Snow    job_id = "ref_backup_{:d}".format(n)
2060af2a09cSJohn Snow    blockdev_backup_mktarget(drive, target_id, filepath, "full",
2070af2a09cSJohn Snow                             job_id=job_id)
208dfdc48d5SJohn Snow    drive.vm.run_job(job_id, auto_dismiss=True)
209dfdc48d5SJohn Snow    log('')
210dfdc48d5SJohn Snow
2110af2a09cSJohn Snowdef backup(drive, n, filepath, sync, **kwargs):
2120af2a09cSJohn Snow    log("--- Test Backup #{:d} ---\n".format(n))
2130af2a09cSJohn Snow    target_id = "backup_target_{:d}".format(n)
2140af2a09cSJohn Snow    job_id = "backup_{:d}".format(n)
2150af2a09cSJohn Snow    kwargs.setdefault('auto-finalize', False)
2160af2a09cSJohn Snow    blockdev_backup_mktarget(drive, target_id, filepath, sync,
2170af2a09cSJohn Snow                             job_id=job_id, **kwargs)
218dfdc48d5SJohn Snow    return job_id
219dfdc48d5SJohn Snow
22000e30f05SVladimir Sementsov-Ogievskiydef perform_writes(drive, n, filter_node_name=None):
221dfdc48d5SJohn Snow    log("--- Write #{:d} ---\n".format(n))
222dfdc48d5SJohn Snow    for pattern in GROUPS[n].patterns:
223dfdc48d5SJohn Snow        cmd = "write -P{:s} 0x{:07x} 0x{:x}".format(
224dfdc48d5SJohn Snow            pattern.byte,
225dfdc48d5SJohn Snow            pattern.offset,
226dfdc48d5SJohn Snow            pattern.size)
227dfdc48d5SJohn Snow        log(cmd)
22800e30f05SVladimir Sementsov-Ogievskiy        log(drive.vm.hmp_qemu_io(filter_node_name or drive.node, cmd))
2295c4343b8SVladimir Sementsov-Ogievskiy    bitmaps = drive.vm.query_bitmaps()
2305c4343b8SVladimir Sementsov-Ogievskiy    log({'bitmaps': bitmaps}, indent=2)
231dfdc48d5SJohn Snow    log('')
232dfdc48d5SJohn Snow    return bitmaps
233dfdc48d5SJohn Snow
234dfdc48d5SJohn Snow
235dfdc48d5SJohn Snowdef compare_images(image, reference, baseimg=None, expected_match=True):
236dfdc48d5SJohn Snow    """
237dfdc48d5SJohn Snow    Print a nice human-readable message comparing these images.
238dfdc48d5SJohn Snow    """
239dfdc48d5SJohn Snow    expected_ret = 0 if expected_match else 1
240dfdc48d5SJohn Snow    if baseimg:
241b66ff2c2SEric Blake        assert qemu_img("rebase", "-u", "-b", baseimg, '-F', iotests.imgfmt,
242b66ff2c2SEric Blake                        image) == 0
243dfdc48d5SJohn Snow    ret = qemu_img("compare", image, reference)
244dfdc48d5SJohn Snow    log('qemu_img compare "{:s}" "{:s}" ==> {:s}, {:s}'.format(
245dfdc48d5SJohn Snow        image, reference,
246dfdc48d5SJohn Snow        "Identical" if ret == 0 else "Mismatch",
247dfdc48d5SJohn Snow        "OK!" if ret == expected_ret else "ERROR!"),
248dfdc48d5SJohn Snow        filters=[iotests.filter_testfiles])
249dfdc48d5SJohn Snow
2500af2a09cSJohn Snowdef test_bitmap_sync(bsync_mode, msync_mode='bitmap', failure=None):
251dfdc48d5SJohn Snow    """
252dfdc48d5SJohn Snow    Test bitmap backup routines.
253dfdc48d5SJohn Snow
254dfdc48d5SJohn Snow    :param bsync_mode: Is the Bitmap Sync mode, and can be any of:
255dfdc48d5SJohn Snow        - on-success: This is the "incremental" style mode. Bitmaps are
256dfdc48d5SJohn Snow                      synchronized to what was copied out only on success.
257dfdc48d5SJohn Snow                      (Partial images must be discarded.)
258dfdc48d5SJohn Snow        - never:      This is the "differential" style mode.
259dfdc48d5SJohn Snow                      Bitmaps are never synchronized.
260dfdc48d5SJohn Snow        - always:     This is a "best effort" style mode.
261dfdc48d5SJohn Snow                      Bitmaps are always synchronized, regardless of failure.
262dfdc48d5SJohn Snow                      (Partial images must be kept.)
263dfdc48d5SJohn Snow
264bd5ceebfSJohn Snow    :param msync_mode: The mirror sync mode to use for the first backup.
265bd5ceebfSJohn Snow                       Can be any one of:
266bd5ceebfSJohn Snow        - bitmap: Backups based on bitmap manifest.
267bd5ceebfSJohn Snow        - full:   Full backups.
268bd5ceebfSJohn Snow        - top:    Full backups of the top layer only.
269bd5ceebfSJohn Snow
270dfdc48d5SJohn Snow    :param failure: Is the (optional) failure mode, and can be any of:
271dfdc48d5SJohn Snow        - None:         No failure. Test the normative path. Default.
272dfdc48d5SJohn Snow        - simulated:    Cancel the job right before it completes.
273dfdc48d5SJohn Snow                        This also tests writes "during" the job.
274dfdc48d5SJohn Snow        - intermediate: This tests a job that fails mid-process and produces
275dfdc48d5SJohn Snow                        an incomplete backup. Testing limitations prevent
276dfdc48d5SJohn Snow                        testing competing writes.
277dfdc48d5SJohn Snow    """
278*a242b19eSNir Soffer    with iotests.FilePaths(
279*a242b19eSNir Soffer            'img', 'bsync1', 'bsync2', 'fbackup0', 'fbackup1', 'fbackup2') as \
280*a242b19eSNir Soffer            (img_path, bsync1, bsync2, fbackup0, fbackup1, fbackup2), \
281dfdc48d5SJohn Snow         iotests.VM() as vm:
282dfdc48d5SJohn Snow
2830af2a09cSJohn Snow        mode = "Mode {:s}; Bitmap Sync {:s}".format(msync_mode, bsync_mode)
284dfdc48d5SJohn Snow        preposition = "with" if failure else "without"
285dfdc48d5SJohn Snow        cond = "{:s} {:s}".format(preposition,
286dfdc48d5SJohn Snow                                  "{:s} failure".format(failure) if failure
287dfdc48d5SJohn Snow                                  else "failure")
288dfdc48d5SJohn Snow        log("\n=== {:s} {:s} ===\n".format(mode, cond))
289dfdc48d5SJohn Snow
290dfdc48d5SJohn Snow        log('--- Preparing image & VM ---\n')
291dfdc48d5SJohn Snow        drive0 = Drive(img_path, vm=vm)
292dfdc48d5SJohn Snow        drive0.img_create(iotests.imgfmt, SIZE)
293dfdc48d5SJohn Snow        vm.add_device("{},id=scsi0".format(iotests.get_virtio_scsi_device()))
294dfdc48d5SJohn Snow        vm.launch()
295dfdc48d5SJohn Snow
296dfdc48d5SJohn Snow        file_config = {
297dfdc48d5SJohn Snow            'driver': 'file',
298dfdc48d5SJohn Snow            'filename': drive0.path
299dfdc48d5SJohn Snow        }
300dfdc48d5SJohn Snow
301dfdc48d5SJohn Snow        if failure == 'intermediate':
302dfdc48d5SJohn Snow            file_config = {
303dfdc48d5SJohn Snow                'driver': 'blkdebug',
304dfdc48d5SJohn Snow                'image': file_config,
305dfdc48d5SJohn Snow                'set-state': [{
306dfdc48d5SJohn Snow                    'event': 'flush_to_disk',
307dfdc48d5SJohn Snow                    'state': 1,
308dfdc48d5SJohn Snow                    'new_state': 2
309dfdc48d5SJohn Snow                }, {
310dfdc48d5SJohn Snow                    'event': 'read_aio',
311dfdc48d5SJohn Snow                    'state': 2,
312dfdc48d5SJohn Snow                    'new_state': 3
313dfdc48d5SJohn Snow                }],
314dfdc48d5SJohn Snow                'inject-error': [{
315dfdc48d5SJohn Snow                    'event': 'read_aio',
316dfdc48d5SJohn Snow                    'errno': 5,
317dfdc48d5SJohn Snow                    'state': 3,
318dfdc48d5SJohn Snow                    'immediately': False,
319dfdc48d5SJohn Snow                    'once': True
320dfdc48d5SJohn Snow                }]
321dfdc48d5SJohn Snow            }
322dfdc48d5SJohn Snow
323f1648454SVladimir Sementsov-Ogievskiy        drive0.node = 'drive0'
324dfdc48d5SJohn Snow        vm.qmp_log('blockdev-add',
325dfdc48d5SJohn Snow                   filters=[iotests.filter_qmp_testfiles],
326f1648454SVladimir Sementsov-Ogievskiy                   node_name=drive0.node,
327dfdc48d5SJohn Snow                   driver=drive0.fmt,
328dfdc48d5SJohn Snow                   file=file_config)
329dfdc48d5SJohn Snow        log('')
330dfdc48d5SJohn Snow
331dfdc48d5SJohn Snow        # 0 - Writes and Reference Backup
332dfdc48d5SJohn Snow        perform_writes(drive0, 0)
333dfdc48d5SJohn Snow        reference_backup(drive0, 0, fbackup0)
334dfdc48d5SJohn Snow        log('--- Add Bitmap ---\n')
335f1648454SVladimir Sementsov-Ogievskiy        vm.qmp_log("block-dirty-bitmap-add", node=drive0.node,
336dfdc48d5SJohn Snow                   name="bitmap0", granularity=GRANULARITY)
337dfdc48d5SJohn Snow        log('')
33832afa5a1SJohn Snow        ebitmap = EmulatedBitmap()
339dfdc48d5SJohn Snow
340dfdc48d5SJohn Snow        # 1 - Writes and Reference Backup
341dfdc48d5SJohn Snow        bitmaps = perform_writes(drive0, 1)
34232afa5a1SJohn Snow        ebitmap.dirty_group(1)
3435c4343b8SVladimir Sementsov-Ogievskiy        bitmap = vm.get_bitmap(drive0.node, 'bitmap0', bitmaps=bitmaps)
34432afa5a1SJohn Snow        ebitmap.compare(bitmap)
345dfdc48d5SJohn Snow        reference_backup(drive0, 1, fbackup1)
346dfdc48d5SJohn Snow
3470af2a09cSJohn Snow        # 1 - Test Backup (w/ Optional induced failure)
348dfdc48d5SJohn Snow        if failure == 'intermediate':
349dfdc48d5SJohn Snow            # Activate blkdebug induced failure for second-to-next read
350f1648454SVladimir Sementsov-Ogievskiy            log(vm.hmp_qemu_io(drive0.node, 'flush'))
351dfdc48d5SJohn Snow            log('')
3520af2a09cSJohn Snow        job = backup(drive0, 1, bsync1, msync_mode,
3530af2a09cSJohn Snow                     bitmap="bitmap0", bitmap_mode=bsync_mode)
354dfdc48d5SJohn Snow
355dfdc48d5SJohn Snow        def _callback():
356dfdc48d5SJohn Snow            """Issue writes while the job is open to test bitmap divergence."""
357dfdc48d5SJohn Snow            # Note: when `failure` is 'intermediate', this isn't called.
358dfdc48d5SJohn Snow            log('')
35900e30f05SVladimir Sementsov-Ogievskiy            bitmaps = perform_writes(drive0, 2, filter_node_name='backup-top')
360dfdc48d5SJohn Snow            # Named bitmap (static, should be unchanged)
3615c4343b8SVladimir Sementsov-Ogievskiy            ebitmap.compare(vm.get_bitmap(drive0.node, 'bitmap0',
3625c4343b8SVladimir Sementsov-Ogievskiy                                          bitmaps=bitmaps))
363dfdc48d5SJohn Snow            # Anonymous bitmap (dynamic, shows new writes)
36432afa5a1SJohn Snow            anonymous = EmulatedBitmap()
36532afa5a1SJohn Snow            anonymous.dirty_group(2)
3665c4343b8SVladimir Sementsov-Ogievskiy            anonymous.compare(vm.get_bitmap(drive0.node, '', recording=True,
3675c4343b8SVladimir Sementsov-Ogievskiy                                            bitmaps=bitmaps))
36832afa5a1SJohn Snow
36932afa5a1SJohn Snow            # Simulate the order in which this will happen:
37032afa5a1SJohn Snow            # group 1 gets cleared first, then group two gets written.
37132afa5a1SJohn Snow            if ((bsync_mode == 'on-success' and not failure) or
37232afa5a1SJohn Snow                (bsync_mode == 'always')):
373bd5ceebfSJohn Snow                ebitmap.clear()
37432afa5a1SJohn Snow            ebitmap.dirty_group(2)
375dfdc48d5SJohn Snow
376dfdc48d5SJohn Snow        vm.run_job(job, auto_dismiss=True, auto_finalize=False,
377dfdc48d5SJohn Snow                   pre_finalize=_callback,
378dfdc48d5SJohn Snow                   cancel=(failure == 'simulated'))
3795c4343b8SVladimir Sementsov-Ogievskiy        bitmaps = vm.query_bitmaps()
3805c4343b8SVladimir Sementsov-Ogievskiy        log({'bitmaps': bitmaps}, indent=2)
381dfdc48d5SJohn Snow        log('')
382dfdc48d5SJohn Snow
383dfdc48d5SJohn Snow        if bsync_mode == 'always' and failure == 'intermediate':
384bd5ceebfSJohn Snow            # TOP treats anything allocated as dirty, expect to see:
385bd5ceebfSJohn Snow            if msync_mode == 'top':
386bd5ceebfSJohn Snow                ebitmap.dirty_group(0)
387bd5ceebfSJohn Snow
388dfdc48d5SJohn Snow            # We manage to copy one sector (one bit) before the error.
38932afa5a1SJohn Snow            ebitmap.clear_bit(ebitmap.first_bit)
390bd5ceebfSJohn Snow
391bd5ceebfSJohn Snow            # Full returns all bits set except what was copied/skipped
392bd5ceebfSJohn Snow            if msync_mode == 'full':
393bd5ceebfSJohn Snow                fail_bit = ebitmap.first_bit
394bd5ceebfSJohn Snow                ebitmap.clear()
395bd5ceebfSJohn Snow                ebitmap.dirty_bits(range(fail_bit, SIZE // GRANULARITY))
396bd5ceebfSJohn Snow
3975c4343b8SVladimir Sementsov-Ogievskiy        ebitmap.compare(vm.get_bitmap(drive0.node, 'bitmap0', bitmaps=bitmaps))
398dfdc48d5SJohn Snow
399dfdc48d5SJohn Snow        # 2 - Writes and Reference Backup
400dfdc48d5SJohn Snow        bitmaps = perform_writes(drive0, 3)
40132afa5a1SJohn Snow        ebitmap.dirty_group(3)
4025c4343b8SVladimir Sementsov-Ogievskiy        ebitmap.compare(vm.get_bitmap(drive0.node, 'bitmap0', bitmaps=bitmaps))
403dfdc48d5SJohn Snow        reference_backup(drive0, 2, fbackup2)
404dfdc48d5SJohn Snow
405dfdc48d5SJohn Snow        # 2 - Bitmap Backup (In failure modes, this is a recovery.)
4060af2a09cSJohn Snow        job = backup(drive0, 2, bsync2, "bitmap",
4070af2a09cSJohn Snow                     bitmap="bitmap0", bitmap_mode=bsync_mode)
408dfdc48d5SJohn Snow        vm.run_job(job, auto_dismiss=True, auto_finalize=False)
4095c4343b8SVladimir Sementsov-Ogievskiy        bitmaps = vm.query_bitmaps()
4105c4343b8SVladimir Sementsov-Ogievskiy        log({'bitmaps': bitmaps}, indent=2)
411dfdc48d5SJohn Snow        log('')
41232afa5a1SJohn Snow        if bsync_mode != 'never':
41332afa5a1SJohn Snow            ebitmap.clear()
4145c4343b8SVladimir Sementsov-Ogievskiy        ebitmap.compare(vm.get_bitmap(drive0.node, 'bitmap0', bitmaps=bitmaps))
415dfdc48d5SJohn Snow
416dfdc48d5SJohn Snow        log('--- Cleanup ---\n')
417dfdc48d5SJohn Snow        vm.qmp_log("block-dirty-bitmap-remove",
418f1648454SVladimir Sementsov-Ogievskiy                   node=drive0.node, name="bitmap0")
4195c4343b8SVladimir Sementsov-Ogievskiy        bitmaps = vm.query_bitmaps()
4205c4343b8SVladimir Sementsov-Ogievskiy        log({'bitmaps': bitmaps}, indent=2)
421dfdc48d5SJohn Snow        vm.shutdown()
422dfdc48d5SJohn Snow        log('')
423dfdc48d5SJohn Snow
424dfdc48d5SJohn Snow        log('--- Verification ---\n')
425dfdc48d5SJohn Snow        # 'simulated' failures will actually all pass here because we canceled
426dfdc48d5SJohn Snow        # while "pending". This is actually undefined behavior,
427dfdc48d5SJohn Snow        # don't rely on this to be true!
428dfdc48d5SJohn Snow        compare_images(bsync1, fbackup1, baseimg=fbackup0,
429dfdc48d5SJohn Snow                       expected_match=failure != 'intermediate')
430dfdc48d5SJohn Snow        if not failure or bsync_mode == 'always':
431dfdc48d5SJohn Snow            # Always keep the last backup on success or when using 'always'
432dfdc48d5SJohn Snow            base = bsync1
433dfdc48d5SJohn Snow        else:
434dfdc48d5SJohn Snow            base = fbackup0
435dfdc48d5SJohn Snow        compare_images(bsync2, fbackup2, baseimg=base)
436dfdc48d5SJohn Snow        compare_images(img_path, fbackup2)
437dfdc48d5SJohn Snow        log('')
438dfdc48d5SJohn Snow
439352092d3SJohn Snowdef test_backup_api():
440352092d3SJohn Snow    """
441352092d3SJohn Snow    Test malformed and prohibited invocations of the backup API.
442352092d3SJohn Snow    """
443*a242b19eSNir Soffer    with iotests.FilePaths('img', 'bsync1') as (img_path, backup_path), \
444352092d3SJohn Snow         iotests.VM() as vm:
445352092d3SJohn Snow
446352092d3SJohn Snow        log("\n=== API failure tests ===\n")
447352092d3SJohn Snow        log('--- Preparing image & VM ---\n')
448352092d3SJohn Snow        drive0 = Drive(img_path, vm=vm)
449352092d3SJohn Snow        drive0.img_create(iotests.imgfmt, SIZE)
450352092d3SJohn Snow        vm.add_device("{},id=scsi0".format(iotests.get_virtio_scsi_device()))
451352092d3SJohn Snow        vm.launch()
452352092d3SJohn Snow
453352092d3SJohn Snow        file_config = {
454352092d3SJohn Snow            'driver': 'file',
455352092d3SJohn Snow            'filename': drive0.path
456352092d3SJohn Snow        }
457352092d3SJohn Snow
458f1648454SVladimir Sementsov-Ogievskiy        drive0.node = 'drive0'
459352092d3SJohn Snow        vm.qmp_log('blockdev-add',
460352092d3SJohn Snow                   filters=[iotests.filter_qmp_testfiles],
461f1648454SVladimir Sementsov-Ogievskiy                   node_name=drive0.node,
462352092d3SJohn Snow                   driver=drive0.fmt,
463352092d3SJohn Snow                   file=file_config)
464352092d3SJohn Snow        log('')
465352092d3SJohn Snow
466352092d3SJohn Snow        target0 = Drive(backup_path, vm=vm)
467352092d3SJohn Snow        target0.create_target("backup_target", drive0.fmt, drive0.size)
468352092d3SJohn Snow        log('')
469352092d3SJohn Snow
470f1648454SVladimir Sementsov-Ogievskiy        vm.qmp_log("block-dirty-bitmap-add", node=drive0.node,
471352092d3SJohn Snow                   name="bitmap0", granularity=GRANULARITY)
472352092d3SJohn Snow        log('')
473352092d3SJohn Snow
474352092d3SJohn Snow        log('-- Testing invalid QMP commands --\n')
475352092d3SJohn Snow
476352092d3SJohn Snow        error_cases = {
477352092d3SJohn Snow            'incremental': {
478352092d3SJohn Snow                None:        ['on-success', 'always', 'never', None],
479352092d3SJohn Snow                'bitmap404': ['on-success', 'always', 'never', None],
480352092d3SJohn Snow                'bitmap0':   ['always', 'never']
481352092d3SJohn Snow            },
482352092d3SJohn Snow            'bitmap': {
483352092d3SJohn Snow                None:        ['on-success', 'always', 'never', None],
484352092d3SJohn Snow                'bitmap404': ['on-success', 'always', 'never', None],
485352092d3SJohn Snow                'bitmap0':   [None],
486352092d3SJohn Snow            },
487bd5ceebfSJohn Snow            'full': {
488bd5ceebfSJohn Snow                None:        ['on-success', 'always', 'never'],
489bd5ceebfSJohn Snow                'bitmap404': ['on-success', 'always', 'never', None],
490bd5ceebfSJohn Snow                'bitmap0':   ['never', None],
491bd5ceebfSJohn Snow            },
492bd5ceebfSJohn Snow            'top': {
493bd5ceebfSJohn Snow                None:        ['on-success', 'always', 'never'],
494bd5ceebfSJohn Snow                'bitmap404': ['on-success', 'always', 'never', None],
495bd5ceebfSJohn Snow                'bitmap0':   ['never', None],
496bd5ceebfSJohn Snow            },
497bd5ceebfSJohn Snow            'none': {
498bd5ceebfSJohn Snow                None:        ['on-success', 'always', 'never'],
499bd5ceebfSJohn Snow                'bitmap404': ['on-success', 'always', 'never', None],
500bd5ceebfSJohn Snow                'bitmap0':   ['on-success', 'always', 'never', None],
501bd5ceebfSJohn Snow            }
502352092d3SJohn Snow        }
503352092d3SJohn Snow
504352092d3SJohn Snow        # Dicts, as always, are not stably-ordered prior to 3.7, so use tuples:
505bd5ceebfSJohn Snow        for sync_mode in ('incremental', 'bitmap', 'full', 'top', 'none'):
506352092d3SJohn Snow            log("-- Sync mode {:s} tests --\n".format(sync_mode))
507352092d3SJohn Snow            for bitmap in (None, 'bitmap404', 'bitmap0'):
508352092d3SJohn Snow                for policy in error_cases[sync_mode][bitmap]:
509f1648454SVladimir Sementsov-Ogievskiy                    blockdev_backup(drive0.vm, drive0.node, "backup_target",
510352092d3SJohn Snow                                    sync_mode, job_id='api_job',
511352092d3SJohn Snow                                    bitmap=bitmap, bitmap_mode=policy)
512352092d3SJohn Snow                    log('')
513352092d3SJohn Snow
514352092d3SJohn Snow
515dfdc48d5SJohn Snowdef main():
516dfdc48d5SJohn Snow    for bsync_mode in ("never", "on-success", "always"):
517dfdc48d5SJohn Snow        for failure in ("simulated", "intermediate", None):
5180af2a09cSJohn Snow            test_bitmap_sync(bsync_mode, "bitmap", failure)
519dfdc48d5SJohn Snow
520bd5ceebfSJohn Snow    for sync_mode in ('full', 'top'):
521bd5ceebfSJohn Snow        for bsync_mode in ('on-success', 'always'):
522bd5ceebfSJohn Snow            for failure in ('simulated', 'intermediate', None):
523bd5ceebfSJohn Snow                test_bitmap_sync(bsync_mode, sync_mode, failure)
524bd5ceebfSJohn Snow
525352092d3SJohn Snow    test_backup_api()
526352092d3SJohn Snow
527dfdc48d5SJohn Snowif __name__ == '__main__':
528103cbc77SMax Reitz    iotests.script_main(main, supported_fmts=['qcow2'],
529103cbc77SMax Reitz                        supported_protocols=['file'])
530