xref: /openbmc/qemu/tests/qemu-iotests/041 (revision 65a117da)
1#!/usr/bin/env python3
2#
3# Tests for image mirroring.
4#
5# Copyright (C) 2012 Red Hat, Inc.
6#
7# This program is free software; you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation; either version 2 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program.  If not, see <http://www.gnu.org/licenses/>.
19#
20
21import time
22import os
23import re
24import iotests
25from iotests import qemu_img, qemu_io
26
27backing_img = os.path.join(iotests.test_dir, 'backing.img')
28target_backing_img = os.path.join(iotests.test_dir, 'target-backing.img')
29test_img = os.path.join(iotests.test_dir, 'test.img')
30target_img = os.path.join(iotests.test_dir, 'target.img')
31
32quorum_img1 = os.path.join(iotests.test_dir, 'quorum1.img')
33quorum_img2 = os.path.join(iotests.test_dir, 'quorum2.img')
34quorum_img3 = os.path.join(iotests.test_dir, 'quorum3.img')
35quorum_repair_img = os.path.join(iotests.test_dir, 'quorum_repair.img')
36quorum_snapshot_file = os.path.join(iotests.test_dir, 'quorum_snapshot.img')
37
38nbd_sock_path = os.path.join(iotests.sock_dir, 'nbd.sock')
39
40class TestSingleDrive(iotests.QMPTestCase):
41    image_len = 1 * 1024 * 1024 # MB
42    qmp_cmd = 'drive-mirror'
43    qmp_target = target_img
44
45    def setUp(self):
46        iotests.create_image(backing_img, self.image_len)
47        qemu_img('create', '-f', iotests.imgfmt, '-o', 'backing_file=%s' % backing_img, test_img)
48        self.vm = iotests.VM().add_drive(test_img, "node-name=top,backing.node-name=base")
49        if iotests.qemu_default_machine == 'pc':
50            self.vm.add_drive(None, 'media=cdrom', 'ide')
51        self.vm.launch()
52
53    def tearDown(self):
54        self.vm.shutdown()
55        os.remove(test_img)
56        os.remove(backing_img)
57        try:
58            os.remove(target_img)
59        except OSError:
60            pass
61
62    def test_complete(self):
63        self.assert_no_active_block_jobs()
64
65        result = self.vm.qmp(self.qmp_cmd, device='drive0', sync='full',
66                             target=self.qmp_target)
67        self.assert_qmp(result, 'return', {})
68
69        self.complete_and_wait()
70        result = self.vm.qmp('query-block')
71        self.assert_qmp(result, 'return[0]/inserted/file', target_img)
72        self.vm.shutdown()
73        self.assertTrue(iotests.compare_images(test_img, target_img),
74                        'target image does not match source after mirroring')
75
76    def test_cancel(self):
77        self.assert_no_active_block_jobs()
78
79        result = self.vm.qmp(self.qmp_cmd, device='drive0', sync='full',
80                             target=self.qmp_target)
81        self.assert_qmp(result, 'return', {})
82
83        self.cancel_and_wait(force=True)
84        result = self.vm.qmp('query-block')
85        self.assert_qmp(result, 'return[0]/inserted/file', test_img)
86
87    def test_cancel_after_ready(self):
88        self.assert_no_active_block_jobs()
89
90        result = self.vm.qmp(self.qmp_cmd, device='drive0', sync='full',
91                             target=self.qmp_target)
92        self.assert_qmp(result, 'return', {})
93
94        self.wait_ready_and_cancel()
95        result = self.vm.qmp('query-block')
96        self.assert_qmp(result, 'return[0]/inserted/file', test_img)
97        self.vm.shutdown()
98        self.assertTrue(iotests.compare_images(test_img, target_img),
99                        'target image does not match source after mirroring')
100
101    def test_pause(self):
102        self.assert_no_active_block_jobs()
103
104        result = self.vm.qmp(self.qmp_cmd, device='drive0', sync='full',
105                             target=self.qmp_target)
106        self.assert_qmp(result, 'return', {})
107
108        self.pause_job('drive0')
109
110        result = self.vm.qmp('query-block-jobs')
111        offset = self.dictpath(result, 'return[0]/offset')
112
113        time.sleep(0.5)
114        result = self.vm.qmp('query-block-jobs')
115        self.assert_qmp(result, 'return[0]/offset', offset)
116
117        result = self.vm.qmp('block-job-resume', device='drive0')
118        self.assert_qmp(result, 'return', {})
119
120        self.complete_and_wait()
121        self.vm.shutdown()
122        self.assertTrue(iotests.compare_images(test_img, target_img),
123                        'target image does not match source after mirroring')
124
125    def test_small_buffer(self):
126        self.assert_no_active_block_jobs()
127
128        # A small buffer is rounded up automatically
129        result = self.vm.qmp(self.qmp_cmd, device='drive0', sync='full',
130                             buf_size=4096, target=self.qmp_target)
131        self.assert_qmp(result, 'return', {})
132
133        self.complete_and_wait()
134        result = self.vm.qmp('query-block')
135        self.assert_qmp(result, 'return[0]/inserted/file', target_img)
136        self.vm.shutdown()
137        self.assertTrue(iotests.compare_images(test_img, target_img),
138                        'target image does not match source after mirroring')
139
140    def test_small_buffer2(self):
141        self.assert_no_active_block_jobs()
142
143        qemu_img('create', '-f', iotests.imgfmt, '-o', 'cluster_size=%d,size=%d'
144                        % (self.image_len, self.image_len), target_img)
145        result = self.vm.qmp(self.qmp_cmd, device='drive0', sync='full',
146                             buf_size=65536, mode='existing', target=self.qmp_target)
147        self.assert_qmp(result, 'return', {})
148
149        self.complete_and_wait()
150        result = self.vm.qmp('query-block')
151        self.assert_qmp(result, 'return[0]/inserted/file', target_img)
152        self.vm.shutdown()
153        self.assertTrue(iotests.compare_images(test_img, target_img),
154                        'target image does not match source after mirroring')
155
156    def test_large_cluster(self):
157        self.assert_no_active_block_jobs()
158
159        qemu_img('create', '-f', iotests.imgfmt, '-o', 'cluster_size=%d,backing_file=%s'
160                        % (self.image_len, backing_img), target_img)
161        result = self.vm.qmp(self.qmp_cmd, device='drive0', sync='full',
162                             mode='existing', target=self.qmp_target)
163        self.assert_qmp(result, 'return', {})
164
165        self.complete_and_wait()
166        result = self.vm.qmp('query-block')
167        self.assert_qmp(result, 'return[0]/inserted/file', target_img)
168        self.vm.shutdown()
169        self.assertTrue(iotests.compare_images(test_img, target_img),
170                        'target image does not match source after mirroring')
171
172    # Tests that the insertion of the mirror_top filter node doesn't make a
173    # difference to query-block
174    def test_implicit_node(self):
175        self.assert_no_active_block_jobs()
176
177        result = self.vm.qmp(self.qmp_cmd, device='drive0', sync='full',
178                             target=self.qmp_target)
179        self.assert_qmp(result, 'return', {})
180
181        result = self.vm.qmp('query-block')
182        self.assert_qmp(result, 'return[0]/inserted/file', test_img)
183        self.assert_qmp(result, 'return[0]/inserted/drv', iotests.imgfmt)
184        self.assert_qmp(result, 'return[0]/inserted/backing_file', backing_img)
185        self.assert_qmp(result, 'return[0]/inserted/backing_file_depth', 1)
186        self.assert_qmp(result, 'return[0]/inserted/image/filename', test_img)
187        self.assert_qmp(result, 'return[0]/inserted/image/backing-image/filename', backing_img)
188
189        result = self.vm.qmp('query-blockstats')
190        self.assert_qmp(result, 'return[0]/node-name', 'top')
191        self.assert_qmp(result, 'return[0]/backing/node-name', 'base')
192
193        self.cancel_and_wait(force=True)
194        result = self.vm.qmp('query-block')
195        self.assert_qmp(result, 'return[0]/inserted/file', test_img)
196        self.assert_qmp(result, 'return[0]/inserted/drv', iotests.imgfmt)
197        self.assert_qmp(result, 'return[0]/inserted/backing_file', backing_img)
198        self.assert_qmp(result, 'return[0]/inserted/backing_file_depth', 1)
199        self.assert_qmp(result, 'return[0]/inserted/image/filename', test_img)
200        self.assert_qmp(result, 'return[0]/inserted/image/backing-image/filename', backing_img)
201
202        result = self.vm.qmp('query-blockstats')
203        self.assert_qmp(result, 'return[0]/node-name', 'top')
204        self.assert_qmp(result, 'return[0]/backing/node-name', 'base')
205
206    def test_medium_not_found(self):
207        if iotests.qemu_default_machine != 'pc':
208            return
209
210        result = self.vm.qmp(self.qmp_cmd, device='ide1-cd0', sync='full',
211                             target=self.qmp_target)
212        self.assert_qmp(result, 'error/class', 'GenericError')
213
214    def test_image_not_found(self):
215        result = self.vm.qmp(self.qmp_cmd, device='drive0', sync='full',
216                             mode='existing', target=self.qmp_target)
217        self.assert_qmp(result, 'error/class', 'GenericError')
218
219    def test_device_not_found(self):
220        result = self.vm.qmp(self.qmp_cmd, device='nonexistent', sync='full',
221                             target=self.qmp_target)
222        self.assert_qmp(result, 'error/class', 'GenericError')
223
224class TestSingleBlockdev(TestSingleDrive):
225    qmp_cmd = 'blockdev-mirror'
226    qmp_target = 'node1'
227
228    def setUp(self):
229        TestSingleDrive.setUp(self)
230        qemu_img('create', '-f', iotests.imgfmt, '-o', 'backing_file=%s' % backing_img, target_img)
231        args = {'driver': iotests.imgfmt,
232                'node-name': self.qmp_target,
233                'file': { 'filename': target_img, 'driver': 'file' } }
234        result = self.vm.qmp("blockdev-add", **args)
235        self.assert_qmp(result, 'return', {})
236
237    def test_mirror_to_self(self):
238        result = self.vm.qmp(self.qmp_cmd, job_id='job0',
239                             device=self.qmp_target, sync='full',
240                             target=self.qmp_target)
241        self.assert_qmp(result, 'error/class', 'GenericError')
242
243    def do_test_resize(self, device, node):
244        def pre_finalize():
245            if device:
246                result = self.vm.qmp('block_resize', device=device, size=65536)
247                self.assert_qmp(result, 'error/class', 'GenericError')
248
249            result = self.vm.qmp('block_resize', node_name=node, size=65536)
250            self.assert_qmp(result, 'error/class', 'GenericError')
251
252        result = self.vm.qmp(self.qmp_cmd, job_id='job0', device='drive0',
253                             sync='full', target=self.qmp_target,
254                             auto_finalize=False, auto_dismiss=False)
255        self.assert_qmp(result, 'return', {})
256
257        result = self.vm.run_job('job0', auto_finalize=False,
258                                 pre_finalize=pre_finalize)
259        self.assertEqual(result, None)
260
261    def test_source_resize(self):
262        self.do_test_resize('drive0', 'top')
263
264    def test_target_resize(self):
265        self.do_test_resize(None, self.qmp_target)
266
267    def do_test_target_size(self, size):
268        result = self.vm.qmp('block_resize', node_name=self.qmp_target,
269                             size=size)
270        self.assert_qmp(result, 'return', {})
271
272        result = self.vm.qmp(self.qmp_cmd, job_id='job0',
273                             device='drive0', sync='full', auto_dismiss=False,
274                             target=self.qmp_target)
275        self.assert_qmp(result, 'return', {})
276
277        result = self.vm.run_job('job0')
278        self.assertEqual(result, 'Source and target image have different sizes')
279
280    def test_small_target(self):
281        self.do_test_target_size(self.image_len // 2)
282
283    def test_large_target(self):
284        self.do_test_target_size(self.image_len * 2)
285
286    test_large_cluster = None
287    test_image_not_found = None
288    test_small_buffer2 = None
289
290class TestSingleDriveZeroLength(TestSingleDrive):
291    image_len = 0
292    test_small_buffer2 = None
293    test_large_cluster = None
294
295class TestSingleBlockdevZeroLength(TestSingleBlockdev):
296    image_len = 0
297    test_small_target = None
298    test_large_target = None
299
300class TestSingleDriveUnalignedLength(TestSingleDrive):
301    image_len = 1025 * 1024
302    test_small_buffer2 = None
303    test_large_cluster = None
304
305class TestSingleBlockdevUnalignedLength(TestSingleBlockdev):
306    image_len = 1025 * 1024
307
308class TestMirrorNoBacking(iotests.QMPTestCase):
309    image_len = 2 * 1024 * 1024 # MB
310
311    def setUp(self):
312        iotests.create_image(backing_img, TestMirrorNoBacking.image_len)
313        qemu_img('create', '-f', iotests.imgfmt, '-o', 'backing_file=%s' % backing_img, test_img)
314        self.vm = iotests.VM().add_drive(test_img)
315        self.vm.launch()
316
317    def tearDown(self):
318        self.vm.shutdown()
319        os.remove(test_img)
320        os.remove(backing_img)
321        try:
322            os.remove(target_backing_img)
323        except:
324            pass
325        os.remove(target_img)
326
327    def test_complete(self):
328        self.assert_no_active_block_jobs()
329
330        qemu_img('create', '-f', iotests.imgfmt, '-o', 'backing_file=%s' % backing_img, target_img)
331        result = self.vm.qmp('drive-mirror', device='drive0', sync='full',
332                             mode='existing', target=target_img)
333        self.assert_qmp(result, 'return', {})
334
335        self.complete_and_wait()
336        result = self.vm.qmp('query-block')
337        self.assert_qmp(result, 'return[0]/inserted/file', target_img)
338        self.vm.shutdown()
339        self.assertTrue(iotests.compare_images(test_img, target_img),
340                        'target image does not match source after mirroring')
341
342    def test_cancel(self):
343        self.assert_no_active_block_jobs()
344
345        qemu_img('create', '-f', iotests.imgfmt, '-o', 'backing_file=%s' % backing_img, target_img)
346        result = self.vm.qmp('drive-mirror', device='drive0', sync='full',
347                             mode='existing', target=target_img)
348        self.assert_qmp(result, 'return', {})
349
350        self.wait_ready_and_cancel()
351        result = self.vm.qmp('query-block')
352        self.assert_qmp(result, 'return[0]/inserted/file', test_img)
353        self.vm.shutdown()
354        self.assertTrue(iotests.compare_images(test_img, target_img),
355                        'target image does not match source after mirroring')
356
357    def test_large_cluster(self):
358        self.assert_no_active_block_jobs()
359
360        # qemu-img create fails if the image is not there
361        qemu_img('create', '-f', iotests.imgfmt, '-o', 'size=%d'
362                        %(TestMirrorNoBacking.image_len), target_backing_img)
363        qemu_img('create', '-f', iotests.imgfmt, '-o', 'cluster_size=%d,backing_file=%s'
364                        % (TestMirrorNoBacking.image_len, target_backing_img), target_img)
365
366        result = self.vm.qmp('drive-mirror', device='drive0', sync='full',
367                             mode='existing', target=target_img)
368        self.assert_qmp(result, 'return', {})
369
370        self.complete_and_wait()
371        result = self.vm.qmp('query-block')
372        self.assert_qmp(result, 'return[0]/inserted/file', target_img)
373        self.vm.shutdown()
374        self.assertTrue(iotests.compare_images(test_img, target_img),
375                        'target image does not match source after mirroring')
376
377class TestMirrorResized(iotests.QMPTestCase):
378    backing_len = 1 * 1024 * 1024 # MB
379    image_len = 2 * 1024 * 1024 # MB
380
381    def setUp(self):
382        iotests.create_image(backing_img, TestMirrorResized.backing_len)
383        qemu_img('create', '-f', iotests.imgfmt, '-o', 'backing_file=%s' % backing_img, test_img)
384        qemu_img('resize', test_img, '2M')
385        self.vm = iotests.VM().add_drive(test_img)
386        self.vm.launch()
387
388    def tearDown(self):
389        self.vm.shutdown()
390        os.remove(test_img)
391        os.remove(backing_img)
392        try:
393            os.remove(target_img)
394        except OSError:
395            pass
396
397    def test_complete_top(self):
398        self.assert_no_active_block_jobs()
399
400        result = self.vm.qmp('drive-mirror', device='drive0', sync='top',
401                             target=target_img)
402        self.assert_qmp(result, 'return', {})
403
404        self.complete_and_wait()
405        result = self.vm.qmp('query-block')
406        self.assert_qmp(result, 'return[0]/inserted/file', target_img)
407        self.vm.shutdown()
408        self.assertTrue(iotests.compare_images(test_img, target_img),
409                        'target image does not match source after mirroring')
410
411    def test_complete_full(self):
412        self.assert_no_active_block_jobs()
413
414        result = self.vm.qmp('drive-mirror', device='drive0', sync='full',
415                             target=target_img)
416        self.assert_qmp(result, 'return', {})
417
418        self.complete_and_wait()
419        result = self.vm.qmp('query-block')
420        self.assert_qmp(result, 'return[0]/inserted/file', target_img)
421        self.vm.shutdown()
422        self.assertTrue(iotests.compare_images(test_img, target_img),
423                        'target image does not match source after mirroring')
424
425class TestReadErrors(iotests.QMPTestCase):
426    image_len = 2 * 1024 * 1024 # MB
427
428    # this should be a multiple of twice the default granularity
429    # so that we hit this offset first in state 1
430    MIRROR_GRANULARITY = 1024 * 1024
431
432    def create_blkdebug_file(self, name, event, errno):
433        file = open(name, 'w')
434        file.write('''
435[inject-error]
436state = "1"
437event = "%s"
438errno = "%d"
439immediately = "off"
440once = "on"
441sector = "%d"
442
443[set-state]
444state = "1"
445event = "%s"
446new_state = "2"
447
448[set-state]
449state = "2"
450event = "%s"
451new_state = "1"
452''' % (event, errno, self.MIRROR_GRANULARITY // 512, event, event))
453        file.close()
454
455    def setUp(self):
456        self.blkdebug_file = backing_img + ".blkdebug"
457        iotests.create_image(backing_img, TestReadErrors.image_len)
458        self.create_blkdebug_file(self.blkdebug_file, "read_aio", 5)
459        qemu_img('create', '-f', iotests.imgfmt,
460                 '-o', 'backing_file=blkdebug:%s:%s,backing_fmt=raw'
461                       % (self.blkdebug_file, backing_img),
462                 test_img)
463        # Write something for tests that use sync='top'
464        qemu_io('-c', 'write %d 512' % (self.MIRROR_GRANULARITY + 65536),
465                        test_img)
466        self.vm = iotests.VM().add_drive(test_img)
467        self.vm.launch()
468
469    def tearDown(self):
470        self.vm.shutdown()
471        os.remove(test_img)
472        os.remove(target_img)
473        os.remove(backing_img)
474        os.remove(self.blkdebug_file)
475
476    def test_report_read(self):
477        self.assert_no_active_block_jobs()
478
479        result = self.vm.qmp('drive-mirror', device='drive0', sync='full',
480                             target=target_img)
481        self.assert_qmp(result, 'return', {})
482
483        completed = False
484        error = False
485        while not completed:
486            for event in self.vm.get_qmp_events(wait=True):
487                if event['event'] == 'BLOCK_JOB_ERROR':
488                    self.assert_qmp(event, 'data/device', 'drive0')
489                    self.assert_qmp(event, 'data/operation', 'read')
490                    error = True
491                elif event['event'] == 'BLOCK_JOB_READY':
492                    self.assertTrue(False, 'job completed unexpectedly')
493                elif event['event'] == 'BLOCK_JOB_COMPLETED':
494                    self.assertTrue(error, 'job completed unexpectedly')
495                    self.assert_qmp(event, 'data/type', 'mirror')
496                    self.assert_qmp(event, 'data/device', 'drive0')
497                    self.assert_qmp(event, 'data/error', 'Input/output error')
498                    completed = True
499                elif event['event'] == 'JOB_STATUS_CHANGE':
500                    self.assert_qmp(event, 'data/id', 'drive0')
501
502        self.assert_no_active_block_jobs()
503
504    def test_ignore_read(self):
505        self.assert_no_active_block_jobs()
506
507        result = self.vm.qmp('drive-mirror', device='drive0', sync='full',
508                             target=target_img, on_source_error='ignore')
509        self.assert_qmp(result, 'return', {})
510
511        event = self.vm.get_qmp_event(wait=True)
512        while event['event'] == 'JOB_STATUS_CHANGE':
513            self.assert_qmp(event, 'data/id', 'drive0')
514            event = self.vm.get_qmp_event(wait=True)
515
516        self.assertEqual(event['event'], 'BLOCK_JOB_ERROR')
517        self.assert_qmp(event, 'data/device', 'drive0')
518        self.assert_qmp(event, 'data/operation', 'read')
519        result = self.vm.qmp('query-block-jobs')
520        self.assert_qmp(result, 'return[0]/paused', False)
521        self.complete_and_wait()
522
523    def test_large_cluster(self):
524        self.assert_no_active_block_jobs()
525
526        # Test COW into the target image.  The first half of the
527        # cluster at MIRROR_GRANULARITY has to be copied from
528        # backing_img, even though sync='top'.
529        qemu_img('create', '-f', iotests.imgfmt, '-ocluster_size=131072,backing_file=%s' %(backing_img), target_img)
530        result = self.vm.qmp('drive-mirror', device='drive0', sync='top',
531                             on_source_error='ignore',
532                             mode='existing', target=target_img)
533        self.assert_qmp(result, 'return', {})
534
535        event = self.vm.get_qmp_event(wait=True)
536        while event['event'] == 'JOB_STATUS_CHANGE':
537            self.assert_qmp(event, 'data/id', 'drive0')
538            event = self.vm.get_qmp_event(wait=True)
539
540        self.assertEqual(event['event'], 'BLOCK_JOB_ERROR')
541        self.assert_qmp(event, 'data/device', 'drive0')
542        self.assert_qmp(event, 'data/operation', 'read')
543        result = self.vm.qmp('query-block-jobs')
544        self.assert_qmp(result, 'return[0]/paused', False)
545        self.complete_and_wait()
546        self.vm.shutdown()
547
548        # Detach blkdebug to compare images successfully
549        qemu_img('rebase', '-f', iotests.imgfmt, '-u', '-b', backing_img, test_img)
550        self.assertTrue(iotests.compare_images(test_img, target_img),
551                        'target image does not match source after mirroring')
552
553    def test_stop_read(self):
554        self.assert_no_active_block_jobs()
555
556        result = self.vm.qmp('drive-mirror', device='drive0', sync='full',
557                             target=target_img, on_source_error='stop')
558        self.assert_qmp(result, 'return', {})
559
560        error = False
561        ready = False
562        while not ready:
563            for event in self.vm.get_qmp_events(wait=True):
564                if event['event'] == 'BLOCK_JOB_ERROR':
565                    self.assert_qmp(event, 'data/device', 'drive0')
566                    self.assert_qmp(event, 'data/operation', 'read')
567
568                    result = self.vm.qmp('query-block-jobs')
569                    self.assert_qmp(result, 'return[0]/paused', True)
570                    self.assert_qmp(result, 'return[0]/io-status', 'failed')
571
572                    result = self.vm.qmp('block-job-resume', device='drive0')
573                    self.assert_qmp(result, 'return', {})
574                    error = True
575                elif event['event'] == 'BLOCK_JOB_READY':
576                    self.assertTrue(error, 'job completed unexpectedly')
577                    self.assert_qmp(event, 'data/device', 'drive0')
578                    ready = True
579
580        result = self.vm.qmp('query-block-jobs')
581        self.assert_qmp(result, 'return[0]/paused', False)
582        self.assert_qmp(result, 'return[0]/io-status', 'ok')
583
584        self.complete_and_wait(wait_ready=False)
585        self.assert_no_active_block_jobs()
586
587class TestWriteErrors(iotests.QMPTestCase):
588    image_len = 2 * 1024 * 1024 # MB
589
590    # this should be a multiple of twice the default granularity
591    # so that we hit this offset first in state 1
592    MIRROR_GRANULARITY = 1024 * 1024
593
594    def create_blkdebug_file(self, name, event, errno):
595        file = open(name, 'w')
596        file.write('''
597[inject-error]
598state = "1"
599event = "%s"
600errno = "%d"
601immediately = "off"
602once = "on"
603sector = "%d"
604
605[set-state]
606state = "1"
607event = "%s"
608new_state = "2"
609
610[set-state]
611state = "2"
612event = "%s"
613new_state = "1"
614''' % (event, errno, self.MIRROR_GRANULARITY // 512, event, event))
615        file.close()
616
617    def setUp(self):
618        self.blkdebug_file = target_img + ".blkdebug"
619        iotests.create_image(backing_img, TestWriteErrors.image_len)
620        self.create_blkdebug_file(self.blkdebug_file, "write_aio", 5)
621        qemu_img('create', '-f', iotests.imgfmt, '-obacking_file=%s' %(backing_img), test_img)
622        self.vm = iotests.VM().add_drive(test_img)
623        self.target_img = 'blkdebug:%s:%s' % (self.blkdebug_file, target_img)
624        qemu_img('create', '-f', iotests.imgfmt, '-osize=%d' %(TestWriteErrors.image_len), target_img)
625        self.vm.launch()
626
627    def tearDown(self):
628        self.vm.shutdown()
629        os.remove(test_img)
630        os.remove(target_img)
631        os.remove(backing_img)
632        os.remove(self.blkdebug_file)
633
634    def test_report_write(self):
635        self.assert_no_active_block_jobs()
636
637        result = self.vm.qmp('drive-mirror', device='drive0', sync='full',
638                             mode='existing', target=self.target_img)
639        self.assert_qmp(result, 'return', {})
640
641        completed = False
642        error = False
643        while not completed:
644            for event in self.vm.get_qmp_events(wait=True):
645                if event['event'] == 'BLOCK_JOB_ERROR':
646                    self.assert_qmp(event, 'data/device', 'drive0')
647                    self.assert_qmp(event, 'data/operation', 'write')
648                    error = True
649                elif event['event'] == 'BLOCK_JOB_READY':
650                    self.assertTrue(False, 'job completed unexpectedly')
651                elif event['event'] == 'BLOCK_JOB_COMPLETED':
652                    self.assertTrue(error, 'job completed unexpectedly')
653                    self.assert_qmp(event, 'data/type', 'mirror')
654                    self.assert_qmp(event, 'data/device', 'drive0')
655                    self.assert_qmp(event, 'data/error', 'Input/output error')
656                    completed = True
657
658        self.assert_no_active_block_jobs()
659
660    def test_ignore_write(self):
661        self.assert_no_active_block_jobs()
662
663        result = self.vm.qmp('drive-mirror', device='drive0', sync='full',
664                             mode='existing', target=self.target_img,
665                             on_target_error='ignore')
666        self.assert_qmp(result, 'return', {})
667
668        event = self.vm.event_wait(name='BLOCK_JOB_ERROR')
669        self.assertEqual(event['event'], 'BLOCK_JOB_ERROR')
670        self.assert_qmp(event, 'data/device', 'drive0')
671        self.assert_qmp(event, 'data/operation', 'write')
672        result = self.vm.qmp('query-block-jobs')
673        self.assert_qmp(result, 'return[0]/paused', False)
674        self.complete_and_wait()
675
676    def test_stop_write(self):
677        self.assert_no_active_block_jobs()
678
679        result = self.vm.qmp('drive-mirror', device='drive0', sync='full',
680                             mode='existing', target=self.target_img,
681                             on_target_error='stop')
682        self.assert_qmp(result, 'return', {})
683
684        error = False
685        ready = False
686        while not ready:
687            for event in self.vm.get_qmp_events(wait=True):
688                if event['event'] == 'BLOCK_JOB_ERROR':
689                    self.assert_qmp(event, 'data/device', 'drive0')
690                    self.assert_qmp(event, 'data/operation', 'write')
691
692                    result = self.vm.qmp('query-block-jobs')
693                    self.assert_qmp(result, 'return[0]/paused', True)
694                    self.assert_qmp(result, 'return[0]/io-status', 'failed')
695
696                    result = self.vm.qmp('block-job-resume', device='drive0')
697                    self.assert_qmp(result, 'return', {})
698
699                    result = self.vm.qmp('query-block-jobs')
700                    self.assert_qmp(result, 'return[0]/paused', False)
701                    self.assert_qmp(result, 'return[0]/io-status', 'ok')
702                    error = True
703                elif event['event'] == 'BLOCK_JOB_READY':
704                    self.assertTrue(error, 'job completed unexpectedly')
705                    self.assert_qmp(event, 'data/device', 'drive0')
706                    ready = True
707
708        self.complete_and_wait(wait_ready=False)
709        self.assert_no_active_block_jobs()
710
711class TestSetSpeed(iotests.QMPTestCase):
712    image_len = 80 * 1024 * 1024 # MB
713
714    def setUp(self):
715        qemu_img('create', backing_img, str(TestSetSpeed.image_len))
716        qemu_img('create', '-f', iotests.imgfmt, '-o', 'backing_file=%s' % backing_img, test_img)
717        self.vm = iotests.VM().add_drive(test_img)
718        self.vm.launch()
719
720    def tearDown(self):
721        self.vm.shutdown()
722        os.remove(test_img)
723        os.remove(backing_img)
724        os.remove(target_img)
725
726    def test_set_speed(self):
727        self.assert_no_active_block_jobs()
728
729        result = self.vm.qmp('drive-mirror', device='drive0', sync='full',
730                             target=target_img)
731        self.assert_qmp(result, 'return', {})
732
733        # Default speed is 0
734        result = self.vm.qmp('query-block-jobs')
735        self.assert_qmp(result, 'return[0]/device', 'drive0')
736        self.assert_qmp(result, 'return[0]/speed', 0)
737
738        result = self.vm.qmp('block-job-set-speed', device='drive0', speed=8 * 1024 * 1024)
739        self.assert_qmp(result, 'return', {})
740
741        # Ensure the speed we set was accepted
742        result = self.vm.qmp('query-block-jobs')
743        self.assert_qmp(result, 'return[0]/device', 'drive0')
744        self.assert_qmp(result, 'return[0]/speed', 8 * 1024 * 1024)
745
746        self.wait_ready_and_cancel()
747
748        # Check setting speed in drive-mirror works
749        result = self.vm.qmp('drive-mirror', device='drive0', sync='full',
750                             target=target_img, speed=4*1024*1024)
751        self.assert_qmp(result, 'return', {})
752
753        result = self.vm.qmp('query-block-jobs')
754        self.assert_qmp(result, 'return[0]/device', 'drive0')
755        self.assert_qmp(result, 'return[0]/speed', 4 * 1024 * 1024)
756
757        self.wait_ready_and_cancel()
758
759    def test_set_speed_invalid(self):
760        self.assert_no_active_block_jobs()
761
762        result = self.vm.qmp('drive-mirror', device='drive0', sync='full',
763                             target=target_img, speed=-1)
764        self.assert_qmp(result, 'error/class', 'GenericError')
765
766        self.assert_no_active_block_jobs()
767
768        result = self.vm.qmp('drive-mirror', device='drive0', sync='full',
769                             target=target_img)
770        self.assert_qmp(result, 'return', {})
771
772        result = self.vm.qmp('block-job-set-speed', device='drive0', speed=-1)
773        self.assert_qmp(result, 'error/class', 'GenericError')
774
775        self.wait_ready_and_cancel()
776
777class TestUnbackedSource(iotests.QMPTestCase):
778    image_len = 2 * 1024 * 1024 # MB
779
780    def setUp(self):
781        qemu_img('create', '-f', iotests.imgfmt, test_img,
782                 str(TestUnbackedSource.image_len))
783        self.vm = iotests.VM()
784        self.vm.launch()
785        result = self.vm.qmp('blockdev-add', node_name='drive0',
786                             driver=iotests.imgfmt,
787                             file={
788                                 'driver': 'file',
789                                 'filename': test_img,
790                             })
791        self.assert_qmp(result, 'return', {})
792
793    def tearDown(self):
794        self.vm.shutdown()
795        os.remove(test_img)
796        os.remove(target_img)
797
798    def test_absolute_paths_full(self):
799        self.assert_no_active_block_jobs()
800        result = self.vm.qmp('drive-mirror', job_id='drive0', device='drive0',
801                             sync='full', target=target_img,
802                             mode='absolute-paths')
803        self.assert_qmp(result, 'return', {})
804        self.complete_and_wait()
805        self.assert_no_active_block_jobs()
806
807    def test_absolute_paths_top(self):
808        self.assert_no_active_block_jobs()
809        result = self.vm.qmp('drive-mirror', job_id='drive0', device='drive0',
810                             sync='top', target=target_img,
811                             mode='absolute-paths')
812        self.assert_qmp(result, 'return', {})
813        self.complete_and_wait()
814        self.assert_no_active_block_jobs()
815
816    def test_absolute_paths_none(self):
817        self.assert_no_active_block_jobs()
818        result = self.vm.qmp('drive-mirror', job_id='drive0', device='drive0',
819                             sync='none', target=target_img,
820                             mode='absolute-paths')
821        self.assert_qmp(result, 'return', {})
822        self.complete_and_wait()
823        self.assert_no_active_block_jobs()
824
825    def test_existing_full(self):
826        qemu_img('create', '-f', iotests.imgfmt, target_img,
827                 str(self.image_len))
828        qemu_io('-c', 'write -P 42 0 64k', target_img)
829
830        self.assert_no_active_block_jobs()
831        result = self.vm.qmp('drive-mirror', job_id='drive0', device='drive0',
832                             sync='full', target=target_img, mode='existing')
833        self.assert_qmp(result, 'return', {})
834        self.complete_and_wait()
835        self.assert_no_active_block_jobs()
836
837        result = self.vm.qmp('blockdev-del', node_name='drive0')
838        self.assert_qmp(result, 'return', {})
839
840        self.assertTrue(iotests.compare_images(test_img, target_img),
841                        'target image does not match source after mirroring')
842
843    def test_blockdev_full(self):
844        qemu_img('create', '-f', iotests.imgfmt, target_img,
845                 str(self.image_len))
846        qemu_io('-c', 'write -P 42 0 64k', target_img)
847
848        result = self.vm.qmp('blockdev-add', node_name='target',
849                             driver=iotests.imgfmt,
850                             file={
851                                 'driver': 'file',
852                                 'filename': target_img,
853                             })
854        self.assert_qmp(result, 'return', {})
855
856        self.assert_no_active_block_jobs()
857        result = self.vm.qmp('blockdev-mirror', job_id='drive0', device='drive0',
858                             sync='full', target='target')
859        self.assert_qmp(result, 'return', {})
860        self.complete_and_wait()
861        self.assert_no_active_block_jobs()
862
863        result = self.vm.qmp('blockdev-del', node_name='drive0')
864        self.assert_qmp(result, 'return', {})
865
866        result = self.vm.qmp('blockdev-del', node_name='target')
867        self.assert_qmp(result, 'return', {})
868
869        self.assertTrue(iotests.compare_images(test_img, target_img),
870                        'target image does not match source after mirroring')
871
872class TestGranularity(iotests.QMPTestCase):
873    image_len = 10 * 1024 * 1024 # MB
874
875    def setUp(self):
876        qemu_img('create', '-f', iotests.imgfmt, test_img,
877                 str(TestGranularity.image_len))
878        qemu_io('-c', 'write 0 %d' % (self.image_len),
879                test_img)
880        self.vm = iotests.VM().add_drive(test_img)
881        self.vm.launch()
882
883    def tearDown(self):
884        self.vm.shutdown()
885        self.assertTrue(iotests.compare_images(test_img, target_img),
886                        'target image does not match source after mirroring')
887        os.remove(test_img)
888        os.remove(target_img)
889
890    def test_granularity(self):
891        self.assert_no_active_block_jobs()
892        result = self.vm.qmp('drive-mirror', device='drive0',
893                             sync='full', target=target_img,
894                             mode='absolute-paths', granularity=8192)
895        self.assert_qmp(result, 'return', {})
896
897        event = self.vm.get_qmp_event(wait=60.0)
898        while event['event'] == 'JOB_STATUS_CHANGE':
899            self.assert_qmp(event, 'data/id', 'drive0')
900            event = self.vm.get_qmp_event(wait=60.0)
901
902        # Failures will manifest as COMPLETED/ERROR.
903        self.assert_qmp(event, 'event', 'BLOCK_JOB_READY')
904        self.complete_and_wait(drive='drive0', wait_ready=False)
905        self.assert_no_active_block_jobs()
906
907class TestRepairQuorum(iotests.QMPTestCase):
908    """ This class test quorum file repair using drive-mirror.
909        It's mostly a fork of TestSingleDrive """
910    image_len = 1 * 1024 * 1024 # MB
911    IMAGES = [ quorum_img1, quorum_img2, quorum_img3 ]
912
913    @iotests.skip_if_unsupported(['quorum'])
914    def setUp(self):
915        self.vm = iotests.VM()
916
917        if iotests.qemu_default_machine == 'pc':
918            self.vm.add_drive(None, 'media=cdrom', 'ide')
919
920        # Add each individual quorum images
921        for i in self.IMAGES:
922            qemu_img('create', '-f', iotests.imgfmt, i,
923                     str(self.image_len))
924            # Assign a node name to each quorum image in order to manipulate
925            # them
926            opts = "node-name=img%i" % self.IMAGES.index(i)
927            opts += ',driver=%s' % iotests.imgfmt
928            opts += ',file.driver=file'
929            opts += ',file.filename=%s' % i
930            self.vm = self.vm.add_blockdev(opts)
931
932        self.vm.launch()
933
934        #assemble the quorum block device from the individual files
935        args = { "driver": "quorum", "node-name": "quorum0",
936                 "vote-threshold": 2, "children": [ "img0", "img1", "img2" ] }
937        result = self.vm.qmp("blockdev-add", **args)
938        self.assert_qmp(result, 'return', {})
939
940
941    def tearDown(self):
942        self.vm.shutdown()
943        for i in self.IMAGES + [ quorum_repair_img, quorum_snapshot_file,
944                                 nbd_sock_path ]:
945            # Do a try/except because the test may have deleted some images
946            try:
947                os.remove(i)
948            except OSError:
949                pass
950
951    def test_complete(self):
952        result = self.vm.qmp('drive-mirror', job_id='job0', device='quorum0',
953                             sync='full', node_name="repair0", replaces="img1",
954                             target=quorum_repair_img, format=iotests.imgfmt)
955        self.assert_qmp(result, 'return', {})
956
957        self.complete_and_wait(drive="job0")
958        self.assert_has_block_node("repair0", quorum_repair_img)
959        self.vm.assert_block_path('quorum0', '/children.1', 'repair0')
960        self.vm.shutdown()
961        self.assertTrue(iotests.compare_images(quorum_img2, quorum_repair_img),
962                        'target image does not match source after mirroring')
963
964    def test_cancel(self):
965        result = self.vm.qmp('drive-mirror', job_id='job0', device='quorum0',
966                             sync='full', node_name="repair0", replaces="img1",
967                             target=quorum_repair_img, format=iotests.imgfmt)
968        self.assert_qmp(result, 'return', {})
969
970        self.cancel_and_wait(drive="job0", force=True)
971        # here we check that the last registered quorum file has not been
972        # swapped out and unref
973        self.assert_has_block_node(None, quorum_img3)
974
975    def test_cancel_after_ready(self):
976        result = self.vm.qmp('drive-mirror', job_id='job0', device='quorum0',
977                             sync='full', node_name="repair0", replaces="img1",
978                             target=quorum_repair_img, format=iotests.imgfmt)
979        self.assert_qmp(result, 'return', {})
980
981        self.wait_ready_and_cancel(drive="job0")
982        # here we check that the last registered quorum file has not been
983        # swapped out and unref
984        self.assert_has_block_node(None, quorum_img3)
985        self.vm.shutdown()
986        self.assertTrue(iotests.compare_images(quorum_img2, quorum_repair_img),
987                        'target image does not match source after mirroring')
988
989    def test_pause(self):
990        result = self.vm.qmp('drive-mirror', job_id='job0', device='quorum0',
991                             sync='full', node_name="repair0", replaces="img1",
992                             target=quorum_repair_img, format=iotests.imgfmt)
993        self.assert_qmp(result, 'return', {})
994
995        self.pause_job('job0')
996
997        result = self.vm.qmp('query-block-jobs')
998        offset = self.dictpath(result, 'return[0]/offset')
999
1000        time.sleep(0.5)
1001        result = self.vm.qmp('query-block-jobs')
1002        self.assert_qmp(result, 'return[0]/offset', offset)
1003
1004        result = self.vm.qmp('block-job-resume', device='job0')
1005        self.assert_qmp(result, 'return', {})
1006
1007        self.complete_and_wait(drive="job0")
1008        self.vm.shutdown()
1009        self.assertTrue(iotests.compare_images(quorum_img2, quorum_repair_img),
1010                        'target image does not match source after mirroring')
1011
1012    def test_medium_not_found(self):
1013        if iotests.qemu_default_machine != 'pc':
1014            return
1015
1016        result = self.vm.qmp('drive-mirror', job_id='job0', device='drive0', # CD-ROM
1017                             sync='full',
1018                             node_name='repair0',
1019                             replaces='img1',
1020                             target=quorum_repair_img, format=iotests.imgfmt)
1021        self.assert_qmp(result, 'error/class', 'GenericError')
1022
1023    def test_image_not_found(self):
1024        result = self.vm.qmp('drive-mirror', job_id='job0', device='quorum0',
1025                             sync='full', node_name='repair0', replaces='img1',
1026                             mode='existing', target=quorum_repair_img,
1027                             format=iotests.imgfmt)
1028        self.assert_qmp(result, 'error/class', 'GenericError')
1029
1030    def test_device_not_found(self):
1031        result = self.vm.qmp('drive-mirror', job_id='job0',
1032                             device='nonexistent', sync='full',
1033                             node_name='repair0',
1034                             replaces='img1',
1035                             target=quorum_repair_img, format=iotests.imgfmt)
1036        self.assert_qmp(result, 'error/class', 'GenericError')
1037
1038    def test_wrong_sync_mode(self):
1039        result = self.vm.qmp('drive-mirror', device='quorum0', job_id='job0',
1040                             node_name='repair0',
1041                             replaces='img1',
1042                             target=quorum_repair_img, format=iotests.imgfmt)
1043        self.assert_qmp(result, 'error/class', 'GenericError')
1044
1045    def test_no_node_name(self):
1046        result = self.vm.qmp('drive-mirror', job_id='job0', device='quorum0',
1047                             sync='full', replaces='img1',
1048                             target=quorum_repair_img, format=iotests.imgfmt)
1049        self.assert_qmp(result, 'error/class', 'GenericError')
1050
1051    def test_nonexistent_replaces(self):
1052        result = self.vm.qmp('drive-mirror', job_id='job0', device='quorum0',
1053                             sync='full', node_name='repair0', replaces='img77',
1054                             target=quorum_repair_img, format=iotests.imgfmt)
1055        self.assert_qmp(result, 'error/class', 'GenericError')
1056
1057    def test_after_a_quorum_snapshot(self):
1058        result = self.vm.qmp('blockdev-snapshot-sync', node_name='img1',
1059                             snapshot_file=quorum_snapshot_file,
1060                             snapshot_node_name="snap1");
1061
1062        result = self.vm.qmp('drive-mirror', job_id='job0', device='quorum0',
1063                             sync='full', node_name='repair0', replaces="img1",
1064                             target=quorum_repair_img, format=iotests.imgfmt)
1065        self.assert_qmp(result, 'error/class', 'GenericError')
1066
1067        result = self.vm.qmp('drive-mirror', job_id='job0', device='quorum0',
1068                             sync='full', node_name='repair0', replaces="snap1",
1069                             target=quorum_repair_img, format=iotests.imgfmt)
1070        self.assert_qmp(result, 'return', {})
1071
1072        self.complete_and_wait('job0')
1073        self.assert_has_block_node("repair0", quorum_repair_img)
1074        self.vm.assert_block_path('quorum0', '/children.1', 'repair0')
1075
1076    def test_with_other_parent(self):
1077        """
1078        Check that we cannot replace a Quorum child when it has other
1079        parents.
1080        """
1081        result = self.vm.qmp('nbd-server-start',
1082                             addr={
1083                                 'type': 'unix',
1084                                 'data': {'path': nbd_sock_path}
1085                             })
1086        self.assert_qmp(result, 'return', {})
1087
1088        result = self.vm.qmp('nbd-server-add', device='img1')
1089        self.assert_qmp(result, 'return', {})
1090
1091        result = self.vm.qmp('drive-mirror', job_id='mirror', device='quorum0',
1092                             sync='full', node_name='repair0', replaces='img1',
1093                             target=quorum_repair_img, format=iotests.imgfmt)
1094        self.assert_qmp(result, 'error/desc',
1095                        "Cannot replace 'img1' by a node mirrored from "
1096                        "'quorum0', because it cannot be guaranteed that doing "
1097                        "so would not lead to an abrupt change of visible data")
1098
1099    def test_with_other_parents_after_mirror_start(self):
1100        """
1101        The same as test_with_other_parent(), but add the NBD server
1102        only when the mirror job is already running.
1103        """
1104        result = self.vm.qmp('nbd-server-start',
1105                             addr={
1106                                 'type': 'unix',
1107                                 'data': {'path': nbd_sock_path}
1108                             })
1109        self.assert_qmp(result, 'return', {})
1110
1111        result = self.vm.qmp('drive-mirror', job_id='mirror', device='quorum0',
1112                             sync='full', node_name='repair0', replaces='img1',
1113                             target=quorum_repair_img, format=iotests.imgfmt)
1114        self.assert_qmp(result, 'return', {})
1115
1116        result = self.vm.qmp('nbd-server-add', device='img1')
1117        self.assert_qmp(result, 'return', {})
1118
1119        # The full error message goes to stderr, we will check it later
1120        self.complete_and_wait('mirror',
1121                               completion_error='Operation not permitted')
1122
1123        # Should not have been replaced
1124        self.vm.assert_block_path('quorum0', '/children.1', 'img1')
1125
1126        # Check the full error message now
1127        self.vm.shutdown()
1128        log = self.vm.get_log()
1129        log = re.sub(r'^\[I \d+\.\d+\] OPENED\n', '', log)
1130        log = re.sub(r'^Formatting.*\n', '', log)
1131        log = re.sub(r'\n\[I \+\d+\.\d+\] CLOSED\n?$', '', log)
1132        log = re.sub(r'^%s: ' % os.path.basename(iotests.qemu_prog), '', log)
1133
1134        self.assertEqual(log,
1135                         "Can no longer replace 'img1' by 'repair0', because " +
1136                         "it can no longer be guaranteed that doing so would " +
1137                         "not lead to an abrupt change of visible data")
1138
1139
1140# Test mirroring with a source that does not have any parents (not even a
1141# BlockBackend)
1142class TestOrphanedSource(iotests.QMPTestCase):
1143    def setUp(self):
1144        blk0 = { 'node-name': 'src',
1145                 'driver': 'null-co' }
1146
1147        blk1 = { 'node-name': 'dest',
1148                 'driver': 'null-co' }
1149
1150        blk2 = { 'node-name': 'dest-ro',
1151                 'driver': 'null-co',
1152                 'read-only': 'on' }
1153
1154        self.vm = iotests.VM()
1155        self.vm.add_blockdev(self.vm.qmp_to_opts(blk0))
1156        self.vm.add_blockdev(self.vm.qmp_to_opts(blk1))
1157        self.vm.add_blockdev(self.vm.qmp_to_opts(blk2))
1158        self.vm.launch()
1159
1160    def tearDown(self):
1161        self.vm.shutdown()
1162
1163    def test_no_job_id(self):
1164        self.assert_no_active_block_jobs()
1165
1166        result = self.vm.qmp('blockdev-mirror', device='src', sync='full',
1167                             target='dest')
1168        self.assert_qmp(result, 'error/class', 'GenericError')
1169
1170    def test_success(self):
1171        self.assert_no_active_block_jobs()
1172
1173        result = self.vm.qmp('blockdev-mirror', job_id='job', device='src',
1174                             sync='full', target='dest')
1175        self.assert_qmp(result, 'return', {})
1176
1177        self.complete_and_wait('job')
1178
1179    def test_failing_permissions(self):
1180        self.assert_no_active_block_jobs()
1181
1182        result = self.vm.qmp('blockdev-mirror', device='src', sync='full',
1183                             target='dest-ro')
1184        self.assert_qmp(result, 'error/class', 'GenericError')
1185
1186    def test_failing_permission_in_complete(self):
1187        self.assert_no_active_block_jobs()
1188
1189        # Unshare consistent-read on the target
1190        # (The mirror job does not care)
1191        result = self.vm.qmp('blockdev-add',
1192                             driver='blkdebug',
1193                             node_name='dest-perm',
1194                             image='dest',
1195                             unshare_child_perms=['consistent-read'])
1196        self.assert_qmp(result, 'return', {})
1197
1198        result = self.vm.qmp('blockdev-mirror', job_id='job', device='src',
1199                             sync='full', target='dest',
1200                             filter_node_name='mirror-filter')
1201        self.assert_qmp(result, 'return', {})
1202
1203        # Require consistent-read on the source
1204        # (We can only add this node once the job has started, or it
1205        # will complain that it does not want to run on non-root nodes)
1206        result = self.vm.qmp('blockdev-add',
1207                             driver='blkdebug',
1208                             node_name='src-perm',
1209                             image='src',
1210                             take_child_perms=['consistent-read'])
1211        self.assert_qmp(result, 'return', {})
1212
1213        # While completing, mirror will attempt to replace src by
1214        # dest, which must fail because src-perm requires
1215        # consistent-read but dest-perm does not share it; thus
1216        # aborting the job when it is supposed to complete
1217        self.complete_and_wait('job',
1218                               completion_error='Operation not permitted')
1219
1220        # Assert that all of our nodes are still there (except for the
1221        # mirror filter, which should be gone despite the failure)
1222        nodes = self.vm.qmp('query-named-block-nodes')['return']
1223        nodes = [node['node-name'] for node in nodes]
1224
1225        for expect in ('src', 'src-perm', 'dest', 'dest-perm'):
1226            self.assertTrue(expect in nodes, '%s disappeared' % expect)
1227        self.assertFalse('mirror-filter' in nodes,
1228                         'Mirror filter node did not disappear')
1229
1230# Test cases for @replaces that do not necessarily involve Quorum
1231class TestReplaces(iotests.QMPTestCase):
1232    # Each of these test cases needs their own block graph, so do not
1233    # create any nodes here
1234    def setUp(self):
1235        self.vm = iotests.VM()
1236        self.vm.launch()
1237
1238    def tearDown(self):
1239        self.vm.shutdown()
1240        for img in (test_img, target_img):
1241            try:
1242                os.remove(img)
1243            except OSError:
1244                pass
1245
1246    @iotests.skip_if_unsupported(['copy-on-read'])
1247    def test_replace_filter(self):
1248        """
1249        Check that we can replace filter nodes.
1250        """
1251        result = self.vm.qmp('blockdev-add', **{
1252                                 'driver': 'copy-on-read',
1253                                 'node-name': 'filter0',
1254                                 'file': {
1255                                     'driver': 'copy-on-read',
1256                                     'node-name': 'filter1',
1257                                     'file': {
1258                                         'driver': 'null-co'
1259                                     }
1260                                 }
1261                             })
1262        self.assert_qmp(result, 'return', {})
1263
1264        result = self.vm.qmp('blockdev-add',
1265                             node_name='target', driver='null-co')
1266        self.assert_qmp(result, 'return', {})
1267
1268        result = self.vm.qmp('blockdev-mirror', job_id='mirror', device='filter0',
1269                             target='target', sync='full', replaces='filter1')
1270        self.assert_qmp(result, 'return', {})
1271
1272        self.complete_and_wait('mirror')
1273
1274        self.vm.assert_block_path('filter0', '/file', 'target')
1275
1276if __name__ == '__main__':
1277    iotests.main(supported_fmts=['qcow2', 'qed'],
1278                 supported_protocols=['file'],
1279                 supported_platforms=['linux', 'freebsd', 'netbsd', 'openbsd'])
1280