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