xref: /openbmc/qemu/tests/qemu-iotests/040 (revision 88cd34ee)
1#!/usr/bin/env python3
2#
3# Tests for image block commit.
4#
5# Copyright (C) 2012 IBM, Corp.
6# Copyright (C) 2012 Red Hat, Inc.
7#
8# This program is free software; you can redistribute it and/or modify
9# it under the terms of the GNU General Public License as published by
10# the Free Software Foundation; either version 2 of the License, or
11# (at your option) any later version.
12#
13# This program is distributed in the hope that it will be useful,
14# but WITHOUT ANY WARRANTY; without even the implied warranty of
15# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16# GNU General Public License for more details.
17#
18# You should have received a copy of the GNU General Public License
19# along with this program.  If not, see <http://www.gnu.org/licenses/>.
20#
21# Test for live block commit
22# Derived from Image Streaming Test 030
23
24import time
25import os
26import iotests
27from iotests import qemu_img, qemu_io
28import struct
29import errno
30
31backing_img = os.path.join(iotests.test_dir, 'backing.img')
32mid_img = os.path.join(iotests.test_dir, 'mid.img')
33test_img = os.path.join(iotests.test_dir, 'test.img')
34
35class ImageCommitTestCase(iotests.QMPTestCase):
36    '''Abstract base class for image commit test cases'''
37
38    def wait_for_complete(self, need_ready=False):
39        completed = False
40        ready = False
41        while not completed:
42            for event in self.vm.get_qmp_events(wait=True):
43                if event['event'] == 'BLOCK_JOB_COMPLETED':
44                    self.assert_qmp_absent(event, 'data/error')
45                    self.assert_qmp(event, 'data/type', 'commit')
46                    self.assert_qmp(event, 'data/device', 'drive0')
47                    self.assert_qmp(event, 'data/offset', event['data']['len'])
48                    if need_ready:
49                        self.assertTrue(ready, "Expecting BLOCK_JOB_COMPLETED event")
50                    completed = True
51                elif event['event'] == 'BLOCK_JOB_READY':
52                    ready = True
53                    self.assert_qmp(event, 'data/type', 'commit')
54                    self.assert_qmp(event, 'data/device', 'drive0')
55                    self.vm.qmp('block-job-complete', device='drive0')
56
57        self.assert_no_active_block_jobs()
58        self.vm.shutdown()
59
60    def run_commit_test(self, top, base, need_ready=False, node_names=False):
61        self.assert_no_active_block_jobs()
62        if node_names:
63            result = self.vm.qmp('block-commit', device='drive0', top_node=top, base_node=base)
64        else:
65            result = self.vm.qmp('block-commit', device='drive0', top=top, base=base)
66        self.assert_qmp(result, 'return', {})
67        self.wait_for_complete(need_ready)
68
69    def run_default_commit_test(self):
70        self.assert_no_active_block_jobs()
71        result = self.vm.qmp('block-commit', device='drive0')
72        self.assert_qmp(result, 'return', {})
73        self.wait_for_complete()
74
75class TestSingleDrive(ImageCommitTestCase):
76    # Need some space after the copied data so that throttling is effective in
77    # tests that use it rather than just completing the job immediately
78    image_len = 2 * 1024 * 1024
79    test_len = 1 * 1024 * 256
80
81    def setUp(self):
82        iotests.create_image(backing_img, self.image_len)
83        qemu_img('create', '-f', iotests.imgfmt, '-o', 'backing_file=%s' % backing_img, mid_img)
84        qemu_img('create', '-f', iotests.imgfmt, '-o', 'backing_file=%s' % mid_img, test_img)
85        qemu_io('-f', 'raw', '-c', 'write -P 0xab 0 524288', backing_img)
86        qemu_io('-f', iotests.imgfmt, '-c', 'write -P 0xef 524288 524288', mid_img)
87        self.vm = iotests.VM().add_drive(test_img, "node-name=top,backing.node-name=mid,backing.backing.node-name=base", interface="none")
88        self.vm.add_device(iotests.get_virtio_scsi_device())
89        self.vm.add_device("scsi-hd,id=scsi0,drive=drive0")
90        self.vm.launch()
91        self.has_quit = False
92
93    def tearDown(self):
94        self.vm.shutdown(has_quit=self.has_quit)
95        os.remove(test_img)
96        os.remove(mid_img)
97        os.remove(backing_img)
98
99    def test_commit(self):
100        self.run_commit_test(mid_img, backing_img)
101        self.assertEqual(-1, qemu_io('-f', 'raw', '-c', 'read -P 0xab 0 524288', backing_img).find("verification failed"))
102        self.assertEqual(-1, qemu_io('-f', 'raw', '-c', 'read -P 0xef 524288 524288', backing_img).find("verification failed"))
103
104    def test_commit_node(self):
105        self.run_commit_test("mid", "base", node_names=True)
106        self.assertEqual(-1, qemu_io('-f', 'raw', '-c', 'read -P 0xab 0 524288', backing_img).find("verification failed"))
107        self.assertEqual(-1, qemu_io('-f', 'raw', '-c', 'read -P 0xef 524288 524288', backing_img).find("verification failed"))
108
109    @iotests.skip_if_unsupported(['throttle'])
110    def test_commit_with_filter_and_quit(self):
111        result = self.vm.qmp('object-add', qom_type='throttle-group', id='tg')
112        self.assert_qmp(result, 'return', {})
113
114        # Add a filter outside of the backing chain
115        result = self.vm.qmp('blockdev-add', driver='throttle', node_name='filter', throttle_group='tg', file='mid')
116        self.assert_qmp(result, 'return', {})
117
118        result = self.vm.qmp('block-commit', device='drive0')
119        self.assert_qmp(result, 'return', {})
120
121        # Quit immediately, thus forcing a simultaneous cancel of the
122        # block job and a bdrv_drain_all()
123        result = self.vm.qmp('quit')
124        self.assert_qmp(result, 'return', {})
125
126        self.has_quit = True
127
128    # Same as above, but this time we add the filter after starting the job
129    @iotests.skip_if_unsupported(['throttle'])
130    def test_commit_plus_filter_and_quit(self):
131        result = self.vm.qmp('object-add', qom_type='throttle-group', id='tg')
132        self.assert_qmp(result, 'return', {})
133
134        result = self.vm.qmp('block-commit', device='drive0')
135        self.assert_qmp(result, 'return', {})
136
137        # Add a filter outside of the backing chain
138        result = self.vm.qmp('blockdev-add', driver='throttle', node_name='filter', throttle_group='tg', file='mid')
139        self.assert_qmp(result, 'return', {})
140
141        # Quit immediately, thus forcing a simultaneous cancel of the
142        # block job and a bdrv_drain_all()
143        result = self.vm.qmp('quit')
144        self.assert_qmp(result, 'return', {})
145
146        self.has_quit = True
147
148    def test_device_not_found(self):
149        result = self.vm.qmp('block-commit', device='nonexistent', top='%s' % mid_img)
150        self.assert_qmp(result, 'error/class', 'DeviceNotFound')
151
152    def test_top_same_base(self):
153        self.assert_no_active_block_jobs()
154        result = self.vm.qmp('block-commit', device='drive0', top='%s' % backing_img, base='%s' % backing_img)
155        self.assert_qmp(result, 'error/class', 'GenericError')
156        self.assert_qmp(result, 'error/desc', 'Base \'%s\' not found' % backing_img)
157
158    def test_top_invalid(self):
159        self.assert_no_active_block_jobs()
160        result = self.vm.qmp('block-commit', device='drive0', top='badfile', base='%s' % backing_img)
161        self.assert_qmp(result, 'error/class', 'GenericError')
162        self.assert_qmp(result, 'error/desc', 'Top image file badfile not found')
163
164    def test_base_invalid(self):
165        self.assert_no_active_block_jobs()
166        result = self.vm.qmp('block-commit', device='drive0', top='%s' % mid_img, base='badfile')
167        self.assert_qmp(result, 'error/class', 'GenericError')
168        self.assert_qmp(result, 'error/desc', 'Base \'badfile\' not found')
169
170    def test_top_node_invalid(self):
171        self.assert_no_active_block_jobs()
172        result = self.vm.qmp('block-commit', device='drive0', top_node='badfile', base_node='base')
173        self.assert_qmp(result, 'error/class', 'GenericError')
174        self.assert_qmp(result, 'error/desc', "Cannot find device= nor node_name=badfile")
175
176    def test_base_node_invalid(self):
177        self.assert_no_active_block_jobs()
178        result = self.vm.qmp('block-commit', device='drive0', top_node='mid', base_node='badfile')
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_top_path_and_node(self):
183        self.assert_no_active_block_jobs()
184        result = self.vm.qmp('block-commit', device='drive0', top_node='mid', base_node='base', top='%s' % mid_img)
185        self.assert_qmp(result, 'error/class', 'GenericError')
186        self.assert_qmp(result, 'error/desc', "'top-node' and 'top' are mutually exclusive")
187
188    def test_base_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', base='%s' % backing_img)
191        self.assert_qmp(result, 'error/class', 'GenericError')
192        self.assert_qmp(result, 'error/desc', "'base-node' and 'base' are mutually exclusive")
193
194    def test_top_is_active(self):
195        self.run_commit_test(test_img, backing_img, need_ready=True)
196        self.assertEqual(-1, qemu_io('-f', 'raw', '-c', 'read -P 0xab 0 524288', backing_img).find("verification failed"))
197        self.assertEqual(-1, qemu_io('-f', 'raw', '-c', 'read -P 0xef 524288 524288', backing_img).find("verification failed"))
198
199    def test_top_is_default_active(self):
200        self.run_default_commit_test()
201        self.assertEqual(-1, qemu_io('-f', 'raw', '-c', 'read -P 0xab 0 524288', backing_img).find("verification failed"))
202        self.assertEqual(-1, qemu_io('-f', 'raw', '-c', 'read -P 0xef 524288 524288', backing_img).find("verification failed"))
203
204    def test_top_and_base_reversed(self):
205        self.assert_no_active_block_jobs()
206        result = self.vm.qmp('block-commit', device='drive0', top='%s' % backing_img, base='%s' % mid_img)
207        self.assert_qmp(result, 'error/class', 'GenericError')
208        self.assert_qmp(result, 'error/desc', 'Base \'%s\' not found' % mid_img)
209
210    def test_top_and_base_node_reversed(self):
211        self.assert_no_active_block_jobs()
212        result = self.vm.qmp('block-commit', device='drive0', top_node='base', base_node='top')
213        self.assert_qmp(result, 'error/class', 'GenericError')
214        self.assert_qmp(result, 'error/desc', "'top' is not in this backing file chain")
215
216    def test_top_node_in_wrong_chain(self):
217        self.assert_no_active_block_jobs()
218
219        result = self.vm.qmp('blockdev-add', driver='null-co', node_name='null')
220        self.assert_qmp(result, 'return', {})
221
222        result = self.vm.qmp('block-commit', device='drive0', top_node='null', base_node='base')
223        self.assert_qmp(result, 'error/class', 'GenericError')
224        self.assert_qmp(result, 'error/desc', "'null' is not in this backing file chain")
225
226    # When the job is running on a BB that is automatically deleted on hot
227    # unplug, the job is cancelled when the device disappears
228    def test_hot_unplug(self):
229        if self.image_len == 0:
230            return
231
232        self.assert_no_active_block_jobs()
233        result = self.vm.qmp('block-commit', device='drive0', top=mid_img,
234                             base=backing_img, speed=(self.image_len // 4))
235        self.assert_qmp(result, 'return', {})
236        result = self.vm.qmp('device_del', id='scsi0')
237        self.assert_qmp(result, 'return', {})
238
239        cancelled = False
240        deleted = False
241        while not cancelled or not deleted:
242            for event in self.vm.get_qmp_events(wait=True):
243                if event['event'] == 'DEVICE_DELETED':
244                    self.assert_qmp(event, 'data/device', 'scsi0')
245                    deleted = True
246                elif event['event'] == 'BLOCK_JOB_CANCELLED':
247                    self.assert_qmp(event, 'data/device', 'drive0')
248                    cancelled = True
249                elif event['event'] == 'JOB_STATUS_CHANGE':
250                    self.assert_qmp(event, 'data/id', 'drive0')
251                else:
252                    self.fail("Unexpected event %s" % (event['event']))
253
254        self.assert_no_active_block_jobs()
255
256    # Tests that the insertion of the commit_top filter node doesn't make a
257    # difference to query-blockstat
258    def test_implicit_node(self):
259        if self.image_len == 0:
260            return
261
262        self.assert_no_active_block_jobs()
263        result = self.vm.qmp('block-commit', device='drive0', top=mid_img,
264                             base=backing_img, speed=(self.image_len // 4))
265        self.assert_qmp(result, 'return', {})
266
267        result = self.vm.qmp('query-block')
268        self.assert_qmp(result, 'return[0]/inserted/file', test_img)
269        self.assert_qmp(result, 'return[0]/inserted/drv', iotests.imgfmt)
270        self.assert_qmp(result, 'return[0]/inserted/backing_file', mid_img)
271        self.assert_qmp(result, 'return[0]/inserted/backing_file_depth', 2)
272        self.assert_qmp(result, 'return[0]/inserted/image/filename', test_img)
273        self.assert_qmp(result, 'return[0]/inserted/image/backing-image/filename', mid_img)
274        self.assert_qmp(result, 'return[0]/inserted/image/backing-image/backing-image/filename', backing_img)
275
276        result = self.vm.qmp('query-blockstats')
277        self.assert_qmp(result, 'return[0]/node-name', 'top')
278        self.assert_qmp(result, 'return[0]/backing/node-name', 'mid')
279        self.assert_qmp(result, 'return[0]/backing/backing/node-name', 'base')
280
281        self.cancel_and_wait()
282        self.assert_no_active_block_jobs()
283
284class TestRelativePaths(ImageCommitTestCase):
285    image_len = 1 * 1024 * 1024
286    test_len = 1 * 1024 * 256
287
288    dir1 = "dir1"
289    dir2 = "dir2/"
290    dir3 = "dir2/dir3/"
291
292    test_img = os.path.join(iotests.test_dir, dir3, 'test.img')
293    mid_img = "../mid.img"
294    backing_img = "../dir1/backing.img"
295
296    backing_img_abs = os.path.join(iotests.test_dir, dir1, 'backing.img')
297    mid_img_abs = os.path.join(iotests.test_dir, dir2, 'mid.img')
298
299    def setUp(self):
300        try:
301            os.mkdir(os.path.join(iotests.test_dir, self.dir1))
302            os.mkdir(os.path.join(iotests.test_dir, self.dir2))
303            os.mkdir(os.path.join(iotests.test_dir, self.dir3))
304        except OSError as exception:
305            if exception.errno != errno.EEXIST:
306                raise
307        iotests.create_image(self.backing_img_abs, TestRelativePaths.image_len)
308        qemu_img('create', '-f', iotests.imgfmt, '-o', 'backing_file=%s' % self.backing_img_abs, self.mid_img_abs)
309        qemu_img('create', '-f', iotests.imgfmt, '-o', 'backing_file=%s' % self.mid_img_abs, self.test_img)
310        qemu_img('rebase', '-u', '-b', self.backing_img, self.mid_img_abs)
311        qemu_img('rebase', '-u', '-b', self.mid_img, self.test_img)
312        qemu_io('-f', 'raw', '-c', 'write -P 0xab 0 524288', self.backing_img_abs)
313        qemu_io('-f', iotests.imgfmt, '-c', 'write -P 0xef 524288 524288', self.mid_img_abs)
314        self.vm = iotests.VM().add_drive(self.test_img)
315        self.vm.launch()
316
317    def tearDown(self):
318        self.vm.shutdown()
319        os.remove(self.test_img)
320        os.remove(self.mid_img_abs)
321        os.remove(self.backing_img_abs)
322        try:
323            os.rmdir(os.path.join(iotests.test_dir, self.dir1))
324            os.rmdir(os.path.join(iotests.test_dir, self.dir3))
325            os.rmdir(os.path.join(iotests.test_dir, self.dir2))
326        except OSError as exception:
327            if exception.errno != errno.EEXIST and exception.errno != errno.ENOTEMPTY:
328                raise
329
330    def test_commit(self):
331        self.run_commit_test(self.mid_img, self.backing_img)
332        self.assertEqual(-1, qemu_io('-f', 'raw', '-c', 'read -P 0xab 0 524288', self.backing_img_abs).find("verification failed"))
333        self.assertEqual(-1, qemu_io('-f', 'raw', '-c', 'read -P 0xef 524288 524288', self.backing_img_abs).find("verification failed"))
334
335    def test_device_not_found(self):
336        result = self.vm.qmp('block-commit', device='nonexistent', top='%s' % self.mid_img)
337        self.assert_qmp(result, 'error/class', 'DeviceNotFound')
338
339    def test_top_same_base(self):
340        self.assert_no_active_block_jobs()
341        result = self.vm.qmp('block-commit', device='drive0', top='%s' % self.mid_img, base='%s' % self.mid_img)
342        self.assert_qmp(result, 'error/class', 'GenericError')
343        self.assert_qmp(result, 'error/desc', 'Base \'%s\' not found' % self.mid_img)
344
345    def test_top_invalid(self):
346        self.assert_no_active_block_jobs()
347        result = self.vm.qmp('block-commit', device='drive0', top='badfile', base='%s' % self.backing_img)
348        self.assert_qmp(result, 'error/class', 'GenericError')
349        self.assert_qmp(result, 'error/desc', 'Top image file badfile not found')
350
351    def test_base_invalid(self):
352        self.assert_no_active_block_jobs()
353        result = self.vm.qmp('block-commit', device='drive0', top='%s' % self.mid_img, base='badfile')
354        self.assert_qmp(result, 'error/class', 'GenericError')
355        self.assert_qmp(result, 'error/desc', 'Base \'badfile\' not found')
356
357    def test_top_is_active(self):
358        self.run_commit_test(self.test_img, self.backing_img)
359        self.assertEqual(-1, qemu_io('-f', 'raw', '-c', 'read -P 0xab 0 524288', self.backing_img_abs).find("verification failed"))
360        self.assertEqual(-1, qemu_io('-f', 'raw', '-c', 'read -P 0xef 524288 524288', self.backing_img_abs).find("verification failed"))
361
362    def test_top_and_base_reversed(self):
363        self.assert_no_active_block_jobs()
364        result = self.vm.qmp('block-commit', device='drive0', top='%s' % self.backing_img, base='%s' % self.mid_img)
365        self.assert_qmp(result, 'error/class', 'GenericError')
366        self.assert_qmp(result, 'error/desc', 'Base \'%s\' not found' % self.mid_img)
367
368
369class TestSetSpeed(ImageCommitTestCase):
370    image_len = 80 * 1024 * 1024 # MB
371
372    def setUp(self):
373        qemu_img('create', backing_img, str(TestSetSpeed.image_len))
374        qemu_img('create', '-f', iotests.imgfmt, '-o', 'backing_file=%s' % backing_img, mid_img)
375        qemu_img('create', '-f', iotests.imgfmt, '-o', 'backing_file=%s' % mid_img, test_img)
376        qemu_io('-f', iotests.imgfmt, '-c', 'write -P 0x1 0 512', test_img)
377        qemu_io('-f', iotests.imgfmt, '-c', 'write -P 0xef 524288 524288', mid_img)
378        self.vm = iotests.VM().add_drive('blkdebug::' + test_img)
379        self.vm.launch()
380
381    def tearDown(self):
382        self.vm.shutdown()
383        os.remove(test_img)
384        os.remove(mid_img)
385        os.remove(backing_img)
386
387    def test_set_speed(self):
388        self.assert_no_active_block_jobs()
389
390        self.vm.pause_drive('drive0')
391        result = self.vm.qmp('block-commit', device='drive0', top=mid_img, speed=1024 * 1024)
392        self.assert_qmp(result, 'return', {})
393
394        # Ensure the speed we set was accepted
395        result = self.vm.qmp('query-block-jobs')
396        self.assert_qmp(result, 'return[0]/device', 'drive0')
397        self.assert_qmp(result, 'return[0]/speed', 1024 * 1024)
398
399        self.cancel_and_wait(resume=True)
400
401class TestActiveZeroLengthImage(TestSingleDrive):
402    image_len = 0
403
404class TestReopenOverlay(ImageCommitTestCase):
405    image_len = 1024 * 1024
406    img0 = os.path.join(iotests.test_dir, '0.img')
407    img1 = os.path.join(iotests.test_dir, '1.img')
408    img2 = os.path.join(iotests.test_dir, '2.img')
409    img3 = os.path.join(iotests.test_dir, '3.img')
410
411    def setUp(self):
412        iotests.create_image(self.img0, self.image_len)
413        qemu_img('create', '-f', iotests.imgfmt, '-o', 'backing_file=%s' % self.img0, self.img1)
414        qemu_img('create', '-f', iotests.imgfmt, '-o', 'backing_file=%s' % self.img1, self.img2)
415        qemu_img('create', '-f', iotests.imgfmt, '-o', 'backing_file=%s' % self.img2, self.img3)
416        qemu_io('-f', iotests.imgfmt, '-c', 'write -P 0xab 0 128K', self.img1)
417        self.vm = iotests.VM().add_drive(self.img3)
418        self.vm.launch()
419
420    def tearDown(self):
421        self.vm.shutdown()
422        os.remove(self.img0)
423        os.remove(self.img1)
424        os.remove(self.img2)
425        os.remove(self.img3)
426
427    # This tests what happens when the overlay image of the 'top' node
428    # needs to be reopened in read-write mode in order to update the
429    # backing image string.
430    def test_reopen_overlay(self):
431        self.run_commit_test(self.img1, self.img0)
432
433class TestErrorHandling(iotests.QMPTestCase):
434    image_len = 2 * 1024 * 1024
435
436    def setUp(self):
437        iotests.create_image(backing_img, self.image_len)
438        qemu_img('create', '-f', iotests.imgfmt, '-o', 'backing_file=%s' % backing_img, mid_img)
439        qemu_img('create', '-f', iotests.imgfmt, '-o', 'backing_file=%s' % mid_img, test_img)
440
441        qemu_io('-f', iotests.imgfmt, '-c', 'write -P 0x11 0 512k', mid_img)
442        qemu_io('-f', iotests.imgfmt, '-c', 'write -P 0x22 0 512k', test_img)
443
444        self.vm = iotests.VM()
445        self.vm.launch()
446
447        self.blkdebug_file = iotests.file_path("blkdebug.conf")
448
449    def tearDown(self):
450        self.vm.shutdown()
451        os.remove(test_img)
452        os.remove(mid_img)
453        os.remove(backing_img)
454
455    def blockdev_add(self, **kwargs):
456        result = self.vm.qmp('blockdev-add', **kwargs)
457        self.assert_qmp(result, 'return', {})
458
459    def add_block_nodes(self, base_debug=None, mid_debug=None, top_debug=None):
460        self.blockdev_add(node_name='base-file', driver='file',
461                          filename=backing_img)
462        self.blockdev_add(node_name='mid-file', driver='file',
463                          filename=mid_img)
464        self.blockdev_add(node_name='top-file', driver='file',
465                          filename=test_img)
466
467        if base_debug:
468            self.blockdev_add(node_name='base-dbg', driver='blkdebug',
469                              image='base-file', inject_error=base_debug)
470        if mid_debug:
471            self.blockdev_add(node_name='mid-dbg', driver='blkdebug',
472                              image='mid-file', inject_error=mid_debug)
473        if top_debug:
474            self.blockdev_add(node_name='top-dbg', driver='blkdebug',
475                              image='top-file', inject_error=top_debug)
476
477        self.blockdev_add(node_name='base-fmt', driver='raw',
478                          file=('base-dbg' if base_debug else 'base-file'))
479        self.blockdev_add(node_name='mid-fmt', driver=iotests.imgfmt,
480                          file=('mid-dbg' if mid_debug else 'mid-file'),
481                          backing='base-fmt')
482        self.blockdev_add(node_name='top-fmt', driver=iotests.imgfmt,
483                          file=('top-dbg' if top_debug else 'top-file'),
484                          backing='mid-fmt')
485
486    def run_job(self, expected_events, error_pauses_job=False):
487        match_device = {'data': {'device': 'job0'}}
488        events = [
489            ('BLOCK_JOB_COMPLETED', match_device),
490            ('BLOCK_JOB_CANCELLED', match_device),
491            ('BLOCK_JOB_ERROR', match_device),
492            ('BLOCK_JOB_READY', match_device),
493        ]
494
495        completed = False
496        log = []
497        while not completed:
498            ev = self.vm.events_wait(events, timeout=5.0)
499            if ev['event'] == 'BLOCK_JOB_COMPLETED':
500                completed = True
501            elif ev['event'] == 'BLOCK_JOB_ERROR':
502                if error_pauses_job:
503                    result = self.vm.qmp('block-job-resume', device='job0')
504                    self.assert_qmp(result, 'return', {})
505            elif ev['event'] == 'BLOCK_JOB_READY':
506                result = self.vm.qmp('block-job-complete', device='job0')
507                self.assert_qmp(result, 'return', {})
508            else:
509                self.fail("Unexpected event: %s" % ev)
510            log.append(iotests.filter_qmp_event(ev))
511
512        self.maxDiff = None
513        self.assertEqual(expected_events, log)
514
515    def event_error(self, op, action):
516        return {
517            'event': 'BLOCK_JOB_ERROR',
518            'data': {'action': action, 'device': 'job0', 'operation': op},
519            'timestamp': {'microseconds': 'USECS', 'seconds': 'SECS'}
520        }
521
522    def event_ready(self):
523        return {
524            'event': 'BLOCK_JOB_READY',
525            'data': {'device': 'job0',
526                     'len': 524288,
527                     'offset': 524288,
528                     'speed': 0,
529                     'type': 'commit'},
530            'timestamp': {'microseconds': 'USECS', 'seconds': 'SECS'},
531        }
532
533    def event_completed(self, errmsg=None, active=True):
534        max_len = 524288 if active else self.image_len
535        data = {
536            'device': 'job0',
537            'len': max_len,
538            'offset': 0 if errmsg else max_len,
539            'speed': 0,
540            'type': 'commit'
541        }
542        if errmsg:
543            data['error'] = errmsg
544
545        return {
546            'event': 'BLOCK_JOB_COMPLETED',
547            'data': data,
548            'timestamp': {'microseconds': 'USECS', 'seconds': 'SECS'},
549        }
550
551    def blkdebug_event(self, event, is_raw=False):
552        if event:
553            return [{
554                'event': event,
555                'sector': 512 if is_raw else 1024,
556                'once': True,
557            }]
558        return None
559
560    def prepare_and_start_job(self, on_error, active=True,
561                              top_event=None, mid_event=None, base_event=None):
562
563        top_debug = self.blkdebug_event(top_event)
564        mid_debug = self.blkdebug_event(mid_event)
565        base_debug = self.blkdebug_event(base_event, True)
566
567        self.add_block_nodes(top_debug=top_debug, mid_debug=mid_debug,
568                             base_debug=base_debug)
569
570        result = self.vm.qmp('block-commit', job_id='job0', device='top-fmt',
571                             top_node='top-fmt' if active else 'mid-fmt',
572                             base_node='mid-fmt' if active else 'base-fmt',
573                             on_error=on_error)
574        self.assert_qmp(result, 'return', {})
575
576    def testActiveReadErrorReport(self):
577        self.prepare_and_start_job('report', top_event='read_aio')
578        self.run_job([
579            self.event_error('read', 'report'),
580            self.event_completed('Input/output error')
581        ])
582
583        self.vm.shutdown()
584        self.assertFalse(iotests.compare_images(test_img, mid_img),
585                         'target image matches source after error')
586
587    def testActiveReadErrorStop(self):
588        self.prepare_and_start_job('stop', top_event='read_aio')
589        self.run_job([
590            self.event_error('read', 'stop'),
591            self.event_ready(),
592            self.event_completed()
593        ], error_pauses_job=True)
594
595        self.vm.shutdown()
596        self.assertTrue(iotests.compare_images(test_img, mid_img),
597                        'target image does not match source after commit')
598
599    def testActiveReadErrorIgnore(self):
600        self.prepare_and_start_job('ignore', top_event='read_aio')
601        self.run_job([
602            self.event_error('read', 'ignore'),
603            self.event_ready(),
604            self.event_completed()
605        ])
606
607        # For commit, 'ignore' actually means retry, so this will succeed
608        self.vm.shutdown()
609        self.assertTrue(iotests.compare_images(test_img, mid_img),
610                        'target image does not match source after commit')
611
612    def testActiveWriteErrorReport(self):
613        self.prepare_and_start_job('report', mid_event='write_aio')
614        self.run_job([
615            self.event_error('write', 'report'),
616            self.event_completed('Input/output error')
617        ])
618
619        self.vm.shutdown()
620        self.assertFalse(iotests.compare_images(test_img, mid_img),
621                         'target image matches source after error')
622
623    def testActiveWriteErrorStop(self):
624        self.prepare_and_start_job('stop', mid_event='write_aio')
625        self.run_job([
626            self.event_error('write', 'stop'),
627            self.event_ready(),
628            self.event_completed()
629        ], error_pauses_job=True)
630
631        self.vm.shutdown()
632        self.assertTrue(iotests.compare_images(test_img, mid_img),
633                        'target image does not match source after commit')
634
635    def testActiveWriteErrorIgnore(self):
636        self.prepare_and_start_job('ignore', mid_event='write_aio')
637        self.run_job([
638            self.event_error('write', 'ignore'),
639            self.event_ready(),
640            self.event_completed()
641        ])
642
643        # For commit, 'ignore' actually means retry, so this will succeed
644        self.vm.shutdown()
645        self.assertTrue(iotests.compare_images(test_img, mid_img),
646                        'target image does not match source after commit')
647
648    def testIntermediateReadErrorReport(self):
649        self.prepare_and_start_job('report', active=False, mid_event='read_aio')
650        self.run_job([
651            self.event_error('read', 'report'),
652            self.event_completed('Input/output error', active=False)
653        ])
654
655        self.vm.shutdown()
656        self.assertFalse(iotests.compare_images(mid_img, backing_img, fmt2='raw'),
657                         'target image matches source after error')
658
659    def testIntermediateReadErrorStop(self):
660        self.prepare_and_start_job('stop', active=False, mid_event='read_aio')
661        self.run_job([
662            self.event_error('read', 'stop'),
663            self.event_completed(active=False)
664        ], error_pauses_job=True)
665
666        self.vm.shutdown()
667        self.assertTrue(iotests.compare_images(mid_img, backing_img, fmt2='raw'),
668                        'target image does not match source after commit')
669
670    def testIntermediateReadErrorIgnore(self):
671        self.prepare_and_start_job('ignore', active=False, mid_event='read_aio')
672        self.run_job([
673            self.event_error('read', 'ignore'),
674            self.event_completed(active=False)
675        ])
676
677        # For commit, 'ignore' actually means retry, so this will succeed
678        self.vm.shutdown()
679        self.assertTrue(iotests.compare_images(mid_img, backing_img, fmt2='raw'),
680                        'target image does not match source after commit')
681
682    def testIntermediateWriteErrorReport(self):
683        self.prepare_and_start_job('report', active=False, base_event='write_aio')
684        self.run_job([
685            self.event_error('write', 'report'),
686            self.event_completed('Input/output error', active=False)
687        ])
688
689        self.vm.shutdown()
690        self.assertFalse(iotests.compare_images(mid_img, backing_img, fmt2='raw'),
691                         'target image matches source after error')
692
693    def testIntermediateWriteErrorStop(self):
694        self.prepare_and_start_job('stop', active=False, base_event='write_aio')
695        self.run_job([
696            self.event_error('write', 'stop'),
697            self.event_completed(active=False)
698        ], error_pauses_job=True)
699
700        self.vm.shutdown()
701        self.assertTrue(iotests.compare_images(mid_img, backing_img, fmt2='raw'),
702                        'target image does not match source after commit')
703
704    def testIntermediateWriteErrorIgnore(self):
705        self.prepare_and_start_job('ignore', active=False, base_event='write_aio')
706        self.run_job([
707            self.event_error('write', 'ignore'),
708            self.event_completed(active=False)
709        ])
710
711        # For commit, 'ignore' actually means retry, so this will succeed
712        self.vm.shutdown()
713        self.assertTrue(iotests.compare_images(mid_img, backing_img, fmt2='raw'),
714                        'target image does not match source after commit')
715
716if __name__ == '__main__':
717    iotests.main(supported_fmts=['qcow2', 'qed'],
718                 supported_protocols=['file'])
719