xref: /openbmc/qemu/tests/qemu-iotests/245 (revision 19f4ed36)
1#!/usr/bin/env python3
2# group: rw
3#
4# Test cases for the QMP 'x-blockdev-reopen' command
5#
6# Copyright (C) 2018-2019 Igalia, S.L.
7# Author: Alberto Garcia <berto@igalia.com>
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
23import os
24import re
25import iotests
26import copy
27import json
28from iotests import qemu_img, qemu_io
29
30hd_path = [
31    os.path.join(iotests.test_dir, 'hd0.img'),
32    os.path.join(iotests.test_dir, 'hd1.img'),
33    os.path.join(iotests.test_dir, 'hd2.img')
34]
35
36def hd_opts(idx):
37    return {'driver': iotests.imgfmt,
38            'node-name': 'hd%d' % idx,
39            'file': {'driver': 'file',
40                     'node-name': 'hd%d-file' % idx,
41                     'filename':  hd_path[idx] } }
42
43class TestBlockdevReopen(iotests.QMPTestCase):
44    total_io_cmds = 0
45
46    def setUp(self):
47        qemu_img('create', '-f', iotests.imgfmt, hd_path[0], '3M')
48        qemu_img('create', '-f', iotests.imgfmt, '-b', hd_path[0],
49                 '-F', iotests.imgfmt, hd_path[1])
50        qemu_img('create', '-f', iotests.imgfmt, hd_path[2], '3M')
51        qemu_io('-f', iotests.imgfmt, '-c', 'write -P 0xa0  0 1M', hd_path[0])
52        qemu_io('-f', iotests.imgfmt, '-c', 'write -P 0xa1 1M 1M', hd_path[1])
53        qemu_io('-f', iotests.imgfmt, '-c', 'write -P 0xa2 2M 1M', hd_path[2])
54        self.vm = iotests.VM()
55        self.vm.launch()
56
57    def tearDown(self):
58        self.vm.shutdown()
59        self.check_qemu_io_errors()
60        os.remove(hd_path[0])
61        os.remove(hd_path[1])
62        os.remove(hd_path[2])
63
64    # The output of qemu-io is not returned by vm.hmp_qemu_io() but
65    # it's stored in the log and can only be read when the VM has been
66    # shut down. This function runs qemu-io and keeps track of the
67    # number of times it's been called.
68    def run_qemu_io(self, img, cmd):
69        result = self.vm.hmp_qemu_io(img, cmd)
70        self.assert_qmp(result, 'return', '')
71        self.total_io_cmds += 1
72
73    # Once the VM is shut down we can parse the log and see if qemu-io
74    # ran without errors.
75    def check_qemu_io_errors(self):
76        self.assertFalse(self.vm.is_running())
77        found = 0
78        log = self.vm.get_log()
79        for line in log.split("\n"):
80            if line.startswith("Pattern verification failed"):
81                raise Exception("%s (command #%d)" % (line, found))
82            if re.match("read .*/.* bytes at offset", line):
83                found += 1
84        self.assertEqual(found, self.total_io_cmds,
85                         "Expected output of %d qemu-io commands, found %d" %
86                         (found, self.total_io_cmds))
87
88    # Run x-blockdev-reopen with 'opts' but applying 'newopts'
89    # on top of it. The original 'opts' dict is unmodified
90    def reopen(self, opts, newopts = {}, errmsg = None):
91        opts = copy.deepcopy(opts)
92
93        # Apply the changes from 'newopts' on top of 'opts'
94        for key in newopts:
95            value = newopts[key]
96            # If key has the form "foo.bar" then we need to do
97            # opts["foo"]["bar"] = value, not opts["foo.bar"] = value
98            subdict = opts
99            while key.find('.') != -1:
100                [prefix, key] = key.split('.', 1)
101                subdict = opts[prefix]
102            subdict[key] = value
103
104        result = self.vm.qmp('x-blockdev-reopen', conv_keys = False, **opts)
105        if errmsg:
106            self.assert_qmp(result, 'error/class', 'GenericError')
107            self.assert_qmp(result, 'error/desc', errmsg)
108        else:
109            self.assert_qmp(result, 'return', {})
110
111
112    # Run query-named-block-nodes and return the specified entry
113    def get_node(self, node_name):
114        result = self.vm.qmp('query-named-block-nodes')
115        for node in result['return']:
116            if node['node-name'] == node_name:
117                return node
118        return None
119
120    # Run 'query-named-block-nodes' and compare its output with the
121    # value passed by the user in 'graph'
122    def check_node_graph(self, graph):
123        result = self.vm.qmp('query-named-block-nodes')
124        self.assertEqual(json.dumps(graph,  sort_keys=True),
125                         json.dumps(result, sort_keys=True))
126
127    # This test opens one single disk image (without backing files)
128    # and tries to reopen it with illegal / incorrect parameters.
129    def test_incorrect_parameters_single_file(self):
130        # Open 'hd0' only (no backing files)
131        opts = hd_opts(0)
132        result = self.vm.qmp('blockdev-add', conv_keys = False, **opts)
133        self.assert_qmp(result, 'return', {})
134        original_graph = self.vm.qmp('query-named-block-nodes')
135
136        # We can reopen the image passing the same options
137        self.reopen(opts)
138
139        # We can also reopen passing a child reference in 'file'
140        self.reopen(opts, {'file': 'hd0-file'})
141
142        # We cannot change any of these
143        self.reopen(opts, {'node-name': 'not-found'}, "Failed to find node with node-name='not-found'")
144        self.reopen(opts, {'node-name': ''}, "Failed to find node with node-name=''")
145        self.reopen(opts, {'node-name': None}, "Invalid parameter type for 'node-name', expected: string")
146        self.reopen(opts, {'driver': 'raw'}, "Cannot change the option 'driver'")
147        self.reopen(opts, {'driver': ''}, "Invalid parameter ''")
148        self.reopen(opts, {'driver': None}, "Invalid parameter type for 'driver', expected: string")
149        self.reopen(opts, {'file': 'not-found'}, "Cannot change the option 'file'")
150        self.reopen(opts, {'file': ''}, "Cannot change the option 'file'")
151        self.reopen(opts, {'file': None}, "Invalid parameter type for 'file', expected: BlockdevRef")
152        self.reopen(opts, {'file.node-name': 'newname'}, "Cannot change the option 'node-name'")
153        self.reopen(opts, {'file.driver': 'host_device'}, "Cannot change the option 'driver'")
154        self.reopen(opts, {'file.filename': hd_path[1]}, "Cannot change the option 'filename'")
155        self.reopen(opts, {'file.aio': 'native'}, "Cannot change the option 'aio'")
156        self.reopen(opts, {'file.locking': 'off'}, "Cannot change the option 'locking'")
157        self.reopen(opts, {'file.filename': None}, "Invalid parameter type for 'file.filename', expected: string")
158
159        # node-name is optional in BlockdevOptions, but x-blockdev-reopen needs it
160        del opts['node-name']
161        self.reopen(opts, {}, "node-name not specified")
162
163        # Check that nothing has changed
164        self.check_node_graph(original_graph)
165
166        # Remove the node
167        result = self.vm.qmp('blockdev-del', conv_keys = True, node_name = 'hd0')
168        self.assert_qmp(result, 'return', {})
169
170    # This test opens an image with a backing file and tries to reopen
171    # it with illegal / incorrect parameters.
172    def test_incorrect_parameters_backing_file(self):
173        # Open hd1 omitting the backing options (hd0 will be opened
174        # with the default options)
175        opts = hd_opts(1)
176        result = self.vm.qmp('blockdev-add', conv_keys = False, **opts)
177        self.assert_qmp(result, 'return', {})
178        original_graph = self.vm.qmp('query-named-block-nodes')
179
180        # We can't reopen the image passing the same options, 'backing' is mandatory
181        self.reopen(opts, {}, "backing is missing for 'hd1'")
182
183        # Everything works if we pass 'backing' using the existing node name
184        for node in original_graph['return']:
185            if node['drv'] == iotests.imgfmt and node['file'] == hd_path[0]:
186                backing_node_name = node['node-name']
187        self.reopen(opts, {'backing': backing_node_name})
188
189        # We can't use a non-existing or empty (non-NULL) node as the backing image
190        self.reopen(opts, {'backing': 'not-found'}, "Cannot find device=\'\' nor node-name=\'not-found\'")
191        self.reopen(opts, {'backing': ''}, "Cannot find device=\'\' nor node-name=\'\'")
192
193        # We can reopen the image just fine if we specify the backing options
194        opts['backing'] = {'driver': iotests.imgfmt,
195                           'file': {'driver': 'file',
196                                    'filename': hd_path[0]}}
197        self.reopen(opts)
198
199        # We cannot change any of these options
200        self.reopen(opts, {'backing.node-name': 'newname'}, "Cannot change the option 'node-name'")
201        self.reopen(opts, {'backing.driver': 'raw'}, "Cannot change the option 'driver'")
202        self.reopen(opts, {'backing.file.node-name': 'newname'}, "Cannot change the option 'node-name'")
203        self.reopen(opts, {'backing.file.driver': 'host_device'}, "Cannot change the option 'driver'")
204
205        # Check that nothing has changed since the beginning
206        self.check_node_graph(original_graph)
207
208        # Remove the node
209        result = self.vm.qmp('blockdev-del', conv_keys = True, node_name = 'hd1')
210        self.assert_qmp(result, 'return', {})
211
212    # Reopen an image several times changing some of its options
213    def test_reopen(self):
214        # Check whether the filesystem supports O_DIRECT
215        if 'O_DIRECT' in qemu_io('-f', 'raw', '-t', 'none', '-c', 'quit', hd_path[0]):
216            supports_direct = False
217        else:
218            supports_direct = True
219
220        # Open the hd1 image passing all backing options
221        opts = hd_opts(1)
222        opts['backing'] = hd_opts(0)
223        result = self.vm.qmp('blockdev-add', conv_keys = False, **opts)
224        self.assert_qmp(result, 'return', {})
225        original_graph = self.vm.qmp('query-named-block-nodes')
226
227        # We can reopen the image passing the same options
228        self.reopen(opts)
229
230        # Reopen in read-only mode
231        self.assert_qmp(self.get_node('hd1'), 'ro', False)
232
233        self.reopen(opts, {'read-only': True})
234        self.assert_qmp(self.get_node('hd1'), 'ro', True)
235        self.reopen(opts)
236        self.assert_qmp(self.get_node('hd1'), 'ro', False)
237
238        # Change the cache options
239        self.assert_qmp(self.get_node('hd1'), 'cache/writeback', True)
240        self.assert_qmp(self.get_node('hd1'), 'cache/direct', False)
241        self.assert_qmp(self.get_node('hd1'), 'cache/no-flush', False)
242        self.reopen(opts, {'cache': { 'direct': supports_direct, 'no-flush': True }})
243        self.assert_qmp(self.get_node('hd1'), 'cache/writeback', True)
244        self.assert_qmp(self.get_node('hd1'), 'cache/direct', supports_direct)
245        self.assert_qmp(self.get_node('hd1'), 'cache/no-flush', True)
246
247        # Reopen again with the original options
248        self.reopen(opts)
249        self.assert_qmp(self.get_node('hd1'), 'cache/writeback', True)
250        self.assert_qmp(self.get_node('hd1'), 'cache/direct', False)
251        self.assert_qmp(self.get_node('hd1'), 'cache/no-flush', False)
252
253        # Change 'detect-zeroes' and 'discard'
254        self.assert_qmp(self.get_node('hd1'), 'detect_zeroes', 'off')
255        self.reopen(opts, {'detect-zeroes': 'on'})
256        self.assert_qmp(self.get_node('hd1'), 'detect_zeroes', 'on')
257        self.reopen(opts, {'detect-zeroes': 'unmap'},
258                    "setting detect-zeroes to unmap is not allowed " +
259                    "without setting discard operation to unmap")
260        self.assert_qmp(self.get_node('hd1'), 'detect_zeroes', 'on')
261        self.reopen(opts, {'detect-zeroes': 'unmap', 'discard': 'unmap'})
262        self.assert_qmp(self.get_node('hd1'), 'detect_zeroes', 'unmap')
263        self.reopen(opts)
264        self.assert_qmp(self.get_node('hd1'), 'detect_zeroes', 'off')
265
266        # Changing 'force-share' is currently not supported
267        self.reopen(opts, {'force-share': True}, "Cannot change the option 'force-share'")
268
269        # Change some qcow2-specific options
270        # No way to test for success other than checking the return message
271        if iotests.imgfmt == 'qcow2':
272            self.reopen(opts, {'l2-cache-entry-size': 128 * 1024},
273                        "L2 cache entry size must be a power of two "+
274                        "between 512 and the cluster size (65536)")
275            self.reopen(opts, {'l2-cache-size': 1024 * 1024,
276                               'cache-size':     512 * 1024},
277                        "l2-cache-size may not exceed cache-size")
278            self.reopen(opts, {'l2-cache-size':        4 * 1024 * 1024,
279                               'refcount-cache-size':  4 * 1024 * 1024,
280                               'l2-cache-entry-size': 32 * 1024})
281            self.reopen(opts, {'pass-discard-request': True})
282
283        # Check that nothing has changed since the beginning
284        # (from the parameters that we can check)
285        self.check_node_graph(original_graph)
286
287        # Check that the node names (other than the top-level one) are optional
288        del opts['file']['node-name']
289        del opts['backing']['node-name']
290        del opts['backing']['file']['node-name']
291        self.reopen(opts)
292        self.check_node_graph(original_graph)
293
294        # Reopen setting backing = null, this removes the backing image from the chain
295        self.reopen(opts, {'backing': None})
296        self.assert_qmp_absent(self.get_node('hd1'), 'image/backing-image')
297
298        # Open the 'hd0' image
299        result = self.vm.qmp('blockdev-add', conv_keys = False, **hd_opts(0))
300        self.assert_qmp(result, 'return', {})
301
302        # Reopen the hd1 image setting 'hd0' as its backing image
303        self.reopen(opts, {'backing': 'hd0'})
304        self.assert_qmp(self.get_node('hd1'), 'image/backing-image/filename', hd_path[0])
305
306        # Check that nothing has changed since the beginning
307        self.reopen(hd_opts(0), {'read-only': True})
308        self.check_node_graph(original_graph)
309
310        # The backing file (hd0) is now a reference, we cannot change backing.* anymore
311        self.reopen(opts, {}, "Cannot change the option 'backing.driver'")
312
313        # We can't remove 'hd0' while it's a backing image of 'hd1'
314        result = self.vm.qmp('blockdev-del', conv_keys = True, node_name = 'hd0')
315        self.assert_qmp(result, 'error/class', 'GenericError')
316        self.assert_qmp(result, 'error/desc', "Node 'hd0' is busy: node is used as backing hd of 'hd1'")
317
318        # But we can remove both nodes if done in the proper order
319        result = self.vm.qmp('blockdev-del', conv_keys = True, node_name = 'hd1')
320        self.assert_qmp(result, 'return', {})
321        result = self.vm.qmp('blockdev-del', conv_keys = True, node_name = 'hd0')
322        self.assert_qmp(result, 'return', {})
323
324    # Reopen a raw image and see the effect of changing the 'offset' option
325    def test_reopen_raw(self):
326        opts = {'driver': 'raw', 'node-name': 'hd0',
327                'file': { 'driver': 'file',
328                          'filename': hd_path[0],
329                          'node-name': 'hd0-file' } }
330
331        # First we create a 2MB raw file, and fill each half with a
332        # different value
333        qemu_img('create', '-f', 'raw', hd_path[0], '2M')
334        qemu_io('-f', 'raw', '-c', 'write -P 0xa0  0 1M', hd_path[0])
335        qemu_io('-f', 'raw', '-c', 'write -P 0xa1 1M 1M', hd_path[0])
336
337        # Open the raw file with QEMU
338        result = self.vm.qmp('blockdev-add', conv_keys = False, **opts)
339        self.assert_qmp(result, 'return', {})
340
341        # Read 1MB from offset 0
342        self.run_qemu_io("hd0", "read -P 0xa0  0 1M")
343
344        # Reopen the image with a 1MB offset.
345        # Now the results are different
346        self.reopen(opts, {'offset': 1024*1024})
347        self.run_qemu_io("hd0", "read -P 0xa1  0 1M")
348
349        # Reopen again with the original options.
350        # We get the original results again
351        self.reopen(opts)
352        self.run_qemu_io("hd0", "read -P 0xa0  0 1M")
353
354        # Remove the block device
355        result = self.vm.qmp('blockdev-del', conv_keys = True, node_name = 'hd0')
356        self.assert_qmp(result, 'return', {})
357
358    # Omitting an option should reset it to the default value, but if
359    # an option cannot be changed it shouldn't be possible to reset it
360    # to its default value either
361    def test_reset_default_values(self):
362        opts = {'driver': 'qcow2', 'node-name': 'hd0',
363                'file': { 'driver': 'file',
364                          'filename': hd_path[0],
365                          'x-check-cache-dropped': True, # This one can be changed
366                          'locking': 'off',              # This one can NOT be changed
367                          'node-name': 'hd0-file' } }
368
369        # Open the file with QEMU
370        result = self.vm.qmp('blockdev-add', conv_keys = False, **opts)
371        self.assert_qmp(result, 'return', {})
372
373        # file.x-check-cache-dropped can be changed...
374        self.reopen(opts, { 'file.x-check-cache-dropped': False })
375        # ...and dropped completely (resetting to the default value)
376        del opts['file']['x-check-cache-dropped']
377        self.reopen(opts)
378
379        # file.locking cannot be changed nor reset to the default value
380        self.reopen(opts, { 'file.locking': 'on' }, "Cannot change the option 'locking'")
381        del opts['file']['locking']
382        self.reopen(opts, {}, "Option 'locking' cannot be reset to its default value")
383        # But we can reopen it if we maintain its previous value
384        self.reopen(opts, { 'file.locking': 'off' })
385
386        # Remove the block device
387        result = self.vm.qmp('blockdev-del', conv_keys = True, node_name = 'hd0')
388        self.assert_qmp(result, 'return', {})
389
390    # This test modifies the node graph a few times by changing the
391    # 'backing' option on reopen and verifies that the guest data that
392    # is read afterwards is consistent with the graph changes.
393    def test_io_with_graph_changes(self):
394        opts = []
395
396        # Open hd0, hd1 and hd2 without any backing image
397        for i in range(3):
398            opts.append(hd_opts(i))
399            opts[i]['backing'] = None
400            result = self.vm.qmp('blockdev-add', conv_keys = False, **opts[i])
401            self.assert_qmp(result, 'return', {})
402
403        # hd0
404        self.run_qemu_io("hd0", "read -P 0xa0  0 1M")
405        self.run_qemu_io("hd0", "read -P 0    1M 1M")
406        self.run_qemu_io("hd0", "read -P 0    2M 1M")
407
408        # hd1 <- hd0
409        self.reopen(opts[0], {'backing': 'hd1'})
410
411        self.run_qemu_io("hd0", "read -P 0xa0  0 1M")
412        self.run_qemu_io("hd0", "read -P 0xa1 1M 1M")
413        self.run_qemu_io("hd0", "read -P 0    2M 1M")
414
415        # hd1 <- hd0 , hd1 <- hd2
416        self.reopen(opts[2], {'backing': 'hd1'})
417
418        self.run_qemu_io("hd2", "read -P 0     0 1M")
419        self.run_qemu_io("hd2", "read -P 0xa1 1M 1M")
420        self.run_qemu_io("hd2", "read -P 0xa2 2M 1M")
421
422        # hd1 <- hd2 <- hd0
423        self.reopen(opts[0], {'backing': 'hd2'})
424
425        self.run_qemu_io("hd0", "read -P 0xa0  0 1M")
426        self.run_qemu_io("hd0", "read -P 0xa1 1M 1M")
427        self.run_qemu_io("hd0", "read -P 0xa2 2M 1M")
428
429        # hd2 <- hd0
430        self.reopen(opts[2], {'backing': None})
431
432        self.run_qemu_io("hd0", "read -P 0xa0  0 1M")
433        self.run_qemu_io("hd0", "read -P 0    1M 1M")
434        self.run_qemu_io("hd0", "read -P 0xa2 2M 1M")
435
436        # hd2 <- hd1 <- hd0
437        self.reopen(opts[1], {'backing': 'hd2'})
438        self.reopen(opts[0], {'backing': 'hd1'})
439
440        self.run_qemu_io("hd0", "read -P 0xa0  0 1M")
441        self.run_qemu_io("hd0", "read -P 0xa1 1M 1M")
442        self.run_qemu_io("hd0", "read -P 0xa2 2M 1M")
443
444        # Illegal operation: hd2 is a child of hd1
445        self.reopen(opts[2], {'backing': 'hd1'},
446                    "Making 'hd1' a backing file of 'hd2' would create a cycle")
447
448        # hd2 <- hd0, hd2 <- hd1
449        self.reopen(opts[0], {'backing': 'hd2'})
450
451        self.run_qemu_io("hd1", "read -P 0     0 1M")
452        self.run_qemu_io("hd1", "read -P 0xa1 1M 1M")
453        self.run_qemu_io("hd1", "read -P 0xa2 2M 1M")
454
455        # More illegal operations
456        self.reopen(opts[2], {'backing': 'hd1'},
457                    "Making 'hd1' a backing file of 'hd2' would create a cycle")
458        self.reopen(opts[2], {'file': 'hd0-file'}, "Cannot change the option 'file'")
459
460        result = self.vm.qmp('blockdev-del', conv_keys = True, node_name = 'hd2')
461        self.assert_qmp(result, 'error/class', 'GenericError')
462        self.assert_qmp(result, 'error/desc', "Node 'hd2' is busy: node is used as backing hd of 'hd0'")
463
464        # hd1 doesn't have a backing file now
465        self.reopen(opts[1], {'backing': None})
466
467        self.run_qemu_io("hd1", "read -P 0     0 1M")
468        self.run_qemu_io("hd1", "read -P 0xa1 1M 1M")
469        self.run_qemu_io("hd1", "read -P 0    2M 1M")
470
471        # We can't remove the 'backing' option if the image has a
472        # default backing file
473        del opts[1]['backing']
474        self.reopen(opts[1], {}, "backing is missing for 'hd1'")
475
476        self.run_qemu_io("hd1", "read -P 0     0 1M")
477        self.run_qemu_io("hd1", "read -P 0xa1 1M 1M")
478        self.run_qemu_io("hd1", "read -P 0    2M 1M")
479
480    # This test verifies that we can't change the children of a block
481    # device during a reopen operation in a way that would create
482    # cycles in the node graph
483    @iotests.skip_if_unsupported(['blkverify'])
484    def test_graph_cycles(self):
485        opts = []
486
487        # Open all three images without backing file
488        for i in range(3):
489            opts.append(hd_opts(i))
490            opts[i]['backing'] = None
491            result = self.vm.qmp('blockdev-add', conv_keys = False, **opts[i])
492            self.assert_qmp(result, 'return', {})
493
494        # hd1 <- hd0, hd1 <- hd2
495        self.reopen(opts[0], {'backing': 'hd1'})
496        self.reopen(opts[2], {'backing': 'hd1'})
497
498        # Illegal: hd2 is backed by hd1
499        self.reopen(opts[1], {'backing': 'hd2'},
500                    "Making 'hd2' a backing file of 'hd1' would create a cycle")
501
502        # hd1 <- hd0 <- hd2
503        self.reopen(opts[2], {'backing': 'hd0'})
504
505        # Illegal: hd2 is backed by hd0, which is backed by hd1
506        self.reopen(opts[1], {'backing': 'hd2'},
507                    "Making 'hd2' a backing file of 'hd1' would create a cycle")
508
509        # Illegal: hd1 cannot point to itself
510        self.reopen(opts[1], {'backing': 'hd1'},
511                    "Making 'hd1' a backing file of 'hd1' would create a cycle")
512
513        # Remove all backing files
514        self.reopen(opts[0])
515        self.reopen(opts[2])
516
517        ##########################################
518        # Add a blkverify node using hd0 and hd1 #
519        ##########################################
520        bvopts = {'driver': 'blkverify',
521                  'node-name': 'bv',
522                  'test': 'hd0',
523                  'raw': 'hd1'}
524        result = self.vm.qmp('blockdev-add', conv_keys = False, **bvopts)
525        self.assert_qmp(result, 'return', {})
526
527        # blkverify doesn't currently allow reopening. TODO: implement this
528        self.reopen(bvopts, {}, "Block format 'blkverify' used by node 'bv'" +
529                    " does not support reopening files")
530
531        # Illegal: hd0 is a child of the blkverify node
532        self.reopen(opts[0], {'backing': 'bv'},
533                    "Making 'bv' a backing file of 'hd0' would create a cycle")
534
535        # Delete the blkverify node
536        result = self.vm.qmp('blockdev-del', conv_keys = True, node_name = 'bv')
537        self.assert_qmp(result, 'return', {})
538
539    # Misc reopen tests with different block drivers
540    @iotests.skip_if_unsupported(['quorum', 'throttle'])
541    def test_misc_drivers(self):
542        ####################
543        ###### quorum ######
544        ####################
545        for i in range(3):
546            opts = hd_opts(i)
547            # Open all three images without backing file
548            opts['backing'] = None
549            result = self.vm.qmp('blockdev-add', conv_keys = False, **opts)
550            self.assert_qmp(result, 'return', {})
551
552        opts = {'driver': 'quorum',
553                'node-name': 'quorum0',
554                'children': ['hd0', 'hd1', 'hd2'],
555                'vote-threshold': 2}
556        result = self.vm.qmp('blockdev-add', conv_keys = False, **opts)
557        self.assert_qmp(result, 'return', {})
558
559        # Quorum doesn't currently allow reopening. TODO: implement this
560        self.reopen(opts, {}, "Block format 'quorum' used by node 'quorum0'" +
561                    " does not support reopening files")
562
563        # You can't make quorum0 a backing file of hd0:
564        # hd0 is already a child of quorum0.
565        self.reopen(hd_opts(0), {'backing': 'quorum0'},
566                    "Making 'quorum0' a backing file of 'hd0' would create a cycle")
567
568        # Delete quorum0
569        result = self.vm.qmp('blockdev-del', conv_keys = True, node_name = 'quorum0')
570        self.assert_qmp(result, 'return', {})
571
572        # Delete hd0, hd1 and hd2
573        for i in range(3):
574            result = self.vm.qmp('blockdev-del', conv_keys = True,
575                                 node_name = 'hd%d' % i)
576            self.assert_qmp(result, 'return', {})
577
578        ######################
579        ###### blkdebug ######
580        ######################
581        opts = {'driver': 'blkdebug',
582                'node-name': 'bd',
583                'config': '/dev/null',
584                'image': hd_opts(0)}
585        result = self.vm.qmp('blockdev-add', conv_keys = False, **opts)
586        self.assert_qmp(result, 'return', {})
587
588        # blkdebug allows reopening if we keep the same options
589        self.reopen(opts)
590
591        # but it currently does not allow changes
592        self.reopen(opts, {'image': 'hd1'}, "Cannot change the option 'image'")
593        self.reopen(opts, {'align': 33554432}, "Cannot change the option 'align'")
594        self.reopen(opts, {'config': '/non/existent'}, "Cannot change the option 'config'")
595        del opts['config']
596        self.reopen(opts, {}, "Option 'config' cannot be reset to its default value")
597
598        # Delete the blkdebug node
599        result = self.vm.qmp('blockdev-del', conv_keys = True, node_name = 'bd')
600        self.assert_qmp(result, 'return', {})
601
602        ##################
603        ###### null ######
604        ##################
605        opts = {'driver': 'null-co', 'node-name': 'root', 'size': 1024}
606
607        result = self.vm.qmp('blockdev-add', conv_keys = False, **opts)
608        self.assert_qmp(result, 'return', {})
609
610        # 1 << 30 is the default value, but we cannot change it explicitly
611        self.reopen(opts, {'size': (1 << 30)}, "Cannot change the option 'size'")
612
613        # We cannot change 'size' back to its default value either
614        del opts['size']
615        self.reopen(opts, {}, "Option 'size' cannot be reset to its default value")
616
617        result = self.vm.qmp('blockdev-del', conv_keys = True, node_name = 'root')
618        self.assert_qmp(result, 'return', {})
619
620        ##################
621        ###### file ######
622        ##################
623        opts = hd_opts(0)
624        opts['file']['locking'] = 'on'
625        result = self.vm.qmp('blockdev-add', conv_keys = False, **opts)
626        self.assert_qmp(result, 'return', {})
627
628        # 'locking' cannot be changed
629        del opts['file']['locking']
630        self.reopen(opts, {'file.locking': 'on'})
631        self.reopen(opts, {'file.locking': 'off'}, "Cannot change the option 'locking'")
632        self.reopen(opts, {}, "Option 'locking' cannot be reset to its default value")
633
634        # Trying to reopen the 'file' node directly does not make a difference
635        opts = opts['file']
636        self.reopen(opts, {'locking': 'on'})
637        self.reopen(opts, {'locking': 'off'}, "Cannot change the option 'locking'")
638        self.reopen(opts, {}, "Option 'locking' cannot be reset to its default value")
639
640        result = self.vm.qmp('blockdev-del', conv_keys = True, node_name = 'hd0')
641        self.assert_qmp(result, 'return', {})
642
643        ######################
644        ###### throttle ######
645        ######################
646        opts = { 'qom-type': 'throttle-group', 'id': 'group0',
647                 'limits': { 'iops-total': 1000 } }
648        result = self.vm.qmp('object-add', conv_keys = False, **opts)
649        self.assert_qmp(result, 'return', {})
650
651        opts = { 'qom-type': 'throttle-group', 'id': 'group1',
652                 'limits': { 'iops-total': 2000 } }
653        result = self.vm.qmp('object-add', conv_keys = False, **opts)
654        self.assert_qmp(result, 'return', {})
655
656        # Add a throttle filter with group = group0
657        opts = { 'driver': 'throttle', 'node-name': 'throttle0',
658                 'throttle-group': 'group0', 'file': hd_opts(0) }
659        result = self.vm.qmp('blockdev-add', conv_keys = False, **opts)
660        self.assert_qmp(result, 'return', {})
661
662        # We can reopen it if we keep the same options
663        self.reopen(opts)
664
665        # We can also reopen if 'file' is a reference to the child
666        self.reopen(opts, {'file': 'hd0'})
667
668        # This is illegal
669        self.reopen(opts, {'throttle-group': 'notfound'}, "Throttle group 'notfound' does not exist")
670
671        # But it's possible to change the group to group1
672        self.reopen(opts, {'throttle-group': 'group1'})
673
674        # Now group1 is in use, it cannot be deleted
675        result = self.vm.qmp('object-del', id = 'group1')
676        self.assert_qmp(result, 'error/class', 'GenericError')
677        self.assert_qmp(result, 'error/desc', "object 'group1' is in use, can not be deleted")
678
679        # Default options, this switches the group back to group0
680        self.reopen(opts)
681
682        # So now we cannot delete group0
683        result = self.vm.qmp('object-del', id = 'group0')
684        self.assert_qmp(result, 'error/class', 'GenericError')
685        self.assert_qmp(result, 'error/desc', "object 'group0' is in use, can not be deleted")
686
687        # But group1 is free this time, and it can be deleted
688        result = self.vm.qmp('object-del', id = 'group1')
689        self.assert_qmp(result, 'return', {})
690
691        # Let's delete the filter node
692        result = self.vm.qmp('blockdev-del', conv_keys = True, node_name = 'throttle0')
693        self.assert_qmp(result, 'return', {})
694
695        # And we can finally get rid of group0
696        result = self.vm.qmp('object-del', id = 'group0')
697        self.assert_qmp(result, 'return', {})
698
699    # If an image has a backing file then the 'backing' option must be
700    # passed on reopen. We don't allow leaving the option out in this
701    # case because it's unclear what the correct semantics would be.
702    def test_missing_backing_options_1(self):
703        # hd2
704        opts = hd_opts(2)
705        result = self.vm.qmp('blockdev-add', conv_keys = False, **opts)
706        self.assert_qmp(result, 'return', {})
707
708        # hd0
709        opts = hd_opts(0)
710        result = self.vm.qmp('blockdev-add', conv_keys = False, **opts)
711        self.assert_qmp(result, 'return', {})
712
713        # hd0 has no backing file: we can omit the 'backing' option
714        self.reopen(opts)
715
716        # hd2 <- hd0
717        self.reopen(opts, {'backing': 'hd2'})
718
719        # hd0 has a backing file: we must set the 'backing' option
720        self.reopen(opts, {}, "backing is missing for 'hd0'")
721
722        # hd2 can't be removed because it's the backing file of hd0
723        result = self.vm.qmp('blockdev-del', conv_keys = True, node_name = 'hd2')
724        self.assert_qmp(result, 'error/class', 'GenericError')
725        self.assert_qmp(result, 'error/desc', "Node 'hd2' is busy: node is used as backing hd of 'hd0'")
726
727        # Detach hd2 from hd0.
728        self.reopen(opts, {'backing': None})
729
730        # Without a backing file, we can omit 'backing' again
731        self.reopen(opts)
732
733        # Remove both hd0 and hd2
734        result = self.vm.qmp('blockdev-del', conv_keys = True, node_name = 'hd0')
735        self.assert_qmp(result, 'return', {})
736
737        result = self.vm.qmp('blockdev-del', conv_keys = True, node_name = 'hd2')
738        self.assert_qmp(result, 'return', {})
739
740    # If an image has default backing file (as part of its metadata)
741    # then the 'backing' option must be passed on reopen. We don't
742    # allow leaving the option out in this case because it's unclear
743    # what the correct semantics would be.
744    def test_missing_backing_options_2(self):
745        # hd0 <- hd1
746        # (hd0 is hd1's default backing file)
747        opts = hd_opts(1)
748        result = self.vm.qmp('blockdev-add', conv_keys = False, **opts)
749        self.assert_qmp(result, 'return', {})
750
751        # hd1 has a backing file: we can't omit the 'backing' option
752        self.reopen(opts, {}, "backing is missing for 'hd1'")
753
754        # Let's detach the backing file
755        self.reopen(opts, {'backing': None})
756
757        # No backing file attached to hd1 now, but we still can't omit the 'backing' option
758        self.reopen(opts, {}, "backing is missing for 'hd1'")
759
760        result = self.vm.qmp('blockdev-del', conv_keys = True, node_name = 'hd1')
761        self.assert_qmp(result, 'return', {})
762
763    # Test that making 'backing' a reference to an existing child
764    # keeps its current options
765    def test_backing_reference(self):
766        # hd2 <- hd1 <- hd0
767        opts = hd_opts(0)
768        opts['backing'] = hd_opts(1)
769        opts['backing']['backing'] = hd_opts(2)
770        # Enable 'detect-zeroes' on all three nodes
771        opts['detect-zeroes'] = 'on'
772        opts['backing']['detect-zeroes'] = 'on'
773        opts['backing']['backing']['detect-zeroes'] = 'on'
774        result = self.vm.qmp('blockdev-add', conv_keys = False, **opts)
775        self.assert_qmp(result, 'return', {})
776
777        # Reopen the chain passing the minimum amount of required options.
778        # By making 'backing' a reference to hd1 (instead of a sub-dict)
779        # we tell QEMU to keep its current set of options.
780        opts = {'driver': iotests.imgfmt,
781                'node-name': 'hd0',
782                'file': 'hd0-file',
783                'backing': 'hd1' }
784        self.reopen(opts)
785
786        # This has reset 'detect-zeroes' on hd0, but not on hd1 and hd2.
787        self.assert_qmp(self.get_node('hd0'), 'detect_zeroes', 'off')
788        self.assert_qmp(self.get_node('hd1'), 'detect_zeroes', 'on')
789        self.assert_qmp(self.get_node('hd2'), 'detect_zeroes', 'on')
790
791    # Test what happens if the graph changes due to other operations
792    # such as block-stream
793    def test_block_stream_1(self):
794        # hd1 <- hd0
795        opts = hd_opts(0)
796        opts['backing'] = hd_opts(1)
797        opts['backing']['backing'] = None
798        result = self.vm.qmp('blockdev-add', conv_keys = False, **opts)
799        self.assert_qmp(result, 'return', {})
800
801        # Stream hd1 into hd0 and wait until it's done
802        result = self.vm.qmp('block-stream', conv_keys = True, job_id = 'stream0', device = 'hd0')
803        self.assert_qmp(result, 'return', {})
804        self.wait_until_completed(drive = 'stream0')
805
806        # Now we have only hd0
807        self.assertEqual(self.get_node('hd1'), None)
808
809        # We have backing.* options but there's no backing file anymore
810        self.reopen(opts, {}, "Cannot change the option 'backing.driver'")
811
812        # If we remove the 'backing' option then we can reopen hd0 just fine
813        del opts['backing']
814        self.reopen(opts)
815
816        # We can also reopen hd0 if we set 'backing' to null
817        self.reopen(opts, {'backing': None})
818
819        result = self.vm.qmp('blockdev-del', conv_keys = True, node_name = 'hd0')
820        self.assert_qmp(result, 'return', {})
821
822    # Another block_stream test
823    def test_block_stream_2(self):
824        # hd2 <- hd1 <- hd0
825        opts = hd_opts(0)
826        opts['backing'] = hd_opts(1)
827        opts['backing']['backing'] = hd_opts(2)
828        result = self.vm.qmp('blockdev-add', conv_keys = False, **opts)
829        self.assert_qmp(result, 'return', {})
830
831        # Stream hd1 into hd0 and wait until it's done
832        result = self.vm.qmp('block-stream', conv_keys = True, job_id = 'stream0',
833                             device = 'hd0', base_node = 'hd2')
834        self.assert_qmp(result, 'return', {})
835        self.wait_until_completed(drive = 'stream0')
836
837        # The chain is hd2 <- hd0 now. hd1 is missing
838        self.assertEqual(self.get_node('hd1'), None)
839
840        # The backing options in the dict were meant for hd1, but we cannot
841        # use them with hd2 because hd1 had a backing file while hd2 does not.
842        self.reopen(opts, {}, "Cannot change the option 'backing.driver'")
843
844        # If we remove hd1's options from the dict then things work fine
845        opts['backing'] = opts['backing']['backing']
846        self.reopen(opts)
847
848        # We can also reopen hd0 if we use a reference to the backing file
849        self.reopen(opts, {'backing': 'hd2'})
850
851        # But we cannot leave the option out
852        del opts['backing']
853        self.reopen(opts, {}, "backing is missing for 'hd0'")
854
855        # Now we can delete hd0 (and hd2)
856        result = self.vm.qmp('blockdev-del', conv_keys = True, node_name = 'hd0')
857        self.assert_qmp(result, 'return', {})
858        self.assertEqual(self.get_node('hd2'), None)
859
860    # Reopen the chain during a block-stream job (from hd1 to hd0)
861    def test_block_stream_3(self):
862        # hd2 <- hd1 <- hd0
863        opts = hd_opts(0)
864        opts['backing'] = hd_opts(1)
865        opts['backing']['backing'] = hd_opts(2)
866        result = self.vm.qmp('blockdev-add', conv_keys = False, **opts)
867        self.assert_qmp(result, 'return', {})
868
869        # hd2 <- hd0
870        result = self.vm.qmp('block-stream', conv_keys = True, job_id = 'stream0',
871                             device = 'hd0', base_node = 'hd2',
872                             auto_finalize = False)
873        self.assert_qmp(result, 'return', {})
874
875        # We can remove hd2 while the stream job is ongoing
876        opts['backing']['backing'] = None
877        self.reopen(opts, {})
878
879        # We can't remove hd1 while the stream job is ongoing
880        opts['backing'] = None
881        self.reopen(opts, {}, "Cannot change 'backing' link from 'hd0' to 'hd1'")
882
883        self.vm.run_job('stream0', auto_finalize = False, auto_dismiss = True)
884
885    # Reopen the chain during a block-stream job (from hd2 to hd1)
886    def test_block_stream_4(self):
887        # hd2 <- hd1 <- hd0
888        opts = hd_opts(0)
889        opts['backing'] = hd_opts(1)
890        opts['backing']['backing'] = hd_opts(2)
891        result = self.vm.qmp('blockdev-add', conv_keys = False, **opts)
892        self.assert_qmp(result, 'return', {})
893
894        # hd1 <- hd0
895        result = self.vm.qmp('block-stream', conv_keys = True, job_id = 'stream0',
896                             device = 'hd1', filter_node_name='cor',
897                             auto_finalize = False)
898        self.assert_qmp(result, 'return', {})
899
900        # We can't reopen with the original options because there is a filter
901        # inserted by stream job above hd1.
902        self.reopen(opts, {},
903                    "Cannot change the option 'backing.backing.file.node-name'")
904
905        # We can't reopen hd1 to read-only, as block-stream requires it to be
906        # read-write
907        self.reopen(opts['backing'], {'read-only': True},
908                    "Read-only block node 'hd1' cannot support read-write users")
909
910        # We can't remove hd2 while the stream job is ongoing
911        opts['backing']['backing'] = None
912        self.reopen(opts['backing'], {'read-only': False},
913                    "Cannot change 'backing' link from 'hd1' to 'hd2'")
914
915        # We can detach hd1 from hd0 because it doesn't affect the stream job
916        opts['backing'] = None
917        self.reopen(opts)
918
919        self.vm.run_job('stream0', auto_finalize = False, auto_dismiss = True)
920
921    # Reopen the chain during a block-commit job (from hd0 to hd2)
922    def test_block_commit_1(self):
923        # hd2 <- hd1 <- hd0
924        opts = hd_opts(0)
925        opts['backing'] = hd_opts(1)
926        opts['backing']['backing'] = hd_opts(2)
927        result = self.vm.qmp('blockdev-add', conv_keys = False, **opts)
928        self.assert_qmp(result, 'return', {})
929
930        result = self.vm.qmp('block-commit', conv_keys = True, job_id = 'commit0',
931                             device = 'hd0')
932        self.assert_qmp(result, 'return', {})
933
934        # We can't remove hd2 while the commit job is ongoing
935        opts['backing']['backing'] = None
936        self.reopen(opts, {}, "Cannot change 'backing' link from 'hd1' to 'hd2'")
937
938        # We can't remove hd1 while the commit job is ongoing
939        opts['backing'] = None
940        self.reopen(opts, {}, "Cannot change 'backing' link from 'hd0' to 'hd1'")
941
942        event = self.vm.event_wait(name='BLOCK_JOB_READY')
943        self.assert_qmp(event, 'data/device', 'commit0')
944        self.assert_qmp(event, 'data/type', 'commit')
945        self.assert_qmp_absent(event, 'data/error')
946
947        result = self.vm.qmp('block-job-complete', device='commit0')
948        self.assert_qmp(result, 'return', {})
949
950        self.wait_until_completed(drive = 'commit0')
951
952    # Reopen the chain during a block-commit job (from hd1 to hd2)
953    def test_block_commit_2(self):
954        # hd2 <- hd1 <- hd0
955        opts = hd_opts(0)
956        opts['backing'] = hd_opts(1)
957        opts['backing']['backing'] = hd_opts(2)
958        result = self.vm.qmp('blockdev-add', conv_keys = False, **opts)
959        self.assert_qmp(result, 'return', {})
960
961        result = self.vm.qmp('block-commit', conv_keys = True, job_id = 'commit0',
962                             device = 'hd0', top_node = 'hd1',
963                             auto_finalize = False)
964        self.assert_qmp(result, 'return', {})
965
966        # We can't remove hd2 while the commit job is ongoing
967        opts['backing']['backing'] = None
968        self.reopen(opts, {}, "Cannot change the option 'backing.driver'")
969
970        # We can't remove hd1 while the commit job is ongoing
971        opts['backing'] = None
972        self.reopen(opts, {}, "Cannot change backing link if 'hd0' has an implicit backing file")
973
974        # hd2 <- hd0
975        self.vm.run_job('commit0', auto_finalize = False, auto_dismiss = True)
976
977        self.assert_qmp(self.get_node('hd0'), 'ro', False)
978        self.assertEqual(self.get_node('hd1'), None)
979        self.assert_qmp(self.get_node('hd2'), 'ro', True)
980
981    def run_test_iothreads(self, iothread_a, iothread_b, errmsg = None):
982        opts = hd_opts(0)
983        result = self.vm.qmp('blockdev-add', conv_keys = False, **opts)
984        self.assert_qmp(result, 'return', {})
985
986        opts2 = hd_opts(2)
987        result = self.vm.qmp('blockdev-add', conv_keys = False, **opts2)
988        self.assert_qmp(result, 'return', {})
989
990        result = self.vm.qmp('object-add', qom_type='iothread', id='iothread0')
991        self.assert_qmp(result, 'return', {})
992
993        result = self.vm.qmp('object-add', qom_type='iothread', id='iothread1')
994        self.assert_qmp(result, 'return', {})
995
996        result = self.vm.qmp('device_add', driver='virtio-scsi', id='scsi0',
997                             iothread=iothread_a)
998        self.assert_qmp(result, 'return', {})
999
1000        result = self.vm.qmp('device_add', driver='virtio-scsi', id='scsi1',
1001                             iothread=iothread_b)
1002        self.assert_qmp(result, 'return', {})
1003
1004        if iothread_a:
1005            result = self.vm.qmp('device_add', driver='scsi-hd', drive='hd0',
1006                                 share_rw=True, bus="scsi0.0")
1007            self.assert_qmp(result, 'return', {})
1008
1009        if iothread_b:
1010            result = self.vm.qmp('device_add', driver='scsi-hd', drive='hd2',
1011                                 share_rw=True, bus="scsi1.0")
1012            self.assert_qmp(result, 'return', {})
1013
1014        # Attaching the backing file may or may not work
1015        self.reopen(opts, {'backing': 'hd2'}, errmsg)
1016
1017        # But removing the backing file should always work
1018        self.reopen(opts, {'backing': None})
1019
1020        self.vm.shutdown()
1021
1022    # We don't allow setting a backing file that uses a different AioContext if
1023    # neither of them can switch to the other AioContext
1024    def test_iothreads_error(self):
1025        self.run_test_iothreads('iothread0', 'iothread1',
1026                                "Cannot change iothread of active block backend")
1027
1028    def test_iothreads_compatible_users(self):
1029        self.run_test_iothreads('iothread0', 'iothread0')
1030
1031    def test_iothreads_switch_backing(self):
1032        self.run_test_iothreads('iothread0', None)
1033
1034    def test_iothreads_switch_overlay(self):
1035        self.run_test_iothreads(None, 'iothread0')
1036
1037if __name__ == '__main__':
1038    iotests.activate_logging()
1039    iotests.main(supported_fmts=["qcow2"],
1040                 supported_protocols=["file"])
1041