File: BmapCopy1_0.py

package info (click to toggle)
bmap-tools 3.9.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 760 kB
  • sloc: python: 5,822; sh: 105; makefile: 2
file content (744 lines) | stat: -rw-r--r-- 29,709 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
# pylint: disable-all

"""This module implements copying of images with bmap and provides the
following API.
  1. BmapCopy class - implements copying to any kind of file, be that a block
     device or a regular file.
  2. BmapBdevCopy class - based on BmapCopy and specializes on copying to block
     devices. It does some more sanity checks and some block device performance
     tuning.

The bmap file is an XML file which contains a list of mapped blocks of the
image. Mapped blocks are the blocks which have disk sectors associated with
them, as opposed to holes, which are blocks with no associated disk sectors. In
other words, the image is considered to be a sparse file, and bmap basically
contains a list of mapped blocks of this sparse file. The bmap additionally
contains some useful information like block size (usually 4KiB), image size,
mapped blocks count, etc.

The bmap is used for copying the image to a block device or to a regular file.
The idea is that we copy quickly with bmap because we copy only mapped blocks
and ignore the holes, because they are useless. And if the image is generated
properly (starting with a huge hole and writing all the data), it usually
contains only little mapped blocks, comparing to the overall image size. And
such an image compresses very well (because holes are read as all zeroes), so
it is beneficial to distributor them as compressed files along with the bmap.

Here is an example. Suppose you have a 4GiB image which contains only 100MiB of
user data and you need to flash it to a slow USB stick. With bmap you end up
copying only a little bit more than 100MiB of data from the image to the USB
stick (namely, you copy only mapped blocks). This is a lot faster than copying
all 4GiB of data. We say that it is a bit more than 100MiB because things like
file-system meta-data (inode tables, superblocks, etc), partition table, etc
also contribute to the mapped blocks and are also copied."""

# Disable the following pylint recommendations:
#   * Too many instance attributes (R0902)
#   * Too many statements (R0915)
#   * Too many branches (R0912)
# pylint: disable=R0902
# pylint: disable=R0915
# pylint: disable=R0912

import os
import stat
import sys
import hashlib
from six import reraise
from six.moves import queue as Queue
from six.moves import _thread as thread
from xml.etree import ElementTree
from bmaptool.BmapHelpers import human_size

# A list of supported image formats
SUPPORTED_IMAGE_FORMATS = ("bz2", "gz", "tar.gz", "tgz", "tar.bz2")

# The highest supported bmap format version
SUPPORTED_BMAP_VERSION = "1.0"


class Error(Exception):
    """A class for exceptions generated by the 'BmapCopy' module. We currently
    support only one type of exceptions, and we basically throw human-readable
    problem description in case of errors."""

    pass


class BmapCopy:
    """This class implements the bmap-based copying functionality. To copy an
    image with bmap you should create an instance of this class, which requires
    the following:

    * full path or a file-like object of the image to copy
    * full path or a file-like object of the destination file copy the image to
    * full path or a file-like object of the bmap file (optional)

    Although the main purpose of this class is to use bmap, the bmap is not
    required, and if it was not provided then the entire image will be copied
    to the destination file.

    The image file may either be an uncompressed raw image or a compressed
    image. Compression type is defined by the image file extension.  Supported
    types are listed by 'SUPPORTED_IMAGE_FORMATS'.

    IMPORTANT: if the image is given as a file-like object, the compression
    type recognition is not performed - the file-like object's 'read()' method
    is used directly instead.

    Once an instance of 'BmapCopy' is created, all the 'bmap_*' attributes are
    initialized and available. They are read from the bmap.

    However, if bmap was not provided, this is not always the case and some of
    the 'bmap_*' attributes are not initialize by the class constructor.
    Instead, they are initialized only in the 'copy()' method. The reason for
    this is that when bmap is absent, 'BmapCopy' uses sensible fall-back values
    for the 'bmap_*' attributes assuming the entire image is "mapped". And if
    the image is compressed, it cannot easily find out the image size. Thus,
    this is postponed until the 'copy()' method decompresses the image for the
    first time.

    The 'copy()' method implements the copying. You may choose whether to
    verify the SHA1 checksum while copying or not.  Note, this is done only in
    case of bmap-based copying and only if bmap contains the SHA1 checksums
    (e.g., bmap version 1.0 did not have SHA1 checksums).

    You may choose whether to synchronize the destination file after writing or
    not. To explicitly synchronize it, use the 'sync()' method.

    This class supports all the bmap format versions up version
    'SUPPORTED_BMAP_VERSION'."""

    def _initialize_sizes(self, image_size):
        """This function is only used when the there is no bmap. It
        initializes attributes like 'blocks_cnt', 'mapped_cnt', etc. Normally,
        the values are read from the bmap file, but in this case they are just
        set to something reasonable."""

        self.image_size = image_size
        self.image_size_human = human_size(image_size)
        self.blocks_cnt = self.image_size + self.block_size - 1
        self.blocks_cnt /= self.block_size
        self.mapped_cnt = self.blocks_cnt
        self.mapped_size = self.image_size
        self.mapped_size_human = self.image_size_human

    def _parse_bmap(self):
        """Parse the bmap file and initialize the 'bmap_*' attributes."""

        bmap_pos = self._f_bmap.tell()
        self._f_bmap.seek(0)

        try:
            self._xml = ElementTree.parse(self._f_bmap)
        except ElementTree.ParseError as err:
            raise Error(
                "cannot parse the bmap file '%s' which should be a "
                "proper XML file: %s" % (self._bmap_path, err)
            )

        xml = self._xml
        self.bmap_version = str(xml.getroot().attrib.get("version"))

        # Make sure we support this version
        major = int(self.bmap_version.split(".", 1)[0])
        if major > SUPPORTED_BMAP_VERSION:
            raise Error(
                "only bmap format version up to %d is supported, "
                "version %d is not supported" % (SUPPORTED_BMAP_VERSION, major)
            )

        # Fetch interesting data from the bmap XML file
        self.block_size = int(xml.find("BlockSize").text.strip())
        self.blocks_cnt = int(xml.find("BlocksCount").text.strip())
        self.mapped_cnt = int(xml.find("MappedBlocksCount").text.strip())
        self.image_size = int(xml.find("ImageSize").text.strip())
        self.image_size_human = human_size(self.image_size)
        self.mapped_size = self.mapped_cnt * self.block_size
        self.mapped_size_human = human_size(self.mapped_size)
        self.mapped_percent = (self.mapped_cnt * 100.0) / self.blocks_cnt

        blocks_cnt = (self.image_size + self.block_size - 1) / self.block_size
        if self.blocks_cnt != blocks_cnt:
            raise Error(
                "Inconsistent bmap - image size does not match "
                "blocks count (%d bytes != %d blocks * %d bytes)"
                % (self.image_size, self.blocks_cnt, self.block_size)
            )

        self._f_bmap.seek(bmap_pos)

    def _open_image_file(self):
        """Open the image file which may be compressed or not. The compression
        type is recognized by the file extension. Supported types are defined
        by 'SUPPORTED_IMAGE_FORMATS'."""

        try:
            is_regular_file = stat.S_ISREG(os.stat(self._image_path).st_mode)
        except OSError as err:
            raise Error(
                "cannot access image file '%s': %s" % (self._image_path, err.strerror)
            )

        if not is_regular_file:
            raise Error("image file '%s' is not a regular file" % self._image_path)

        try:
            if (
                self._image_path.endswith(".tar.gz")
                or self._image_path.endswith(".tar.bz2")
                or self._image_path.endswith(".tgz")
            ):
                import tarfile

                tar = tarfile.open(self._image_path, "r")
                # The tarball is supposed to contain only one single member
                members = tar.getnames()
                if len(members) > 1:
                    raise Error(
                        "the image tarball '%s' contains more than "
                        "one file" % self._image_path
                    )
                elif len(members) == 0:
                    raise Error(
                        "the image tarball '%s' is empty (no files)" % self._image_path
                    )
                self._f_image = tar.extractfile(members[0])
            elif self._image_path.endswith(".gz"):
                import gzip

                self._f_image = gzip.GzipFile(self._image_path, "rb")
            elif self._image_path.endswith(".bz2"):
                import bz2

                self._f_image = bz2.BZ2File(self._image_path, "rb")
            else:
                self._image_is_compressed = False
                self._f_image = open(self._image_path, "rb")
        except IOError as err:
            raise Error("cannot open image file '%s': %s" % (self._image_path, err))

        self._f_image_needs_close = True

    def _validate_image_size(self):
        """Make sure that image size from bmap matches real image size."""

        image_size = os.fstat(self._f_image.fileno()).st_size
        if image_size != self.image_size:
            raise Error(
                "Size mismatch, bmap '%s' was created for an image "
                "of size %d bytes, but image '%s' has size %d bytes"
                % (self._bmap_path, self.image_size, self._image_path, image_size)
            )

    def _open_destination_file(self):
        """Open the destination file."""

        try:
            self._f_dest = open(self._dest_path, "w")
        except IOError as err:
            raise Error(
                "cannot open destination file '%s': %s" % (self._dest_path, err)
            )

        self._f_dest_needs_close = True

    def _open_bmap_file(self):
        """Open the bmap file."""

        try:
            self._f_bmap = open(self._bmap_path, "r")
        except IOError as err:
            raise Error(
                "cannot open bmap file '%s': %s" % (self._bmap_path, err.strerror)
            )

        self._f_bmap_needs_close = True

    def __init__(self, image, dest, bmap=None):
        """The class constructor. The parameters are:
        image - full path or file object of the image which should be copied
        dest  - full path or file-like object of the destination file to
                copy the image to
        bmap  - full path or file-like object of the bmap file to use for
                copying"""

        self._xml = None
        self._image_is_compressed = True

        self._dest_fsync_watermark = None
        self._batch_blocks = None
        self._batch_queue = None
        self._batch_bytes = 1024 * 1024
        self._batch_queue_len = 2

        self.bmap_version = None
        self.block_size = None
        self.blocks_cnt = None
        self.mapped_cnt = None
        self.image_size = None
        self.image_size_human = None
        self.mapped_size = None
        self.mapped_size_human = None
        self.mapped_percent = None

        self._f_dest_needs_close = False
        self._f_image_needs_close = False
        self._f_bmap_needs_close = False

        self._f_bmap = None
        self._f_bmap_path = None

        if hasattr(dest, "write"):
            self._f_dest = dest
            self._dest_path = dest.name
        else:
            self._dest_path = dest
            self._open_destination_file()

        if hasattr(image, "read"):
            self._f_image = image
            self._image_path = image.name
        else:
            self._image_path = image
            self._open_image_file()

        st_mode = os.fstat(self._f_dest.fileno()).st_mode
        self._dest_is_regfile = stat.S_ISREG(st_mode)

        if bmap:
            if hasattr(bmap, "read"):
                self._f_bmap = bmap
                self._bmap_path = bmap.name
            else:
                self._bmap_path = bmap
                self._open_bmap_file()
            self._parse_bmap()
        else:
            # There is no bmap. Initialize user-visible attributes to something
            # sensible with an assumption that we just have all blocks mapped.
            self.bmap_version = 0
            self.block_size = 4096
            self.mapped_percent = 100

            # We can initialize size-related attributes only if we the image is
            # uncompressed.
            if not self._image_is_compressed:
                image_size = os.fstat(self._f_image.fileno()).st_size
                self._initialize_sizes(image_size)

        if not self._image_is_compressed:
            self._validate_image_size()

        self._batch_blocks = self._batch_bytes / self.block_size

    def __del__(self):
        """The class destructor which closes the opened files."""

        if self._f_image_needs_close:
            self._f_image.close()
        if self._f_dest_needs_close:
            self._f_dest.close()
        if self._f_bmap_needs_close:
            self._f_bmap.close()

    def _get_block_ranges(self):
        """This is a helper generator that parses the bmap XML file and for
        each block range in the XML file it yields ('first', 'last', 'sha1')
        tuples, where:
          * 'first' is the first block of the range;
          * 'last' is the last block of the range;
          * 'sha1' is the SHA1 checksum of the range ('None' is used if it is
            missing.

        If there is no bmap file, the generator just yields a single range
        for entire image file. If the image size is unknown (the image is
        compressed), the generator infinitely yields continuous ranges of
        size '_batch_blocks'."""

        if not self._f_bmap:
            # We do not have the bmap, yield a tuple with all blocks
            if self.blocks_cnt:
                yield (0, self.blocks_cnt - 1, None)
            else:
                # We do not know image size, keep yielding tuples with many
                # blocks infinitely.
                first = 0
                while True:
                    yield (first, first + self._batch_blocks - 1, None)
                    first += self._batch_blocks
            return

        # We have the bmap, just read it and yield block ranges
        xml = self._xml
        xml_bmap = xml.find("BlockMap")

        for xml_element in xml_bmap.findall("Range"):
            blocks_range = xml_element.text.strip()
            # The range of blocks has the "X - Y" format, or it can be just "X"
            # in old bmap format versions. First, split the blocks range string
            # and strip white-spaces.
            split = [x.strip() for x in blocks_range.split("-", 1)]

            first = int(split[0])
            if len(split) > 1:
                last = int(split[1])
                if first > last:
                    raise Error("bad range (first > last): '%s'" % blocks_range)
            else:
                last = first

            if "sha1" in xml_element.attrib:
                sha1 = xml_element.attrib["sha1"]
            else:
                sha1 = None

            yield (first, last, sha1)

    def _get_batches(self, first, last):
        """This is a helper generator which splits block ranges from the bmap
        file to smaller batches. Indeed, we cannot read and write entire block
        ranges from the image file, because a range can be very large. So we
        perform the I/O in batches. Batch size is defined by the
        '_batch_blocks' attribute. Thus, for each (first, last) block range,
        the generator yields smaller (start, end, length) batch ranges, where:
          * 'start' is the starting batch block number;
          * 'last' is the ending batch block number;
          * 'length' is the batch length in blocks (same as
             'end' - 'start' + 1)."""

        batch_blocks = self._batch_blocks

        while first + batch_blocks - 1 <= last:
            yield (first, first + batch_blocks - 1, batch_blocks)
            first += batch_blocks

        batch_blocks = last - first + 1
        if batch_blocks:
            yield (first, first + batch_blocks - 1, batch_blocks)

    def _get_data(self, verify):
        """This is generator  which reads the image file in '_batch_blocks'
        chunks and yields ('type', 'start', 'end',  'buf) tuples, where:
          * 'start' is the starting block number of the batch;
          * 'end' is the last block of the batch;
          * 'buf' a buffer containing the batch data."""

        try:
            for first, last, sha1 in self._get_block_ranges():
                if verify and sha1:
                    hash_obj = hashlib.new("sha1")

                self._f_image.seek(first * self.block_size)

                iterator = self._get_batches(first, last)
                for start, end, length in iterator:
                    try:
                        buf = self._f_image.read(length * self.block_size)
                    except IOError as err:
                        raise Error(
                            "error while reading blocks %d-%d of the "
                            "image file '%s': %s" % (start, end, self._image_path, err)
                        )

                    if not buf:
                        self._batch_queue.put(None)
                        return

                    if verify and sha1:
                        hash_obj.update(buf)

                    blocks = (len(buf) + self.block_size - 1) / self.block_size
                    self._batch_queue.put(("range", start, start + blocks - 1, buf))

                if verify and sha1 and hash_obj.hexdigest() != sha1:
                    raise Error(
                        "checksum mismatch for blocks range %d-%d: "
                        "calculated %s, should be %s"
                        % (first, last, hash_obj.hexdigest(), sha1)
                    )
        # Silence pylint warning about catching too general exception
        # pylint: disable=W0703
        except Exception:
            # pylint: enable=W0703
            # In case of any exception - just pass it to the main thread
            # through the queue.
            reraise(exc_info[0], exc_info[1], exc_info[2])

        self._batch_queue.put(None)

    def copy(self, sync=True, verify=True):
        """Copy the image to the destination file using bmap. The sync
        argument defines whether the destination file has to be synchronized
        upon return.  The 'verify' argument defines whether the SHA1 checksum
        has to be verified while copying."""

        # Save file positions in order to restore them at the end
        image_pos = self._f_image.tell()
        dest_pos = self._f_dest.tell()
        if self._f_bmap:
            bmap_pos = self._f_bmap.tell()

        # Create the queue for block batches and start the reader thread, which
        # will read the image in batches and put the results to '_batch_queue'.
        self._batch_queue = Queue.Queue(self._batch_queue_len)
        thread.start_new_thread(self._get_data, (verify,))

        blocks_written = 0
        bytes_written = 0
        fsync_last = 0

        # Read the image in '_batch_blocks' chunks and write them to the
        # destination file
        while True:
            batch = self._batch_queue.get()
            if batch is None:
                # No more data, the image is written
                break
            elif batch[0] == "error":
                # The reader thread encountered an error and passed us the
                # exception.
                exc_info = batch[1]
                raise exc_info[1].with_traceback(exc_info[2])

            (start, end, buf) = batch[1:4]

            assert len(buf) <= (end - start + 1) * self.block_size
            assert len(buf) > (end - start) * self.block_size

            self._f_dest.seek(start * self.block_size)

            # Synchronize the destination file if we reached the watermark
            if self._dest_fsync_watermark:
                if blocks_written >= fsync_last + self._dest_fsync_watermark:
                    fsync_last = blocks_written
                    self.sync()

            try:
                self._f_dest.write(buf)
            except IOError as err:
                raise Error(
                    "error while writing blocks %d-%d of '%s': %s"
                    % (start, end, self._dest_path, err)
                )

            self._batch_queue.task_done()
            blocks_written += end - start + 1
            bytes_written += len(buf)

        if not self.image_size:
            # The image size was unknown up until now, probably because this is
            # a compressed image. Initialize the corresponding class attributes
            # now, when we know the size.
            self._initialize_sizes(bytes_written)

        # This is just a sanity check - we should have written exactly
        # 'mapped_cnt' blocks.
        if blocks_written != self.mapped_cnt:
            raise Error(
                "wrote %u blocks, but should have %u - inconsistent "
                "bmap file" % (blocks_written, self.mapped_cnt)
            )

        if self._dest_is_regfile:
            # Make sure the destination file has the same size as the image
            try:
                os.ftruncate(self._f_dest.fileno(), self.image_size)
            except OSError as err:
                raise Error("cannot truncate file '%s': %s" % (self._dest_path, err))

        try:
            self._f_dest.flush()
        except IOError as err:
            raise Error("cannot flush '%s': %s" % (self._dest_path, err))

        if sync:
            self.sync()

        # Restore file positions
        self._f_image.seek(image_pos)
        self._f_dest.seek(dest_pos)
        if self._f_bmap:
            self._f_bmap.seek(bmap_pos)

    def sync(self):
        """Synchronize the destination file to make sure all the data are
        actually written to the disk."""

        try:
            os.fsync(self._f_dest.fileno()),
        except OSError as err:
            raise Error(
                "cannot synchronize '%s': %s " % (self._dest_path, err.strerror)
            )


class BmapBdevCopy(BmapCopy):
    """This class is a specialized version of 'BmapCopy' which copies the
    image to a block device. Unlike the base 'BmapCopy' class, this class does
    various optimizations specific to block devices, e.g., switching to the
    'noop' I/O scheduler."""

    def _open_destination_file(self):
        """Open the block device in exclusive mode."""

        try:
            self._f_dest = os.open(self._dest_path, os.O_WRONLY | os.O_EXCL)
        except OSError as err:
            raise Error(
                "cannot open block device '%s' in exclusive mode: %s"
                % (self._dest_path, err.strerror)
            )

        try:
            os.fstat(self._f_dest).st_mode
        except OSError as err:
            raise Error(
                "cannot access block device '%s': %s" % (self._dest_path, err.strerror)
            )

        # Turn the block device file descriptor into a file object
        try:
            self._f_dest = os.fdopen(self._f_dest, "wb")
        except OSError as err:
            os.close(self._f_dest)
            raise Error("cannot open block device '%s': %s" % (self._dest_path, err))

        self._f_dest_needs_close = True

    def _tune_block_device(self):
        """ " Tune the block device for better performance:
        1. Switch to the 'noop' I/O scheduler if it is available - sequential
           write to the block device becomes a lot faster comparing to CFQ.
        2. Limit the write buffering - we do not need the kernel to buffer a
           lot of the data we send to the block device, because we write
           sequentially. Limit the buffering.

        The old settings are saved in order to be able to restore them later.
        """
        # Switch to the 'noop' I/O scheduler
        try:
            with open(self._sysfs_scheduler_path, "r+") as f_scheduler:
                contents = f_scheduler.read()
                f_scheduler.seek(0)
                f_scheduler.write("noop")
        except IOError:
            # No problem, this is just an optimization.
            return

        # The file contains a list of scheduler with the current
        # scheduler in square brackets, e.g., "noop deadline [cfq]".
        # Fetch the current scheduler name
        import re

        match = re.match(r".*\[(.+)\].*", contents)
        self._old_scheduler_value = match.group(1)

        # Limit the write buffering
        try:
            with open(self._sysfs_max_ratio_path, "r+") as f_ratio:
                self._old_max_ratio_value = f_ratio.read()
                f_ratio.seek(0)
                f_ratio.write("1")
        except IOError:
            return

    def _restore_bdev_settings(self):
        """Restore old block device settings which we changed in
        '_tune_block_device()'."""

        if self._old_scheduler_value is not None:
            try:
                with open(self._sysfs_scheduler_path, "w") as f_scheduler:
                    f_scheduler.write(self._old_scheduler_value)
            except IOError:
                # No problem, this is just an optimization.
                return

        if self._old_max_ratio_value is not None:
            try:
                with open(self._sysfs_max_ratio_path, "w") as f_ratio:
                    f_ratio.write(self._old_max_ratio_value)
            except IOError:
                return

    def copy(self, sync=True, verify=True):
        """The same as in the base class but tunes the block device for better
        performance before starting writing. Additionally, it forces block
        device synchronization from time to time in order to make sure we do
        not get stuck in 'fsync()' for too long time. The problem is that the
        kernel synchronizes block devices when the file is closed. And the
        result is that if the user interrupts us while we are copying the data,
        the program will be blocked in 'close()' waiting for the block device
        synchronization, which may last minutes for slow USB stick. This is
        very bad user experience, and we work around this effect by
        synchronizing from time to time."""

        try:
            self._tune_block_device()
            BmapCopy.copy(self, sync, verify)
        except:
            self._restore_bdev_settings()
            raise

    def __init__(self, image, dest, bmap=None):
        """The same as the constructor of the 'BmapCopy' base class, but adds
        useful guard-checks specific to block devices."""

        # Call the base class constructor first
        BmapCopy.__init__(self, image, dest, bmap)

        self._batch_bytes = 1024 * 1024
        self._batch_blocks = self._batch_bytes / self.block_size
        self._batch_queue_len = 6
        self._dest_fsync_watermark = (6 * 1024 * 1024) / self.block_size

        self._sysfs_base = None
        self._sysfs_scheduler_path = None
        self._sysfs_max_ratio_path = None
        self._old_scheduler_value = None
        self._old_max_ratio_value = None

        # If the image size is known (i.e., it is not compressed) - check that
        # it fits the block device.
        if self.image_size:
            try:
                bdev_size = os.lseek(self._f_dest.fileno(), 0, os.SEEK_END)
                os.lseek(self._f_dest.fileno(), 0, os.SEEK_SET)
            except OSError as err:
                raise Error(
                    "cannot seed block device '%s': %s "
                    % (self._dest_path, err.strerror)
                )

            if bdev_size < self.image_size:
                raise Error(
                    "the image file '%s' has size %s and it will not "
                    "fit the block device '%s' which has %s capacity"
                    % (
                        self._image_path,
                        self.image_size_human,
                        self._dest_path,
                        human_size(bdev_size),
                    )
                )

        # Construct the path to the sysfs directory of our block device
        st_rdev = os.fstat(self._f_dest.fileno()).st_rdev
        self._sysfs_base = "/sys/dev/block/%s:%s/" % (
            os.major(st_rdev),
            os.minor(st_rdev),
        )

        # Check if the 'queue' sub-directory exists. If yes, then our block
        # device is entire disk. Otherwise, it is a partition, in which case we
        # need to go one level up in the sysfs hierarchy.
        try:
            if not os.path.exists(self._sysfs_base + "queue"):
                self._sysfs_base = self._sysfs_base + "../"
        except OSError:
            # No problem, this is just an optimization.
            pass

        self._sysfs_scheduler_path = self._sysfs_base + "queue/scheduler"
        self._sysfs_max_ratio_path = self._sysfs_base + "bdi/max_ratio"