xref: /openbmc/qemu/tests/qemu-iotests/040 (revision cbb45ff0)
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    def setUp(self):
748        qemu_img('create', '-f', iotests.imgfmt, self.img0, '64M')
749        qemu_img('create', '-f', iotests.imgfmt, self.img1, '64M')
750        qemu_img('create', '-f', iotests.imgfmt, self.img2, '64M')
751        qemu_img('create', '-f', iotests.imgfmt, self.img3, '64M')
752
753        # Distributions of the patterns in the files; this is checked
754        # by tearDown() and should be changed by the test cases as is
755        # necessary
756        self.pattern_files = [self.img0, self.img1, self.img2, self.img3]
757
758        self.do_test_io('write')
759
760        self.vm = iotests.VM().add_device('virtio-scsi,id=vio-scsi')
761        self.vm.launch()
762
763        result = self.vm.qmp('object-add', qom_type='throttle-group', id='tg')
764        self.assert_qmp(result, 'return', {})
765
766        result = self.vm.qmp('blockdev-add', **{
767                'node-name': 'top-filter',
768                'driver': 'throttle',
769                'throttle-group': 'tg',
770                'file': {
771                    'node-name': 'cow-3',
772                    'driver': iotests.imgfmt,
773                    'file': {
774                        'driver': 'file',
775                        'filename': self.img3
776                    },
777                    'backing': {
778                        'node-name': 'cow-2',
779                        'driver': iotests.imgfmt,
780                        'file': {
781                            'driver': 'file',
782                            'filename': self.img2
783                        },
784                        'backing': {
785                            'node-name': 'cow-1',
786                            'driver': iotests.imgfmt,
787                            'file': {
788                                'driver': 'file',
789                                'filename': self.img1
790                            },
791                            'backing': {
792                                'node-name': 'bottom-filter',
793                                'driver': 'throttle',
794                                'throttle-group': 'tg',
795                                'file': {
796                                    'node-name': 'cow-0',
797                                    'driver': iotests.imgfmt,
798                                    'file': {
799                                        'driver': 'file',
800                                        'filename': self.img0
801                                    }
802                                }
803                            }
804                        }
805                    }
806                }
807            })
808        self.assert_qmp(result, 'return', {})
809
810    def tearDown(self):
811        self.vm.shutdown()
812        self.do_test_io('read')
813
814        os.remove(self.img3)
815        os.remove(self.img2)
816        os.remove(self.img1)
817        os.remove(self.img0)
818
819    # Filters make for funny filenames, so we cannot just use
820    # self.imgX to get them
821    def get_filename(self, node):
822        return self.vm.node_info(node)['image']['filename']
823
824    def test_filterless_commit(self):
825        result = self.vm.qmp('block-commit',
826                             job_id='commit',
827                             device='top-filter',
828                             top_node='cow-2',
829                             base_node='cow-1')
830        self.assert_qmp(result, 'return', {})
831        self.wait_until_completed(drive='commit')
832
833        self.assertIsNotNone(self.vm.node_info('cow-3'))
834        self.assertIsNone(self.vm.node_info('cow-2'))
835        self.assertIsNotNone(self.vm.node_info('cow-1'))
836
837        # 2 has been comitted into 1
838        self.pattern_files[2] = self.img1
839
840    def test_commit_through_filter(self):
841        result = self.vm.qmp('block-commit',
842                             job_id='commit',
843                             device='top-filter',
844                             top_node='cow-1',
845                             base_node='cow-0')
846        self.assert_qmp(result, 'return', {})
847        self.wait_until_completed(drive='commit')
848
849        self.assertIsNotNone(self.vm.node_info('cow-2'))
850        self.assertIsNone(self.vm.node_info('cow-1'))
851        self.assertIsNone(self.vm.node_info('bottom-filter'))
852        self.assertIsNotNone(self.vm.node_info('cow-0'))
853
854        # 1 has been comitted into 0
855        self.pattern_files[1] = self.img0
856
857    def test_filtered_active_commit_with_filter(self):
858        # Add a device, so the commit job finds a parent it can change
859        # to point to the base node (so we can test that top-filter is
860        # dropped from the graph)
861        result = self.vm.qmp('device_add', id='drv0', driver='scsi-hd',
862                             bus='vio-scsi.0', drive='top-filter')
863        self.assert_qmp(result, 'return', {})
864
865        # Try to release our reference to top-filter; that should not
866        # work because drv0 uses it
867        result = self.vm.qmp('blockdev-del', node_name='top-filter')
868        self.assert_qmp(result, 'error/class', 'GenericError')
869        self.assert_qmp(result, 'error/desc', 'Node top-filter is in use')
870
871        result = self.vm.qmp('block-commit',
872                             job_id='commit',
873                             device='top-filter',
874                             base_node='cow-2')
875        self.assert_qmp(result, 'return', {})
876        self.complete_and_wait(drive='commit')
877
878        # Try to release our reference to top-filter again
879        result = self.vm.qmp('blockdev-del', node_name='top-filter')
880        self.assert_qmp(result, 'return', {})
881
882        self.assertIsNone(self.vm.node_info('top-filter'))
883        self.assertIsNone(self.vm.node_info('cow-3'))
884        self.assertIsNotNone(self.vm.node_info('cow-2'))
885
886        # Check that drv0 is now connected to cow-2
887        blockdevs = self.vm.qmp('query-block')['return']
888        drv0 = next(dev for dev in blockdevs if dev['qdev'] == 'drv0')
889        self.assertEqual(drv0['inserted']['node-name'], 'cow-2')
890
891        # 3 has been comitted into 2
892        self.pattern_files[3] = self.img2
893
894    def test_filtered_active_commit_without_filter(self):
895        result = self.vm.qmp('block-commit',
896                             job_id='commit',
897                             device='top-filter',
898                             top_node='cow-3',
899                             base_node='cow-2')
900        self.assert_qmp(result, 'return', {})
901        self.complete_and_wait(drive='commit')
902
903        self.assertIsNotNone(self.vm.node_info('top-filter'))
904        self.assertIsNone(self.vm.node_info('cow-3'))
905        self.assertIsNotNone(self.vm.node_info('cow-2'))
906
907        # 3 has been comitted into 2
908        self.pattern_files[3] = self.img2
909
910class TestCommitWithOverriddenBacking(iotests.QMPTestCase):
911    img_base_a = os.path.join(iotests.test_dir, 'base_a.img')
912    img_base_b = os.path.join(iotests.test_dir, 'base_b.img')
913    img_top = os.path.join(iotests.test_dir, 'top.img')
914
915    def setUp(self):
916        qemu_img('create', '-f', iotests.imgfmt, self.img_base_a, '1M')
917        qemu_img('create', '-f', iotests.imgfmt, self.img_base_b, '1M')
918        qemu_img('create', '-f', iotests.imgfmt, '-b', self.img_base_a,
919                 '-F', iotests.imgfmt, self.img_top)
920
921        self.vm = iotests.VM()
922        self.vm.launch()
923
924        # Use base_b instead of base_a as the backing of top
925        result = self.vm.qmp('blockdev-add', **{
926                                'node-name': 'top',
927                                'driver': iotests.imgfmt,
928                                'file': {
929                                    'driver': 'file',
930                                    'filename': self.img_top
931                                },
932                                'backing': {
933                                    'node-name': 'base',
934                                    'driver': iotests.imgfmt,
935                                    'file': {
936                                        'driver': 'file',
937                                        'filename': self.img_base_b
938                                    }
939                                }
940                            })
941        self.assert_qmp(result, 'return', {})
942
943    def tearDown(self):
944        self.vm.shutdown()
945        os.remove(self.img_top)
946        os.remove(self.img_base_a)
947        os.remove(self.img_base_b)
948
949    def test_commit_to_a(self):
950        # Try committing to base_a (which should fail, as top's
951        # backing image is base_b instead)
952        result = self.vm.qmp('block-commit',
953                             job_id='commit',
954                             device='top',
955                             base=self.img_base_a)
956        self.assert_qmp(result, 'error/class', 'GenericError')
957
958    def test_commit_to_b(self):
959        # Try committing to base_b (which should work, since that is
960        # actually top's backing image)
961        result = self.vm.qmp('block-commit',
962                             job_id='commit',
963                             device='top',
964                             base=self.img_base_b)
965        self.assert_qmp(result, 'return', {})
966
967        self.vm.event_wait('BLOCK_JOB_READY')
968        self.vm.qmp('block-job-complete', device='commit')
969        self.vm.event_wait('BLOCK_JOB_COMPLETED')
970
971if __name__ == '__main__':
972    iotests.main(supported_fmts=['qcow2', 'qed'],
973                 supported_protocols=['file'])
974