Debian Codegraph @

oslo_utils/imageutils/qemu.py

raw symbols SCIP
1 # Copyright 2010 United States Government as represented by the
2 # Administrator of the National Aeronautics and Space Administration.
3 # All Rights Reserved.
4 # Copyright (c) 2010 Citrix Systems, Inc.
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License"); you may
7 # not use this file except in compliance with the License. You may obtain
8 # a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 # License for the specific language governing permissions and limitations
16 # under the License.
17
18 """
19 Helper methods to deal with images.
20
21 .. versionadded:: 3.1
22
23 .. versionchanged:: 3.14.0
24 add paramter format.
25
26 """
27
28 import json
29 import re
30 from typing import Any
31
32 from oslo_utils._i18n import _
33 from oslo_utils import strutils
34
35
36 class QemuImgInfo:
37 """Parse Qemu image information from command `qemu-img info`'s output.
38
39 The instance of :class:`QemuImgInfo` has properties: `image`,
40 `backing_file`, `file_format`, `virtual_size`, `cluster_size`,
41 `disk_size`, `snapshots` and `encrypted`.
42 """
43
44 BACKING_FILE_RE = re.compile(
45 (
46 r"^(.*?)\s*\(actual\s+path\s*:"
47 r"\s+(.*?)\)\s*$"
48 ),
49 re.I,
50 )
51 TOP_LEVEL_RE = re.compile(r"^([\w\d\s\_\-]+):(.*)$")
52 SIZE_RE = re.compile(
53 r"([0-9]+[eE][-+][0-9]+|\d*\.?\d+)"
54 r"\s*(\w+)?(\s*\(\s*(\d+)\s+bytes\s*\))?",
55 re.I,
56 )
57
58 def __init__(
59 self,
60 cmd_output: str | bytes | bytearray | None = None,
61 format: str = 'json',
62 ) -> None:
63 if isinstance(cmd_output, bytes | bytearray):
64 cmd_output = cmd_output.decode()
65
66 if format != 'json':
67 raise ValueError(
68 f'Unsupported format: {format}. Only \'json\' is supported'
69 )
70
71 details = json.loads(cmd_output or '{}')
72
73 self.image = details.get('filename')
74 self.backing_file = details.get('backing-filename')
75 self.backing_file_format = details.get('backing-filename-format')
76 self.file_format = details.get('format')
77 self.virtual_size = details.get('virtual-size')
78 self.cluster_size = details.get('cluster-size')
79 self.disk_size = details.get('actual-size')
80 self.snapshots = details.get('snapshots', [])
81 # NOTE(tkajinam) Preserve compatibility with the 'human' format, which
82 # is the previous default and was removed.
83 self.encrypted = 'yes' if details.get('encrypted') else None
84 self.format_specific = details.get('format-specific')
85
86 def __str__(self) -> str:
87 lines = [
88 f'image: {self.image}',
89 f'file_format: {self.file_format}',
90 f'virtual_size: {self.virtual_size}',
91 f'disk_size: {self.disk_size}',
92 f'cluster_size: {self.cluster_size}',
93 f'backing_file: {self.backing_file}',
94 f'backing_file_format: {self.backing_file_format}',
95 ]
96 if self.snapshots:
97 lines.append(f"snapshots: {self.snapshots}")
98 if self.encrypted:
99 lines.append(f"encrypted: {self.encrypted}")
100 if self.format_specific:
101 lines.append(f"format_specific: {self.format_specific}")
102 return "\n".join(lines)
103
104 def _canonicalize(self, field: str) -> str:
105 # Standardize on underscores/lc/no dash and no spaces
106 # since qemu seems to have mixed outputs here... and
107 # this format allows for better integration with python
108 # - i.e. for usage in kwargs and such...
109 field = field.lower().strip()
110 for c in (" ", "-"):
111 field = field.replace(c, '_')
112 return field
113
114 def _extract_bytes(self, details: str) -> int:
115 # Replace it with the byte amount
116 real_size = self.SIZE_RE.search(details)
117 if not real_size:
118 raise ValueError(_('Invalid input value "%s".') % details)
119 magnitude = real_size.group(1)
120 if "e" in magnitude.lower():
121 magnitude = format(float(real_size.group(1)), '.0f')
122 unit_of_measure = real_size.group(2)
123 bytes_info = real_size.group(3)
124 if bytes_info:
125 return int(real_size.group(4))
126 elif not unit_of_measure:
127 return int(magnitude)
128 # Allow abbreviated unit such as K to mean KB for compatibility.
129 if len(unit_of_measure) == 1 and unit_of_measure != 'B':
130 unit_of_measure += 'B'
131 return int(
132 strutils.string_to_bytes(
133 f'{magnitude}{unit_of_measure}', return_int=True
134 )
135 )
136
137 def _extract_details(
138 self, root_cmd: str, root_details: str, lines_after: list[str]
139 ) -> str | int | list[dict[str, str]]:
140 real_details: str | int | list[dict[str, str]] = root_details
141 if root_cmd == 'backing_file':
142 # Replace it with the real backing file
143 backing_match = self.BACKING_FILE_RE.match(root_details)
144 if backing_match:
145 real_details = backing_match.group(2).strip()
146 elif root_cmd in ['virtual_size', 'cluster_size', 'disk_size']:
147 # Replace it with the byte amount (if we can convert it)
148 if root_details in ('None', 'unavailable'):
149 real_details = 0
150 else:
151 real_details = self._extract_bytes(root_details)
152 elif root_cmd == 'file_format':
153 real_details = root_details.strip().lower()
154 elif root_cmd == 'snapshot_list':
155 # Next line should be a header, starting with 'ID'
156 if not lines_after or not lines_after.pop(0).startswith("ID"):
157 msg = _("Snapshot list encountered but no header found!")
158 raise ValueError(msg)
159 real_details = []
160 # This is the sprintf pattern we will try to match
161 # "%-10s%-20s%7s%20s%15s"
162 # ID TAG VM SIZE DATE VM CLOCK (current header)
163 while lines_after:
164 line = lines_after[0]
165 line_pieces = line.split()
166 if len(line_pieces) != 6:
167 break
168 # Check against this pattern in the final position
169 # "%02d:%02d:%02d.%03d"
170 date_pieces = line_pieces[5].split(":")
171 if len(date_pieces) != 3:
172 break
173 lines_after.pop(0)
174 real_details.append(
175 {
176 'id': line_pieces[0],
177 'tag': line_pieces[1],
178 'vm_size': line_pieces[2],
179 'date': line_pieces[3],
180 'vm_clock': line_pieces[4] + " " + line_pieces[5],
181 }
182 )
183 return real_details
184
185 def _parse(self, cmd_output: str) -> dict[str, Any]:
186 # Analysis done of qemu-img.c to figure out what is going on here
187 # Find all points start with some chars and then a ':' then a newline
188 # and then handle the results of those 'top level' items in a separate
189 # function.
190 #
191 # TODO(harlowja): newer versions might have a json output format
192 # we should switch to that whenever possible.
193 # see: http://bit.ly/XLJXDX
194 contents = {}
195 lines = [x for x in cmd_output.splitlines() if x.strip()]
196 while lines:
197 line = lines.pop(0)
198 top_level = self.TOP_LEVEL_RE.match(line)
199 if top_level:
200 root = self._canonicalize(top_level.group(1))
201 if not root:
202 continue
203 root_details = top_level.group(2).strip()
204 details = self._extract_details(root, root_details, lines)
205 contents[root] = details
206 return contents