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