xref: /openbmc/qemu/tests/qemu-iotests/040 (revision d24eb059)
1#!/usr/bin/env python3
2# group: rw auto
3#
4# Tests for image block commit.
5#
6# Copyright (C) 2012 IBM, Corp.
7# Copyright (C) 2012 Red Hat, Inc.
8#
9# This program is free software; you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation; either version 2 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program.  If not, see <http://www.gnu.org/licenses/>.
21#
22# Test for live block commit
23# Derived from Image Streaming Test 030
24
25import time
26import os
27import iotests
28from iotests import qemu_img, qemu_io
29import struct
30import errno
31
32backing_img = os.path.join(iotests.test_dir, 'backing.img')
33mid_img = os.path.join(iotests.test_dir, 'mid.img')
34test_img = os.path.join(iotests.test_dir, 'test.img')
35
36class ImageCommitTestCase(iotests.QMPTestCase):
37    '''Abstract base class for image commit test cases'''
38
39    def wait_for_complete(self, need_ready=False):
40        completed = False
41        ready = False
42        while not completed:
43            for event in self.vm.get_qmp_events(wait=True):
44                if event['event'] == 'BLOCK_JOB_COMPLETED':
45                    self.assert_qmp_absent(event, 'data/error')
46                    self.assert_qmp(event, 'data/type', 'commit')
47                    self.assert_qmp(event, 'data/device', 'drive0')
48                    self.assert_qmp(event, 'data/offset', event['data']['len'])
49                    if need_ready:
50                        self.assertTrue(ready, "Expecting BLOCK_JOB_COMPLETED event")
51                    completed = True
52                elif event['event'] == 'BLOCK_JOB_READY':
53                    ready = True
54                    self.assert_qmp(event, 'data/type', 'commit')
55                    self.assert_qmp(event, 'data/device', 'drive0')
56                    self.vm.qmp('block-job-complete', device='drive0')
57
58        self.assert_no_active_block_jobs()
59        self.vm.shutdown()
60
61    def run_commit_test(self, top, base, need_ready=False, node_names=False):
62        self.assert_no_active_block_jobs()
63        if node_names:
64            result = self.vm.qmp('block-commit', device='drive0', top_node=top, base_node=base)
65            self.assert_qmp(result, 'return', {})
66        else:
67            result = self.vm.qmp('block-commit', device='drive0', top=top, base=base)
68            self.assert_qmp(result, 'return', {})
69        self.wait_for_complete(need_ready)
70
71    def run_default_commit_test(self):
72        self.assert_no_active_block_jobs()
73        result = self.vm.qmp('block-commit', device='drive0')
74        self.assert_qmp(result, 'return', {})
75        self.wait_for_complete()
76
77class TestSingleDrive(ImageCommitTestCase):
78    # Need some space after the copied data so that throttling is effective in
79    # tests that use it rather than just completing the job immediately
80    image_len = 2 * 1024 * 1024
81    test_len = 1 * 1024 * 256
82
83    def setUp(self):
84        iotests.create_image(backing_img, self.image_len)
85        qemu_img('create', '-f', iotests.imgfmt,
86                 '-o', 'backing_file=%s' % backing_img, '-F', 'raw', mid_img)
87        qemu_img('create', '-f', iotests.imgfmt,
88                 '-o', 'backing_file=%s' % mid_img,
89                 '-F', iotests.imgfmt, test_img)
90        if self.image_len:
91            qemu_io('-f', 'raw', '-c', 'write -P 0xab 0 524288', backing_img)
92            qemu_io('-f', iotests.imgfmt, '-c', 'write -P 0xef 524288 524288',
93                    mid_img)
94        self.vm = iotests.VM().add_drive(test_img, "node-name=top,backing.node-name=mid,backing.backing.node-name=base", interface="none")
95        self.vm.add_device('virtio-scsi')
96        self.vm.add_device("scsi-hd,id=scsi0,drive=drive0")
97        self.vm.launch()
98
99    def tearDown(self):
100        self.vm.shutdown()
101        os.remove(test_img)
102        os.remove(mid_img)
103        os.remove(backing_img)
104
105    def test_commit(self):
106        self.run_commit_test(mid_img, backing_img)
107        if not self.image_len:
108            return
109        qemu_io('-f', 'raw', '-c', 'read -P 0xab 0 524288', backing_img)
110        qemu_io('-f', 'raw', '-c', 'read -P 0xef 524288 524288', backing_img)
111
112    def test_commit_node(self):
113        self.run_commit_test("mid", "base", node_names=True)
114        if not self.image_len:
115            return
116        qemu_io('-f', 'raw', '-c', 'read -P 0xab 0 524288', backing_img)
117        qemu_io('-f', 'raw', '-c', 'read -P 0xef 524288 524288', backing_img)
118
119    @iotests.skip_if_unsupported(['throttle'])
120    def test_commit_with_filter_and_quit(self):
121        result = self.vm.qmp('object-add', qom_type='throttle-group', id='tg')
122        self.assert_qmp(result, 'return', {})
123
124        # Add a filter outside of the backing chain
125        result = self.vm.qmp('blockdev-add', driver='throttle', node_name='filter', throttle_group='tg', file='mid')
126        self.assert_qmp(result, 'return', {})
127
128        result = self.vm.qmp('block-commit', device='drive0')
129        self.assert_qmp(result, 'return', {})
130
131        # Quit immediately, thus forcing a simultaneous cancel of the
132        # block job and a bdrv_drain_all()
133        result = self.vm.qmp('quit')
134        self.assert_qmp(result, 'return', {})
135
136    # Same as above, but this time we add the filter after starting the job
137    @iotests.skip_if_unsupported(['throttle'])
138    def test_commit_plus_filter_and_quit(self):
139        result = self.vm.qmp('object-add', qom_type='throttle-group', id='tg')
140        self.assert_qmp(result, 'return', {})
141
142        result = self.vm.qmp('block-commit', device='drive0')
143        self.assert_qmp(result, 'return', {})
144
145        # Add a filter outside of the backing chain
146        result = self.vm.qmp('blockdev-add', driver='throttle', node_name='filter', throttle_group='tg', file='mid')
147        self.assert_qmp(result, 'return', {})
148
149        # Quit immediately, thus forcing a simultaneous cancel of the
150        # block job and a bdrv_drain_all()
151        result = self.vm.qmp('quit')
152        self.assert_qmp(result, 'return', {})
153
154    def test_device_not_found(self):
155        result = self.vm.qmp('block-commit', device='nonexistent', top='%s' % mid_img)
156        self.assert_qmp(result, 'error/class', 'DeviceNotFound')
157
158    def test_top_same_base(self):
159        self.assert_no_active_block_jobs()
160        result = self.vm.qmp('block-commit', device='drive0', top='%s' % backing_img, base='%s' % backing_img)
161        self.assert_qmp(result, 'error/class', 'GenericError')
162        self.assert_qmp(result, 'error/desc', "Can't find '%s' in the backing chain" % backing_img)
163
164    def test_top_invalid(self):
165        self.assert_no_active_block_jobs()
166        result = self.vm.qmp('block-commit', device='drive0', top='badfile', base='%s' % backing_img)
167        self.assert_qmp(result, 'error/class', 'GenericError')
168        self.assert_qmp(result, 'error/desc', 'Top image file badfile not found')
169
170    def test_base_invalid(self):
171        self.assert_no_active_block_jobs()
172        result = self.vm.qmp('block-commit', device='drive0', top='%s' % mid_img, base='badfile')
173        self.assert_qmp(result, 'error/class', 'GenericError')
174        self.assert_qmp(result, 'error/desc', "Can't find 'badfile' in the backing chain")
175
176    def test_top_node_invalid(self):
177        self.assert_no_active_block_jobs()
178        result = self.vm.qmp('block-commit', device='drive0', top_node='badfile', base_node='base')
179        self.assert_qmp(result, 'error/class', 'GenericError')
180        self.assert_qmp(result, 'error/desc', "Cannot find device='' nor node-name='badfile'")
181
182    def test_base_node_invalid(self):
183        self.assert_no_active_block_jobs()
184        result = self.vm.qmp('block-commit', device='drive0', top_node='mid', base_node='badfile')
185        self.assert_qmp(result, 'error/class', 'GenericError')
186        self.assert_qmp(result, 'error/desc', "Cannot find device='' nor node-name='badfile'")
187
188    def test_top_path_and_node(self):
189        self.assert_no_active_block_jobs()
190        result = self.vm.qmp('block-commit', device='drive0', top_node='mid', base_node='base', top='%s' % mid_img)
191        self.assert_qmp(result, 'error/class', 'GenericError')
192        self.assert_qmp(result, 'error/desc', "'top-node' and 'top' are mutually exclusive")
193
194    def test_base_path_and_node(self):
195        self.assert_no_active_block_jobs()
196        result = self.vm.qmp('block-commit', device='drive0', top_node='mid', base_node='base', base='%s' % backing_img)
197        self.assert_qmp(result, 'error/class', 'GenericError')
198        self.assert_qmp(result, 'error/desc', "'base-node' and 'base' are mutually exclusive")
199
200    def test_top_is_active(self):
201        self.run_commit_test(test_img, backing_img, need_ready=True)
202        if not self.image_len:
203            return
204        qemu_io('-f', 'raw', '-c', 'read -P 0xab 0 524288', backing_img)
205        qemu_io('-f', 'raw', '-c', 'read -P 0xef 524288 524288', backing_img)
206
207    def test_top_is_default_active(self):
208        self.run_default_commit_test()
209        if not self.image_len:
210            return
211        qemu_io('-f', 'raw', '-c', 'read -P 0xab 0 524288', backing_img)
212        qemu_io('-f', 'raw', '-c', 'read -P 0xef 524288 524288', backing_img)
213
214    def test_top_and_base_reversed(self):
215        self.assert_no_active_block_jobs()
216        result = self.vm.qmp('block-commit', device='drive0', top='%s' % backing_img, base='%s' % mid_img)
217        self.assert_qmp(result, 'error/class', 'GenericError')
218        self.assert_qmp(result, 'error/desc', "Can't find '%s' in the backing chain" % mid_img)
219
220    def test_top_and_base_node_reversed(self):
221        self.assert_no_active_block_jobs()
222        result = self.vm.qmp('block-commit', device='drive0', top_node='base', base_node='top')
223        self.assert_qmp(result, 'error/class', 'GenericError')
224        self.assert_qmp(result, 'error/desc', "'top' is not in this backing file chain")
225
226    def test_top_node_in_wrong_chain(self):
227        self.assert_no_active_block_jobs()
228
229        result = self.vm.qmp('blockdev-add', driver='null-co', node_name='null')
230        self.assert_qmp(result, 'return', {})
231
232        result = self.vm.qmp('block-commit', device='drive0', top_node='null', base_node='base')
233        self.assert_qmp(result, 'error/class', 'GenericError')
234        self.assert_qmp(result, 'error/desc', "'null' is not in this backing file chain")
235
236    # When the job is running on a BB that is automatically deleted on hot
237    # unplug, the job is cancelled when the device disappears
238    def test_hot_unplug(self):
239        if self.image_len == 0:
240            return
241
242        self.assert_no_active_block_jobs()
243        result = self.vm.qmp('block-commit', device='drive0', top=mid_img,
244                             base=backing_img, speed=(self.image_len // 4))
245        self.assert_qmp(result, 'return', {})
246        result = self.vm.qmp('device_del', id='scsi0')
247        self.assert_qmp(result, 'return', {})
248
249        cancelled = False
250        deleted = False
251        while not cancelled or not deleted:
252            for event in self.vm.get_qmp_events(wait=True):
253                if event['event'] == 'DEVICE_DELETED':
254                    self.assert_qmp(event, 'data/device', 'scsi0')
255                    deleted = True
256                elif event['event'] == 'BLOCK_JOB_CANCELLED':
257                    self.assert_qmp(event, 'data/device', 'drive0')
258                    cancelled = True
259                elif event['event'] == 'JOB_STATUS_CHANGE':
260                    self.assert_qmp(event, 'data/id', 'drive0')
261                else:
262                    self.fail("Unexpected event %s" % (event['event']))
263
264        self.assert_no_active_block_jobs()
265
266    # Tests that the insertion of the commit_top filter node doesn't make a
267    # difference to query-blockstat
268    def test_implicit_node(self):
269        if self.image_len == 0:
270            return
271
272        self.assert_no_active_block_jobs()
273        result = self.vm.qmp('block-commit', device='drive0', top=mid_img,
274                             base=backing_img, speed=(self.image_len // 4))
275        self.assert_qmp(result, 'return', {})
276
277        result = self.vm.qmp('query-block')
278        self.assert_qmp(result, 'return[0]/inserted/file', test_img)
279        self.assert_qmp(result, 'return[0]/inserted/drv', iotests.imgfmt)
280        self.assert_qmp(result, 'return[0]/inserted/backing_file', mid_img)
281        self.assert_qmp(result, 'return[0]/inserted/backing_file_depth', 2)
282        self.assert_qmp(result, 'return[0]/inserted/image/filename', test_img)
283        self.assert_qmp(result, 'return[0]/inserted/image/backing-image/filename', mid_img)
284        self.assert_qmp(result, 'return[0]/inserted/image/backing-image/backing-image/filename', backing_img)
285
286        result = self.vm.qmp('query-blockstats')
287        self.assert_qmp(result, 'return[0]/node-name', 'top')
288        self.assert_qmp(result, 'return[0]/backing/node-name', 'mid')
289        self.assert_qmp(result, 'return[0]/backing/backing/node-name', 'base')
290
291        self.cancel_and_wait()
292        self.assert_no_active_block_jobs()
293
294class TestRelativePaths(ImageCommitTestCase):
295    image_len = 1 * 1024 * 1024
296    test_len = 1 * 1024 * 256
297
298    dir1 = "dir1"
299    dir2 = "dir2/"
300    dir3 = "dir2/dir3/"
301
302    test_img = os.path.join(iotests.test_dir, dir3, 'test.img')
303    mid_img = "../mid.img"
304    backing_img = "../dir1/backing.img"
305
306    backing_img_abs = os.path.join(iotests.test_dir, dir1, 'backing.img')
307    mid_img_abs = os.path.join(iotests.test_dir, dir2, 'mid.img')
308
309    def setUp(self):
310        try:
311            os.mkdir(os.path.join(iotests.test_dir, self.dir1))
312            os.mkdir(os.path.join(iotests.test_dir, self.dir2))
313            os.mkdir(os.path.join(iotests.test_dir, self.dir3))
314        except OSError as exception:
315            if exception.errno != errno.EEXIST:
316                raise
317        iotests.create_image(self.backing_img_abs, TestRelativePaths.image_len)
318        qemu_img('create', '-f', iotests.imgfmt,
319                 '-o', 'backing_file=%s' % self.backing_img_abs,
320                 '-F', 'raw', self.mid_img_abs)
321        qemu_img('create', '-f', iotests.imgfmt,
322                 '-o', 'backing_file=%s' % self.mid_img_abs,
323                 '-F', iotests.imgfmt, self.test_img)
324        qemu_img('rebase', '-u', '-b', self.backing_img,
325                 '-F', 'raw', self.mid_img_abs)
326        qemu_img('rebase', '-u', '-b', self.mid_img,
327                 '-F', iotests.imgfmt, self.test_img)
328        qemu_io('-f', 'raw', '-c', 'write -P 0xab 0 524288', self.backing_img_abs)
329        qemu_io('-f', iotests.imgfmt, '-c', 'write -P 0xef 524288 524288', self.mid_img_abs)
330        self.vm = iotests.VM().add_drive(self.test_img)
331        self.vm.launch()
332
333    def tearDown(self):
334        self.vm.shutdown()
335        os.remove(self.test_img)
336        os.remove(self.mid_img_abs)
337        os.remove(self.backing_img_abs)
338        try:
339            os.rmdir(os.path.join(iotests.test_dir, self.dir1))
340            os.rmdir(os.path.join(iotests.test_dir, self.dir3))
341            os.rmdir(os.path.join(iotests.test_dir, self.dir2))
342        except OSError as exception:
343            if exception.errno != errno.EEXIST and exception.errno != errno.ENOTEMPTY:
344                raise
345
346    def test_commit(self):
347        self.run_commit_test(self.mid_img, self.backing_img)
348        qemu_io('-f', 'raw', '-c', 'read -P 0xab 0 524288', self.backing_img_abs)
349        qemu_io('-f', 'raw', '-c', 'read -P 0xef 524288 524288', self.backing_img_abs)
350
351    def test_device_not_found(self):
352        result = self.vm.qmp('block-commit', device='nonexistent', top='%s' % self.mid_img)
353        self.assert_qmp(result, 'error/class', 'DeviceNotFound')
354
355    def test_top_same_base(self):
356        self.assert_no_active_block_jobs()
357        result = self.vm.qmp('block-commit', device='drive0', top='%s' % self.mid_img, base='%s' % self.mid_img)
358        self.assert_qmp(result, 'error/class', 'GenericError')
359        self.assert_qmp(result, 'error/desc', "Can't find '%s' in the backing chain" % self.mid_img)
360
361    def test_top_invalid(self):
362        self.assert_no_active_block_jobs()
363        result = self.vm.qmp('block-commit', device='drive0', top='badfile', base='%s' % self.backing_img)
364        self.assert_qmp(result, 'error/class', 'GenericError')
365        self.assert_qmp(result, 'error/desc', 'Top image file badfile not found')
366
367    def test_base_invalid(self):
368        self.assert_no_active_block_jobs()
369        result = self.vm.qmp('block-commit', device='drive0', top='%s' % self.mid_img, base='badfile')
370        self.assert_qmp(result, 'error/class', 'GenericError')
371        self.assert_qmp(result, 'error/desc', "Can't find 'badfile' in the backing chain")
372
373    def test_top_is_active(self):
374        self.run_commit_test(self.test_img, self.backing_img)
375        qemu_io('-f', 'raw', '-c', 'read -P 0xab 0 524288', self.backing_img_abs)
376        qemu_io('-f', 'raw', '-c', 'read -P 0xef 524288 524288', self.backing_img_abs)
377
378    def test_top_and_base_reversed(self):
379        self.assert_no_active_block_jobs()
380        result = self.vm.qmp('block-commit', device='drive0', top='%s' % self.backing_img, base='%s' % self.mid_img)
381        self.assert_qmp(result, 'error/class', 'GenericError')
382        self.assert_qmp(result, 'error/desc', "Can't find '%s' in the backing chain" % self.mid_img)
383
384
385class TestSetSpeed(ImageCommitTestCase):
386    image_len = 80 * 1024 * 1024 # MB
387
388    def setUp(self):
389        qemu_img('create', backing_img, str(TestSetSpeed.image_len))
390        qemu_img('create', '-f', iotests.imgfmt,
391                 '-o', 'backing_file=%s' % backing_img, '-F', 'raw', mid_img)
392        qemu_img('create', '-f', iotests.imgfmt,
393                 '-o', 'backing_file=%s' % mid_img,
394                 '-F', iotests.imgfmt, test_img)
395        qemu_io('-f', iotests.imgfmt, '-c', 'write -P 0x1 0 512', test_img)
396        qemu_io('-f', iotests.imgfmt, '-c', 'write -P 0xef 524288 524288', mid_img)
397        self.vm = iotests.VM().add_drive('blkdebug::' + test_img)
398        self.vm.launch()
399
400    def tearDown(self):
401        self.vm.shutdown()
402        os.remove(test_img)
403        os.remove(mid_img)
404        os.remove(backing_img)
405
406    def test_set_speed(self):
407        self.assert_no_active_block_jobs()
408
409        self.vm.pause_drive('drive0')
410        result = self.vm.qmp('block-commit', device='drive0', top=mid_img, speed=1024 * 1024)
411        self.assert_qmp(result, 'return', {})
412
413        # Ensure the speed we set was accepted
414        result = self.vm.qmp('query-block-jobs')
415        self.assert_qmp(result, 'return[0]/device', 'drive0')
416        self.assert_qmp(result, 'return[0]/speed', 1024 * 1024)
417
418        self.cancel_and_wait(resume=True)
419
420class TestActiveZeroLengthImage(TestSingleDrive):
421    image_len = 0
422
423class TestReopenOverlay(ImageCommitTestCase):
424    image_len = 1024 * 1024
425    img0 = os.path.join(iotests.test_dir, '0.img')
426    img1 = os.path.join(iotests.test_dir, '1.img')
427    img2 = os.path.join(iotests.test_dir, '2.img')
428    img3 = os.path.join(iotests.test_dir, '3.img')
429
430    def setUp(self):
431        iotests.create_image(self.img0, self.image_len)
432        qemu_img('create', '-f', iotests.imgfmt,
433                 '-o', 'backing_file=%s' % self.img0, '-F', 'raw', self.img1)
434        qemu_img('create', '-f', iotests.imgfmt,
435                 '-o', 'backing_file=%s' % self.img1,
436                 '-F', iotests.imgfmt, self.img2)
437        qemu_img('create', '-f', iotests.imgfmt,
438                 '-o', 'backing_file=%s' % self.img2,
439                 '-F', iotests.imgfmt, self.img3)
440        qemu_io('-f', iotests.imgfmt, '-c', 'write -P 0xab 0 128K', self.img1)
441        self.vm = iotests.VM().add_drive(self.img3)
442        self.vm.launch()
443
444    def tearDown(self):
445        self.vm.shutdown()
446        os.remove(self.img0)
447        os.remove(self.img1)
448        os.remove(self.img2)
449        os.remove(self.img3)
450
451    # This tests what happens when the overlay image of the 'top' node
452    # needs to be reopened in read-write mode in order to update the
453    # backing image string.
454    def test_reopen_overlay(self):
455        self.run_commit_test(self.img1, self.img0)
456
457class TestErrorHandling(iotests.QMPTestCase):
458    image_len = 2 * 1024 * 1024
459
460    def setUp(self):
461        iotests.create_image(backing_img, self.image_len)
462        qemu_img('create', '-f', iotests.imgfmt,
463                 '-o', 'backing_file=%s' % backing_img,
464                 '-F', 'raw', mid_img)
465        qemu_img('create', '-f', iotests.imgfmt,
466                 '-o', 'backing_file=%s' % mid_img,
467                 '-F', iotests.imgfmt, test_img)
468
469        qemu_io('-f', iotests.imgfmt, '-c', 'write -P 0x11 0 512k', mid_img)
470        qemu_io('-f', iotests.imgfmt, '-c', 'write -P 0x22 0 512k', test_img)
471
472        self.vm = iotests.VM()
473        self.vm.launch()
474
475        self.blkdebug_file = iotests.file_path("blkdebug.conf")
476
477    def tearDown(self):
478        self.vm.shutdown()
479        os.remove(test_img)
480        os.remove(mid_img)
481        os.remove(backing_img)
482
483    def blockdev_add(self, **kwargs):
484        result = self.vm.qmp('blockdev-add', **kwargs)
485        self.assert_qmp(result, 'return', {})
486
487    def add_block_nodes(self, base_debug=None, mid_debug=None, top_debug=None):
488        self.blockdev_add(node_name='base-file', driver='file',
489                          filename=backing_img)
490        self.blockdev_add(node_name='mid-file', driver='file',
491                          filename=mid_img)
492        self.blockdev_add(node_name='top-file', driver='file',
493                          filename=test_img)
494
495        if base_debug:
496            self.blockdev_add(node_name='base-dbg', driver='blkdebug',
497                              image='base-file', inject_error=base_debug)
498        if mid_debug:
499            self.blockdev_add(node_name='mid-dbg', driver='blkdebug',
500                              image='mid-file', inject_error=mid_debug)
501        if top_debug:
502            self.blockdev_add(node_name='top-dbg', driver='blkdebug',
503                              image='top-file', inject_error=top_debug)
504
505        self.blockdev_add(node_name='base-fmt', driver='raw',
506                          file=('base-dbg' if base_debug else 'base-file'))
507        self.blockdev_add(node_name='mid-fmt', driver=iotests.imgfmt,
508                          file=('mid-dbg' if mid_debug else 'mid-file'),
509                          backing='base-fmt')
510        self.blockdev_add(node_name='top-fmt', driver=iotests.imgfmt,
511                          file=('top-dbg' if top_debug else 'top-file'),
512                          backing='mid-fmt')
513
514    def run_job(self, expected_events, error_pauses_job=False):
515        match_device = {'data': {'device': 'job0'}}
516        events = [
517            ('BLOCK_JOB_COMPLETED', match_device),
518            ('BLOCK_JOB_CANCELLED', match_device),
519            ('BLOCK_JOB_ERROR', match_device),
520            ('BLOCK_JOB_READY', match_device),
521        ]
522
523        completed = False
524        log = []
525        while not completed:
526            ev = self.vm.events_wait(events, timeout=5.0)
527            if ev['event'] == 'BLOCK_JOB_COMPLETED':
528                completed = True
529            elif ev['event'] == 'BLOCK_JOB_ERROR':
530                if error_pauses_job:
531                    result = self.vm.qmp('block-job-resume', device='job0')
532                    self.assert_qmp(result, 'return', {})
533            elif ev['event'] == 'BLOCK_JOB_READY':
534                result = self.vm.qmp('block-job-complete', device='job0')
535                self.assert_qmp(result, 'return', {})
536            else:
537                self.fail("Unexpected event: %s" % ev)
538            log.append(iotests.filter_qmp_event(ev))
539
540        self.maxDiff = None
541        self.assertEqual(expected_events, log)
542
543    def event_error(self, op, action):
544        return {
545            'event': 'BLOCK_JOB_ERROR',
546            'data': {'action': action, 'device': 'job0', 'operation': op},
547            'timestamp': {'microseconds': 'USECS', 'seconds': 'SECS'}
548        }
549
550    def event_ready(self):
551        return {
552            'event': 'BLOCK_JOB_READY',
553            'data': {'device': 'job0',
554                     'len': 524288,
555                     'offset': 524288,
556                     'speed': 0,
557                     'type': 'commit'},
558            'timestamp': {'microseconds': 'USECS', 'seconds': 'SECS'},
559        }
560
561    def event_completed(self, errmsg=None, active=True):
562        max_len = 524288 if active else self.image_len
563        data = {
564            'device': 'job0',
565            'len': max_len,
566            'offset': 0 if errmsg else max_len,
567            'speed': 0,
568            'type': 'commit'
569        }
570        if errmsg:
571            data['error'] = errmsg
572
573        return {
574            'event': 'BLOCK_JOB_COMPLETED',
575            'data': data,
576            'timestamp': {'microseconds': 'USECS', 'seconds': 'SECS'},
577        }
578
579    def blkdebug_event(self, event, is_raw=False):
580        if event:
581            return [{
582                'event': event,
583                'sector': 512 if is_raw else 1024,
584                'once': True,
585            }]
586        return None
587
588    def prepare_and_start_job(self, on_error, active=True,
589                              top_event=None, mid_event=None, base_event=None):
590
591        top_debug = self.blkdebug_event(top_event)
592        mid_debug = self.blkdebug_event(mid_event)
593        base_debug = self.blkdebug_event(base_event, True)
594
595        self.add_block_nodes(top_debug=top_debug, mid_debug=mid_debug,
596                             base_debug=base_debug)
597
598        result = self.vm.qmp('block-commit', job_id='job0', device='top-fmt',
599                             top_node='top-fmt' if active else 'mid-fmt',
600                             base_node='mid-fmt' if active else 'base-fmt',
601                             on_error=on_error)
602        self.assert_qmp(result, 'return', {})
603
604    def testActiveReadErrorReport(self):
605        self.prepare_and_start_job('report', top_event='read_aio')
606        self.run_job([
607            self.event_error('read', 'report'),
608            self.event_completed('Input/output error')
609        ])
610
611        self.vm.shutdown()
612        self.assertFalse(iotests.compare_images(test_img, mid_img),
613                         'target image matches source after error')
614
615    def testActiveReadErrorStop(self):
616        self.prepare_and_start_job('stop', top_event='read_aio')
617        self.run_job([
618            self.event_error('read', 'stop'),
619            self.event_ready(),
620            self.event_completed()
621        ], error_pauses_job=True)
622
623        self.vm.shutdown()
624        self.assertTrue(iotests.compare_images(test_img, mid_img),
625                        'target image does not match source after commit')
626
627    def testActiveReadErrorIgnore(self):
628        self.prepare_and_start_job('ignore', top_event='read_aio')
629        self.run_job([
630            self.event_error('read', 'ignore'),
631            self.event_ready(),
632            self.event_completed()
633        ])
634
635        # For commit, 'ignore' actually means retry, so this will succeed
636        self.vm.shutdown()
637        self.assertTrue(iotests.compare_images(test_img, mid_img),
638                        'target image does not match source after commit')
639
640    def testActiveWriteErrorReport(self):
641        self.prepare_and_start_job('report', mid_event='write_aio')
642        self.run_job([
643            self.event_error('write', 'report'),
644            self.event_completed('Input/output error')
645        ])
646
647        self.vm.shutdown()
648        self.assertFalse(iotests.compare_images(test_img, mid_img),
649                         'target image matches source after error')
650
651    def testActiveWriteErrorStop(self):
652        self.prepare_and_start_job('stop', mid_event='write_aio')
653        self.run_job([
654            self.event_error('write', 'stop'),
655            self.event_ready(),
656            self.event_completed()
657        ], error_pauses_job=True)
658
659        self.vm.shutdown()
660        self.assertTrue(iotests.compare_images(test_img, mid_img),
661                        'target image does not match source after commit')
662
663    def testActiveWriteErrorIgnore(self):
664        self.prepare_and_start_job('ignore', mid_event='write_aio')
665        self.run_job([
666            self.event_error('write', 'ignore'),
667            self.event_ready(),
668            self.event_completed()
669        ])
670
671        # For commit, 'ignore' actually means retry, so this will succeed
672        self.vm.shutdown()
673        self.assertTrue(iotests.compare_images(test_img, mid_img),
674                        'target image does not match source after commit')
675
676    def testIntermediateReadErrorReport(self):
677        self.prepare_and_start_job('report', active=False, mid_event='read_aio')
678        self.run_job([
679            self.event_error('read', 'report'),
680            self.event_completed('Input/output error', active=False)
681        ])
682
683        self.vm.shutdown()
684        self.assertFalse(iotests.compare_images(mid_img, backing_img, fmt2='raw'),
685                         'target image matches source after error')
686
687    def testIntermediateReadErrorStop(self):
688        self.prepare_and_start_job('stop', active=False, mid_event='read_aio')
689        self.run_job([
690            self.event_error('read', 'stop'),
691            self.event_completed(active=False)
692        ], error_pauses_job=True)
693
694        self.vm.shutdown()
695        self.assertTrue(iotests.compare_images(mid_img, backing_img, fmt2='raw'),
696                        'target image does not match source after commit')
697
698    def testIntermediateReadErrorIgnore(self):
699        self.prepare_and_start_job('ignore', active=False, mid_event='read_aio')
700        self.run_job([
701            self.event_error('read', 'ignore'),
702            self.event_completed(active=False)
703        ])
704
705        # For commit, 'ignore' actually means retry, so this will succeed
706        self.vm.shutdown()
707        self.assertTrue(iotests.compare_images(mid_img, backing_img, fmt2='raw'),
708                        'target image does not match source after commit')
709
710    def testIntermediateWriteErrorReport(self):
711        self.prepare_and_start_job('report', active=False, base_event='write_aio')
712        self.run_job([
713            self.event_error('write', 'report'),
714            self.event_completed('Input/output error', active=False)
715        ])
716
717        self.vm.shutdown()
718        self.assertFalse(iotests.compare_images(mid_img, backing_img, fmt2='raw'),
719                         'target image matches source after error')
720
721    def testIntermediateWriteErrorStop(self):
722        self.prepare_and_start_job('stop', active=False, base_event='write_aio')
723        self.run_job([
724            self.event_error('write', 'stop'),
725            self.event_completed(active=False)
726        ], error_pauses_job=True)
727
728        self.vm.shutdown()
729        self.assertTrue(iotests.compare_images(mid_img, backing_img, fmt2='raw'),
730                        'target image does not match source after commit')
731
732    def testIntermediateWriteErrorIgnore(self):
733        self.prepare_and_start_job('ignore', active=False, base_event='write_aio')
734        self.run_job([
735            self.event_error('write', 'ignore'),
736            self.event_completed(active=False)
737        ])
738
739        # For commit, 'ignore' actually means retry, so this will succeed
740        self.vm.shutdown()
741        self.assertTrue(iotests.compare_images(mid_img, backing_img, fmt2='raw'),
742                        'target image does not match source after commit')
743
744class TestCommitWithFilters(iotests.QMPTestCase):
745    img0 = os.path.join(iotests.test_dir, '0.img')
746    img1 = os.path.join(iotests.test_dir, '1.img')
747    img2 = os.path.join(iotests.test_dir, '2.img')
748    img3 = os.path.join(iotests.test_dir, '3.img')
749
750    def do_test_io(self, read_or_write):
751        for index, pattern_file in enumerate(self.pattern_files):
752            qemu_io('-f', iotests.imgfmt,
753                    '-c',
754                    f'{read_or_write} -P {index + 1} {index}M 1M',
755                    pattern_file)
756
757    @iotests.skip_if_unsupported(['throttle'])
758    def setUp(self):
759        qemu_img('create', '-f', iotests.imgfmt, self.img0, '64M')
760        qemu_img('create', '-f', iotests.imgfmt, self.img1, '64M')
761        qemu_img('create', '-f', iotests.imgfmt, self.img2, '64M')
762        qemu_img('create', '-f', iotests.imgfmt, self.img3, '64M')
763
764        # Distributions of the patterns in the files; this is checked
765        # by tearDown() and should be changed by the test cases as is
766        # necessary
767        self.pattern_files = [self.img0, self.img1, self.img2, self.img3]
768
769        self.do_test_io('write')
770
771        self.vm = iotests.VM().add_device('virtio-scsi,id=vio-scsi')
772        self.vm.launch()
773
774        result = self.vm.qmp('object-add', qom_type='throttle-group', id='tg')
775        self.assert_qmp(result, 'return', {})
776
777        result = self.vm.qmp('blockdev-add', **{
778                'node-name': 'top-filter',
779                'driver': 'throttle',
780                'throttle-group': 'tg',
781                'file': {
782                    'node-name': 'cow-3',
783                    'driver': iotests.imgfmt,
784                    'file': {
785                        'driver': 'file',
786                        'filename': self.img3
787                    },
788                    'backing': {
789                        'node-name': 'cow-2',
790                        'driver': iotests.imgfmt,
791                        'file': {
792                            'driver': 'file',
793                            'filename': self.img2
794                        },
795                        'backing': {
796                            'node-name': 'cow-1',
797                            'driver': iotests.imgfmt,
798                            'file': {
799                                'driver': 'file',
800                                'filename': self.img1
801                            },
802                            'backing': {
803                                'node-name': 'bottom-filter',
804                                'driver': 'throttle',
805                                'throttle-group': 'tg',
806                                'file': {
807                                    'node-name': 'cow-0',
808                                    'driver': iotests.imgfmt,
809                                    'file': {
810                                        'driver': 'file',
811                                        'filename': self.img0
812                                    }
813                                }
814                            }
815                        }
816                    }
817                }
818            })
819        self.assert_qmp(result, 'return', {})
820
821    def tearDown(self):
822        self.vm.shutdown()
823        self.do_test_io('read')
824
825        os.remove(self.img3)
826        os.remove(self.img2)
827        os.remove(self.img1)
828        os.remove(self.img0)
829
830    # Filters make for funny filenames, so we cannot just use
831    # self.imgX to get them
832    def get_filename(self, node):
833        return self.vm.node_info(node)['image']['filename']
834
835    def test_filterless_commit(self):
836        result = self.vm.qmp('block-commit',
837                             job_id='commit',
838                             device='top-filter',
839                             top_node='cow-2',
840                             base_node='cow-1',
841                             backing_file=self.img1)
842        self.assert_qmp(result, 'return', {})
843        self.wait_until_completed(drive='commit')
844
845        self.assertIsNotNone(self.vm.node_info('cow-3'))
846        self.assertIsNone(self.vm.node_info('cow-2'))
847        self.assertIsNotNone(self.vm.node_info('cow-1'))
848
849        # 2 has been committed into 1
850        self.pattern_files[2] = self.img1
851
852    def test_commit_through_filter(self):
853        result = self.vm.qmp('block-commit',
854                             job_id='commit',
855                             device='top-filter',
856                             top_node='cow-1',
857                             base_node='cow-0',
858                             backing_file=self.img0)
859        self.assert_qmp(result, 'return', {})
860        self.wait_until_completed(drive='commit')
861
862        self.assertIsNotNone(self.vm.node_info('cow-2'))
863        self.assertIsNone(self.vm.node_info('cow-1'))
864        self.assertIsNone(self.vm.node_info('bottom-filter'))
865        self.assertIsNotNone(self.vm.node_info('cow-0'))
866
867        # 1 has been committed into 0
868        self.pattern_files[1] = self.img0
869
870    def test_filtered_active_commit_with_filter(self):
871        # Add a device, so the commit job finds a parent it can change
872        # to point to the base node (so we can test that top-filter is
873        # dropped from the graph)
874        result = self.vm.qmp('device_add', id='drv0', driver='scsi-hd',
875                             bus='vio-scsi.0', drive='top-filter')
876        self.assert_qmp(result, 'return', {})
877
878        # Try to release our reference to top-filter; that should not
879        # work because drv0 uses it
880        result = self.vm.qmp('blockdev-del', node_name='top-filter')
881        self.assert_qmp(result, 'error/class', 'GenericError')
882        self.assert_qmp(result, 'error/desc', 'Node top-filter is in use')
883
884        result = self.vm.qmp('block-commit',
885                             job_id='commit',
886                             device='top-filter',
887                             base_node='cow-2')
888        self.assert_qmp(result, 'return', {})
889        self.complete_and_wait(drive='commit')
890
891        # Try to release our reference to top-filter again
892        result = self.vm.qmp('blockdev-del', node_name='top-filter')
893        self.assert_qmp(result, 'return', {})
894
895        self.assertIsNone(self.vm.node_info('top-filter'))
896        self.assertIsNone(self.vm.node_info('cow-3'))
897        self.assertIsNotNone(self.vm.node_info('cow-2'))
898
899        # Check that drv0 is now connected to cow-2
900        blockdevs = self.vm.qmp('query-block')['return']
901        drv0 = next(dev for dev in blockdevs if dev['qdev'] == 'drv0')
902        self.assertEqual(drv0['inserted']['node-name'], 'cow-2')
903
904        # 3 has been committed into 2
905        self.pattern_files[3] = self.img2
906
907    def test_filtered_active_commit_without_filter(self):
908        result = self.vm.qmp('block-commit',
909                             job_id='commit',
910                             device='top-filter',
911                             top_node='cow-3',
912                             base_node='cow-2')
913        self.assert_qmp(result, 'return', {})
914        self.complete_and_wait(drive='commit')
915
916        self.assertIsNotNone(self.vm.node_info('top-filter'))
917        self.assertIsNone(self.vm.node_info('cow-3'))
918        self.assertIsNotNone(self.vm.node_info('cow-2'))
919
920        # 3 has been committed into 2
921        self.pattern_files[3] = self.img2
922
923class TestCommitWithOverriddenBacking(iotests.QMPTestCase):
924    img_base_a = os.path.join(iotests.test_dir, 'base_a.img')
925    img_base_b = os.path.join(iotests.test_dir, 'base_b.img')
926    img_top = os.path.join(iotests.test_dir, 'top.img')
927
928    def setUp(self):
929        qemu_img('create', '-f', iotests.imgfmt, self.img_base_a, '1M')
930        qemu_img('create', '-f', iotests.imgfmt, self.img_base_b, '1M')
931        qemu_img('create', '-f', iotests.imgfmt, '-b', self.img_base_a,
932                 '-F', iotests.imgfmt, self.img_top)
933
934        self.vm = iotests.VM()
935        self.vm.launch()
936
937        # Use base_b instead of base_a as the backing of top
938        result = self.vm.qmp('blockdev-add', **{
939                                'node-name': 'top',
940                                'driver': iotests.imgfmt,
941                                'file': {
942                                    'driver': 'file',
943                                    'filename': self.img_top
944                                },
945                                'backing': {
946                                    'node-name': 'base',
947                                    'driver': iotests.imgfmt,
948                                    'file': {
949                                        'driver': 'file',
950                                        'filename': self.img_base_b
951                                    }
952                                }
953                            })
954        self.assert_qmp(result, 'return', {})
955
956    def tearDown(self):
957        self.vm.shutdown()
958        os.remove(self.img_top)
959        os.remove(self.img_base_a)
960        os.remove(self.img_base_b)
961
962    def test_commit_to_a(self):
963        # Try committing to base_a (which should fail, as top's
964        # backing image is base_b instead)
965        result = self.vm.qmp('block-commit',
966                             job_id='commit',
967                             device='top',
968                             base=self.img_base_a)
969        self.assert_qmp(result, 'error/class', 'GenericError')
970
971    def test_commit_to_b(self):
972        # Try committing to base_b (which should work, since that is
973        # actually top's backing image)
974        result = self.vm.qmp('block-commit',
975                             job_id='commit',
976                             device='top',
977                             base=self.img_base_b)
978        self.assert_qmp(result, 'return', {})
979
980        self.vm.event_wait('BLOCK_JOB_READY')
981        self.vm.qmp('block-job-complete', device='commit')
982        self.vm.event_wait('BLOCK_JOB_COMPLETED')
983
984if __name__ == '__main__':
985    iotests.main(supported_fmts=['qcow2', 'qed'],
986                 supported_protocols=['file'])
987