Skip to contentSkip to conversation

iotests: Dump QCOW2 dirty bitmaps metadata

PATCH Superseded Andrey Shinkevich 2 participants 10 messages Jun 11, 2020 Block layer

v6 of 13 Superseded Latest is v13 →

lore
Share & tools
lore
#0 lore raw

v6 cover iotests: Dump QCOW2 dirty bitmaps metadata

Note: based on the Vladimir's series
[v5 00/13] iotests: Dump QCOW2 dirty bitmaps metadata

Add dirty bitmap information to QCOW2 metadata dump in the qcow2_format.py.

v6:
01: Fixing capitalization of header extension constant.
(Suggested by Eric)
02: The cluster size global variable discarded and passed as a parameter. 03: Re-based to Vladimir's v5 series.
04: The code of passing qcow2.py JSON format key moved to separate patch. 05: Making dict(s) for dumping in JSON format was substituted with a copy

      of __dict__.

v5: The Vladimir's preliminary series
v4: The Vladimir's preliminary series

Andrey Shinkevich (8):
qcow2: Fix capitalization of header extension constant. qcow2_format.py: make printable data an extension class member qcow2_format.py: Dump bitmap directory info qcow2_format.py: pass cluster size to substructures qcow2_format.py: Dump bitmap table serialized entries qcow2.py: Introduce '-j' key to dump in JSON format qcow2_format.py: collect fields to dump in JSON format
qcow2_format.py: support dumping metadata in JSON format

 block/qcow2.c                      |   2 +-
 docs/interop/qcow2.txt             |   2 +-
 tests/qemu-iotests/qcow2.py        |  20 +++-
 tests/qemu-iotests/qcow2_format.py | 219 ++++++++++++++++++++++++++++++++++---
 4 files changed, 222 insertions(+), 21 deletions(-)
Signature · 1 line
1.8.3.1
#1 lore raw

PATCH v6 1/8 qcow2: Fix capitalization of header extension constant.

Make the capitalization of the hexadecimal numbers consistent for the QCOW2 header extension constants in docs/interop/qcow2.txt.

---
 block/qcow2.c          | 2 +-
 docs/interop/qcow2.txt | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)
block/qcow2.c +1 -1
index 0cd2e67..80dfe5f 100644
@@ -66,7 +66,7 @@ typedef struct {
 } QEMU_PACKED QCowExtension;
 
 #define  QCOW2_EXT_MAGIC_END 0
-#define  QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
+#define  QCOW2_EXT_MAGIC_BACKING_FORMAT 0xe2792aca
 #define  QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
 #define  QCOW2_EXT_MAGIC_CRYPTO_HEADER 0x0537be77
 #define  QCOW2_EXT_MAGIC_BITMAPS 0x23852875
docs/interop/qcow2.txt +1 -1
index cb72346..f072e27 100644
@@ -231,7 +231,7 @@ be stored. Each extension has a structure like the following:
 
     Byte  0 -  3:   Header extension type:
                         0x00000000 - End of the header extension area
-                        0xE2792ACA - Backing file format name string
+                        0xe2792aca - Backing file format name string
                         0x6803f857 - Feature name table
                         0x23852875 - Bitmaps extension
                         0x0537be77 - Full disk encryption header pointer
Signature · 1 line
1.8.3.1
Reviewed-by on v6 1/8
#2 lore raw

Re: [PATCH v6 1/8] qcow2: Fix capitalization of header extension constant.

Quoted 10 lines · Andrey Shinkevich

Make the capitalization of the hexadecimal numbers consistent for the QCOW2 header extension constants in docs/interop/qcow2.txt.

---
  block/qcow2.c          | 2 +-
  docs/interop/qcow2.txt | 2 +-
  2 files changed, 2 insertions(+), 2 deletions(-)

tests/qemu-iotests/114 has an instance that could be adjusted as well (no change to 114.out).

With that added,

Signature · 3 lines
Eric Blake, Principal Software Engineer
Red Hat, Inc.           +1-919-301-3226
Virtualization:  qemu.org | libvirt.org
#3 lore raw

PATCH v6 2/8 qcow2_format.py: make printable data an extension class member

In reply to Andrey Shinkevich

Let us differ binary data type from string one for the extension data variable and keep the string as the QcowHeaderExtension class member.

---
 tests/qemu-iotests/qcow2_format.py | 14 ++++++++------
 1 file changed, 8 insertions(+), 6 deletions(-)
tests/qemu-iotests/qcow2_format.py +8 -6
index 0f65fd1..d4f0000 100644
@@ -164,6 +164,13 @@ class QcowHeaderExtension(Qcow2Struct):
             self.data = fd.read(padded)
             assert self.data is not None
 
+        data_str = self.data[:self.length]
+        if all(c in string.printable.encode('ascii') for c in data_str):
+            data_str = f"'{ data_str.decode('ascii') }'"
+        else:
+            data_str = '<binary>'
+        self.data_str = data_str
+
         if self.magic == QCOW2_EXT_MAGIC_BITMAPS:
             self.obj = Qcow2BitmapExt(data=self.data)
         else:
@@ -173,12 +180,7 @@ class QcowHeaderExtension(Qcow2Struct):
         super().dump()
 
         if self.obj is None:
-            data = self.data[:self.length]
-            if all(c in string.printable.encode('ascii') for c in data):
-                data = f"'{ data.decode('ascii') }'"
-            else:
-                data = '<binary>'
-            print(f'{"data":<25} {data}')
+            print(f'{"data":<25} {self.data_str}')
         else:
             self.obj.dump()
 
Signature · 1 line
1.8.3.1
#4 lore raw

PATCH v6 3/8 qcow2_format.py: Dump bitmap directory info

In reply to Andrey Shinkevich

Read and dump entries from the bitmap directory of QCOW2 image with the script qcow2.py.

Header extension:
magic 0x23852875 (Bitmaps)
...

Bitmap name               bitmap-1
flag                      auto
table size                8 (bytes)
bitmap_table_offset       0x90000
bitmap_table_size         1
flags                     0
type                      1
granularity_bits          16
name_size                 8
extra_data_size           0
---
 tests/qemu-iotests/qcow2_format.py | 75 ++++++++++++++++++++++++++++++++++++++
 1 file changed, 75 insertions(+)
tests/qemu-iotests/qcow2_format.py +75 -0
index d4f0000..a7868a7 100644
@@ -103,6 +103,10 @@ class Qcow2Struct(metaclass=Qcow2StructMeta):
             print('{:<25} {}'.format(f[2], value_str))
 
 
+# seek relative to the current position in the file
+FROM_CURRENT = 1
+
+
 class Qcow2BitmapExt(Qcow2Struct):
 
     fields = (
@@ -112,6 +116,73 @@ class Qcow2BitmapExt(Qcow2Struct):
         ('u64', '{:#x}', 'bitmap_directory_offset')
     )
 
+    def read_bitmap_directory(self, fd):
+        self.bitmaps = []
+        fd.seek(self.bitmap_directory_offset)
+        buf_size = struct.calcsize(Qcow2BitmapDirEntry.fmt)
+
+        for n in range(self.nb_bitmaps):
+            buf = fd.read(buf_size)
+            dir_entry = Qcow2BitmapDirEntry(data=buf)
+            fd.seek(dir_entry.extra_data_size, FROM_CURRENT)
+            bitmap_name = fd.read(dir_entry.name_size)
+            dir_entry.name = bitmap_name.decode('ascii')
+            self.bitmaps.append(dir_entry)
+            entry_raw_size = dir_entry.bitmap_dir_entry_raw_size()
+            shift = ((entry_raw_size + 7) & ~7) - entry_raw_size
+            fd.seek(shift, FROM_CURRENT)
+
+    def load(self, fd):
+        self.read_bitmap_directory(fd)
+
+    def dump(self):
+        super().dump()
+        for bm in self.bitmaps:
+            bm.dump_bitmap_dir_entry()
+
+
+BME_FLAG_IN_USE = 1 << 0
+BME_FLAG_AUTO = 1 << 1
+
+
+class Qcow2BitmapDirEntry(Qcow2Struct):
+
+    name = ''
+
+    fields = (
+        ('u64', '{:#x}', 'bitmap_table_offset'),
+        ('u32', '{}',    'bitmap_table_size'),
+        ('u32', '{}',    'flags'),
+        ('u8',  '{}',    'type'),
+        ('u8',  '{}',    'granularity_bits'),
+        ('u16', '{}',    'name_size'),
+        ('u32', '{}',    'extra_data_size')
+    )
+
+    def __init__(self, data):
+        super().__init__(data=data)
+
+        self.bitmap_table_bytes = self.bitmap_table_size \
+            * struct.calcsize('Q')
+
+        self.bitmap_flags = []
+        if (self.flags & BME_FLAG_IN_USE):
+            self.bitmap_flags.append("in-use")
+        if (self.flags & BME_FLAG_AUTO):
+            self.bitmap_flags.append("auto")
+
+    def bitmap_dir_entry_raw_size(self):
+        return struct.calcsize(self.fmt) + self.name_size + \
+            self.extra_data_size
+
+    def dump_bitmap_dir_entry(self):
+        print()
+        print(f'{"Bitmap name":<25} {self.name}')
+        for fl in self.bitmap_flags:
+            print(f'{"flag":<25} {fl}')
+        print(f'{"table size ":<25} {self.bitmap_table_bytes} {"(bytes)"}')
+        super().dump()
+
 
 QCOW2_EXT_MAGIC_BITMAPS = 0x23852875
 
@@ -253,6 +324,10 @@ class QcowHeader(Qcow2Struct):
             else:
                 self.extensions.append(ext)
 
+        for ext in self.extensions:
+            if ext.obj is not None:
+                ext.obj.load(fd)
+
     def update_extensions(self, fd):
 
         fd.seek(self.header_length)
Signature · 1 line
1.8.3.1
#5 lore raw

PATCH v6 4/8 qcow2_format.py: pass cluster size to substructures

In reply to Andrey Shinkevich

The cluster size of an image is the QcowHeader class member and may be obtained by dependent extension structures such as Qcow2BitmapExt for further bitmap table details print.

---
 tests/qemu-iotests/qcow2_format.py | 19 ++++++++++++++-----
 1 file changed, 14 insertions(+), 5 deletions(-)
tests/qemu-iotests/qcow2_format.py +14 -5
index a7868a7..6589f68 100644
@@ -116,6 +116,10 @@ class Qcow2BitmapExt(Qcow2Struct):
         ('u64', '{:#x}', 'bitmap_directory_offset')
     )
 
+    def __init__(self, data, cluster_size):
+        super().__init__(data=data)
+        self.cluster_size = cluster_size
+
     def read_bitmap_directory(self, fd):
         self.bitmaps = []
         fd.seek(self.bitmap_directory_offset)
@@ -123,7 +127,8 @@ class Qcow2BitmapExt(Qcow2Struct):
 
         for n in range(self.nb_bitmaps):
             buf = fd.read(buf_size)
-            dir_entry = Qcow2BitmapDirEntry(data=buf)
+            dir_entry = Qcow2BitmapDirEntry(data=buf,
+                                            cluster_size=self.cluster_size)
             fd.seek(dir_entry.extra_data_size, FROM_CURRENT)
             bitmap_name = fd.read(dir_entry.name_size)
             dir_entry.name = bitmap_name.decode('ascii')
@@ -159,8 +164,9 @@ class Qcow2BitmapDirEntry(Qcow2Struct):
         ('u32', '{}',    'extra_data_size')
     )
 
-    def __init__(self, data):
+    def __init__(self, data, cluster_size):
         super().__init__(data=data)
+        self.cluster_size = cluster_size
 
         self.bitmap_table_bytes = self.bitmap_table_size \
             * struct.calcsize('Q')
@@ -205,11 +211,13 @@ class QcowHeaderExtension(Qcow2Struct):
         # then padding to next multiply of 8
     )
 
-    def __init__(self, magic=None, length=None, data=None, fd=None):
+    def __init__(self, magic=None, length=None, data=None, fd=None,
+                 cluster_size=None):
         """
         Support both loading from fd and creation from user data.
         For fd-based creation current position in a file will be used to read
         the data.
+        The cluster_size value may be obtained by dependent structures.
 
         This should be somehow refactored and functionality should be moved to
         superclass (to allow creation of any qcow2 struct), but then, fields
@@ -243,7 +251,8 @@ class QcowHeaderExtension(Qcow2Struct):
         self.data_str = data_str
 
         if self.magic == QCOW2_EXT_MAGIC_BITMAPS:
-            self.obj = Qcow2BitmapExt(data=self.data)
+            self.obj = Qcow2BitmapExt(data=self.data,
+                                      cluster_size=cluster_size)
         else:
             self.obj = None
 
@@ -318,7 +327,7 @@ class QcowHeader(Qcow2Struct):
             end = self.cluster_size
 
         while fd.tell() < end:
-            ext = QcowHeaderExtension(fd=fd)
+            ext = QcowHeaderExtension(fd=fd, cluster_size=self.cluster_size)
             if ext.magic == 0:
                 break
             else:
Signature · 1 line
1.8.3.1
#6 lore raw

PATCH v6 5/8 qcow2_format.py: Dump bitmap table serialized entries

In reply to Andrey Shinkevich

Add bitmap table information to the QCOW2 metadata dump.

Bitmap name bitmap-1
...

Bitmap table    type            offset          size
        0       serialized      0xa0000         65536
        1       all-zeroes      0x0             65536
        2       all-zeroes      0x0             65536
        3       all-zeroes      0x0             65536
        4       all-zeroes      0x0             65536
        5       all-zeroes      0x0             65536
        6       all-zeroes      0x0             65536
        7       all-zeroes      0x0             65536
---
 tests/qemu-iotests/qcow2_format.py | 42 ++++++++++++++++++++++++++++++++++++++
 1 file changed, 42 insertions(+)
tests/qemu-iotests/qcow2_format.py +42 -0
index 6589f68..2e7c058 100644
@@ -137,6 +137,9 @@ class Qcow2BitmapExt(Qcow2Struct):
             shift = ((entry_raw_size + 7) & ~7) - entry_raw_size
             fd.seek(shift, FROM_CURRENT)
 
+        for bm in self.bitmaps:
+            bm.read_bitmap_table(fd)
+
     def load(self, fd):
         self.read_bitmap_directory(fd)
 
@@ -181,6 +184,12 @@ class Qcow2BitmapDirEntry(Qcow2Struct):
         return struct.calcsize(self.fmt) + self.name_size + \
             self.extra_data_size
 
+    def read_bitmap_table(self, fd):
+        fd.seek(self.bitmap_table_offset)
+        table_size = self.bitmap_table_bytes * struct.calcsize('Q')
+        table = [e[0] for e in struct.iter_unpack('>Q', fd.read(table_size))]
+        self.bitmap_table = Qcow2BitmapTable(table)
+
     def dump_bitmap_dir_entry(self):
         print()
         print(f'{"Bitmap name":<25} {self.name}')
@@ -188,6 +197,39 @@ class Qcow2BitmapDirEntry(Qcow2Struct):
             print(f'{"flag":<25} {fl}')
         print(f'{"table size ":<25} {self.bitmap_table_bytes} {"(bytes)"}')
         super().dump()
+        self.bitmap_table.print_bitmap_table(self.cluster_size)
+
+
+class Qcow2BitmapTableEntry:
+
+    BME_TABLE_ENTRY_OFFSET_MASK = 0x00fffffffffffe00
+    BME_TABLE_ENTRY_FLAG_ALL_ONES = 1
+    bmte_type = ['all-zeroes', 'all-ones', 'serialized']
+
+    def __init__(self, entry):
+        self.offset = entry & self.BME_TABLE_ENTRY_OFFSET_MASK
+        if self.offset:
+            self.type = 'serialized'
+        elif entry & self.BME_TABLE_ENTRY_FLAG_ALL_ONES:
+            self.type = 'all-ones'
+        else:
+            self.type = 'all-zeroes'
+
+
+class Qcow2BitmapTable:
+
+    def __init__(self, raw_table):
+        self.entries = []
+        for entry in raw_table:
+            self.entries.append(Qcow2BitmapTableEntry(entry))
+
+    def print_bitmap_table(self, cluster_size):
+        bitmap_table = enumerate(self.entries)
+        print("Bitmap table\ttype\t\toffset\t\tsize")
+        for i, entry in bitmap_table:
+            print("\t%-4d\t%s\t%#x\t\t%d" % (i, entry.type, entry.offset,
+                                             cluster_size))
+        print("")
 
 
 QCOW2_EXT_MAGIC_BITMAPS = 0x23852875
Signature · 1 line
1.8.3.1
#7 lore raw

PATCH v6 6/8 qcow2.py: Introduce '-j' key to dump in JSON format

In reply to Andrey Shinkevich

Add the command key to the qcow2.py arguments list to dump QCOW2 metadata in JSON format. Here is the suggested way to do that. The implementation of the dump in JSON format is in the patch that follows.

---
 tests/qemu-iotests/qcow2.py        | 20 +++++++++++++++-----
 tests/qemu-iotests/qcow2_format.py | 18 +++++++++---------
 2 files changed, 24 insertions(+), 14 deletions(-)
tests/qemu-iotests/qcow2.py +15 -5
index 8c187e9..b08d8fc 100755
@@ -24,16 +24,19 @@ from qcow2_format import (
 )
 
 
+dump_json = False
+
+
 def cmd_dump_header(fd):
     h = QcowHeader(fd)
-    h.dump()
+    h.dump(dump_json)
     print()
-    h.dump_extensions()
+    h.dump_extensions(dump_json)
 
 
 def cmd_dump_header_exts(fd):
     h = QcowHeader(fd)
-    h.dump_extensions()
+    h.dump_extensions(dump_json)
 
 
 def cmd_set_header(fd, name, value):
@@ -132,6 +135,11 @@ cmds = [
 
 
 def main(filename, cmd, args):
+    global dump_json
+    dump_json = '-j' in sys.argv
+    if dump_json:
+        sys.argv.remove('-j')
+        args.remove('-j')
     fd = open(filename, "r+b")
     try:
         for name, handler, num_args, desc in cmds:
@@ -149,12 +157,14 @@ def main(filename, cmd, args):
 
 
 def usage():
-    print("Usage: %s <file> <cmd> [<arg>, ...]" % sys.argv[0])
+    print("Usage: %s <file> <cmd> [<arg>, ...] [<key>, ...]" % sys.argv[0])
     print("")
     print("Supported commands:")
     for name, handler, num_args, desc in cmds:
         print("    %-20s - %s" % (name, desc))
-
+    print("")
+    print("Supported keys:")
+    print("    %-20s - %s" % ('-j', 'Dump in JSON format'))
 
 if __name__ == '__main__':
     if len(sys.argv) < 3:
tests/qemu-iotests/qcow2_format.py +9 -9
index 2e7c058..95db7a9 100644
@@ -92,7 +92,7 @@ class Qcow2Struct(metaclass=Qcow2StructMeta):
         self.__dict__ = dict((field[2], values[i])
                              for i, field in enumerate(self.fields))
 
-    def dump(self):
+    def dump(self, dump_json=None):
         for f in self.fields:
             value = self.__dict__[f[2]]
             if isinstance(f[1], str):
@@ -143,10 +143,10 @@ class Qcow2BitmapExt(Qcow2Struct):
     def load(self, fd):
         self.read_bitmap_directory(fd)
 
-    def dump(self):
-        super().dump()
+    def dump(self, dump_json=None):
+        super().dump(dump_json)
         for bm in self.bitmaps:
-            bm.dump_bitmap_dir_entry()
+            bm.dump_bitmap_dir_entry(dump_json)
 
 
 BME_FLAG_IN_USE = 1 << 0
@@ -190,7 +190,7 @@ class Qcow2BitmapDirEntry(Qcow2Struct):
         table = [e[0] for e in struct.iter_unpack('>Q', fd.read(table_size))]
         self.bitmap_table = Qcow2BitmapTable(table)
 
-    def dump_bitmap_dir_entry(self):
+    def dump_bitmap_dir_entry(self, dump_json=None):
         print()
         print(f'{"Bitmap name":<25} {self.name}')
         for fl in self.bitmap_flags:
@@ -298,13 +298,13 @@ class QcowHeaderExtension(Qcow2Struct):
         else:
             self.obj = None
 
-    def dump(self):
+    def dump(self, dump_json=None):
         super().dump()
 
         if self.obj is None:
             print(f'{"data":<25} {self.data_str}')
         else:
-            self.obj.dump()
+            self.obj.dump(dump_json)
 
     @classmethod
     def create(cls, magic, data):
@@ -407,8 +407,8 @@ class QcowHeader(Qcow2Struct):
         buf = buf[0:header_bytes-1]
         fd.write(buf)
 
-    def dump_extensions(self):
+    def dump_extensions(self, dump_json=None):
         for ex in self.extensions:
             print('Header extension:')
-            ex.dump()
+            ex.dump(dump_json)
             print()
Signature · 1 line
1.8.3.1
#8 lore raw

PATCH v6 7/8 qcow2_format.py: collect fields to dump in JSON format

In reply to Andrey Shinkevich

As __dict__ is being extended with class members we do not want to print in JSON format dump, make a light copy of the initial __dict__ and extend the copy by adding lists we have to print in the JSON output.

---
 tests/qemu-iotests/qcow2_format.py | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
tests/qemu-iotests/qcow2_format.py +4 -1
index 95db7a9..bb2f13b 100644
@@ -92,6 +92,8 @@ class Qcow2Struct(metaclass=Qcow2StructMeta):
         self.__dict__ = dict((field[2], values[i])
                              for i, field in enumerate(self.fields))
 
+        self.fields_dict = self.__dict__.copy()
+
     def dump(self, dump_json=None):
         for f in self.fields:
             value = self.__dict__[f[2]]
@@ -102,7 +104,6 @@ class Qcow2Struct(metaclass=Qcow2StructMeta):
 
             print('{:<25} {}'.format(f[2], value_str))
 
-
 # seek relative to the current position in the file
 FROM_CURRENT = 1
 
@@ -142,6 +143,7 @@ class Qcow2BitmapExt(Qcow2Struct):
 
     def load(self, fd):
         self.read_bitmap_directory(fd)
+        self.fields_dict.update(entries=self.bitmaps)
 
     def dump(self, dump_json=None):
         super().dump(dump_json)
@@ -189,6 +191,7 @@ class Qcow2BitmapDirEntry(Qcow2Struct):
         table_size = self.bitmap_table_bytes * struct.calcsize('Q')
         table = [e[0] for e in struct.iter_unpack('>Q', fd.read(table_size))]
         self.bitmap_table = Qcow2BitmapTable(table)
+        self.fields_dict.update(bitmap_table=self.bitmap_table)
 
     def dump_bitmap_dir_entry(self, dump_json=None):
         print()
Signature · 1 line
1.8.3.1
#9 lore raw

PATCH v6 8/8 qcow2_format.py: support dumping metadata in JSON format

In reply to Andrey Shinkevich

Implementation of dumping QCOW2 image metadata.
The sample output:

{
    "Header_extensions": [
        {
            "name": "Feature table",
            "magic": 1745090647,
            "length": 192,
            "data_str": "<binary>"
        },
        {
            "name": "Bitmaps",
            "magic": 595929205,
            "length": 24,
            "data": {
                "nb_bitmaps": 2,
                "reserved32": 0,
                "bitmap_directory_size": 64,
                "bitmap_directory_offset": 1048576,
                "entries": [
                    {
                        "name": "bitmap-1",
                        "bitmap_table_offset": 589824,
                        "bitmap_table_size": 1,
                        "flags": [
                            "auto"
                        ],
                        "type": 1,
                        "granularity_bits": 16,
                        "name_size": 8,
                        "extra_data_size": 0,
                        "bitmap_table": {
                            "table_entries": [
                                {
                                    "type": "serialized",
                                    "offset": 655360
                                },
                                ...
---
 tests/qemu-iotests/qcow2_format.py | 60 ++++++++++++++++++++++++++++++++++++++
 1 file changed, 60 insertions(+)
tests/qemu-iotests/qcow2_format.py +60 -0
index bb2f13b..d87f8e0 100644
@@ -18,6 +18,15 @@
 
 import struct
 import string
+import json
+
+
+class ComplexEncoder(json.JSONEncoder):
+    def default(self, obj):
+        if hasattr(obj, 'get_fields_dict'):
+            return obj.get_fields_dict()
+        else:
+            return json.JSONEncoder.default(self, obj)
 
 
 class Qcow2Field:
@@ -95,6 +104,11 @@ class Qcow2Struct(metaclass=Qcow2StructMeta):
         self.fields_dict = self.__dict__.copy()
 
     def dump(self, dump_json=None):
+        if dump_json:
+            print(json.dumps(self.get_fields_dict(), indent=4,
+                             cls=ComplexEncoder))
+            return
+
         for f in self.fields:
             value = self.__dict__[f[2]]
             if isinstance(f[1], str):
@@ -150,6 +164,9 @@ class Qcow2BitmapExt(Qcow2Struct):
         for bm in self.bitmaps:
             bm.dump_bitmap_dir_entry(dump_json)
 
+    def get_fields_dict(self):
+        return self.fields_dict
+
 
 BME_FLAG_IN_USE = 1 << 0
 BME_FLAG_AUTO = 1 << 1
@@ -202,6 +219,12 @@ class Qcow2BitmapDirEntry(Qcow2Struct):
         super().dump()
         self.bitmap_table.print_bitmap_table(self.cluster_size)
 
+    def get_fields_dict(self):
+        bmp_name = dict(name=self.name)
+        bme_dict = {**bmp_name, **self.fields_dict}
+        bme_dict['flags'] = self.bitmap_flags
+        return bme_dict
+
 
 class Qcow2BitmapTableEntry:
 
@@ -218,6 +241,9 @@ class Qcow2BitmapTableEntry:
         else:
             self.type = 'all-zeroes'
 
+    def get_fields_dict(self):
+        return dict(type=self.type, offset=self.offset)
+
 
 class Qcow2BitmapTable:
 
@@ -234,6 +260,18 @@ class Qcow2BitmapTable:
                                              cluster_size))
         print("")
 
+    def get_fields_dict(self):
+        return dict(table_entries=self.entries)
+
+
+class Qcow2HeaderExtensionsDoc:
+
+    def __init__(self, extensions):
+        self.extensions = extensions
+
+    def get_fields_dict(self):
+        return dict(Header_extensions=self.extensions)
+
 
 QCOW2_EXT_MAGIC_BITMAPS = 0x23852875
 
@@ -249,6 +287,9 @@ class QcowHeaderExtension(Qcow2Struct):
             0x44415441: 'Data file'
         }
 
+        def get_fields_dict(self):
+            return self.mapping.get(self.value, "<unknown>")
+
     fields = (
         ('u32', Magic, 'magic'),
         ('u32', '{}', 'length')
@@ -309,6 +350,16 @@ class QcowHeaderExtension(Qcow2Struct):
         else:
             self.obj.dump(dump_json)
 
+    def get_fields_dict(self):
+        ext_name = dict(name=self.Magic(self.magic))
+        he_dict = {**ext_name, **self.fields_dict}
+        if self.obj is not None:
+            he_dict.update(data=self.obj)
+        else:
+            he_dict.update(data_str=self.data_str)
+
+        return he_dict
+
     @classmethod
     def create(cls, magic, data):
         return QcowHeaderExtension(magic, len(data), data)
@@ -411,7 +462,16 @@ class QcowHeader(Qcow2Struct):
         fd.write(buf)
 
     def dump_extensions(self, dump_json=None):
+        if dump_json:
+            ext_doc = Qcow2HeaderExtensionsDoc(self.extensions)
+            print(json.dumps(ext_doc.get_fields_dict(), indent=4,
+                             cls=ComplexEncoder))
+            return
+
         for ex in self.extensions:
             print('Header extension:')
             ex.dump(dump_json)
             print()
+
+    def get_fields_dict(self):
+        return self.fields_dict
Signature · 1 line
1.8.3.1