Debian Codegraph @

ansible_collections/community/libvirt/plugins/module_utils/qemu.py

raw
1 # (c) 2025, Joey Zhang <[email protected]>
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3
4 from __future__ import (absolute_import, division, print_function)
5 __metaclass__ = type
6
7 import json
8
9
10 class QemuImgTool(object):
11 """
12 A wrapper for invoking qemu-img command-line tool.
13 """
14
15 def __init__(self, module,
16 qemu_img_path=None):
17 self.module = module
18 self.warnings = []
19 self._base_command = qemu_img_path if qemu_img_path is not None else 'qemu-img'
20 self.command_argv = [self._base_command]
21 self._executed_commands = []
22
23 def get_commands(self):
24 """Return list of commands that have been executed."""
25 return self._executed_commands
26
27 def _reset_command(self):
28 """Reset command_argv to base command for new operation"""
29 self.command_argv = [self._base_command]
30
31 def _add_flag(self, flag):
32 """Add a flag to the command line"""
33 self.command_argv.append(flag)
34
35 def _add_option(self, flag, value):
36 """Add an option with value to the command line"""
37 if value is not None:
38 self.command_argv.append(flag)
39 self.command_argv.append(str(value))
40
41 def _add_option_list(self, flag, value_list):
42 """Add multiple values for an option"""
43 if value_list:
44 for value in value_list:
45 if value is not None:
46 self.command_argv.append(flag)
47 self.command_argv.append(str(value))
48
49 def convert(self, filename, output_filename,
50 source_format=None, output_format=None,
51 compressed=False, sparse_size=None, num_coroutines=None):
52 """
53 Build and execute qemu-img convert command
54
55 This operation creates a new image file and respects check_mode.
56 In check_mode, the command is built but not executed.
57 """
58 self._reset_command()
59 self.command_argv.append('convert')
60
61 if source_format:
62 self._add_option('-f', source_format)
63
64 if output_format:
65 self._add_option('-O', output_format)
66
67 if compressed:
68 self._add_flag('-c')
69
70 if sparse_size:
71 self._add_option('-S', sparse_size)
72
73 if num_coroutines:
74 self._add_option('-m', num_coroutines)
75
76 # Add disk image filename
77 self.command_argv.append(str(filename))
78
79 # Add output filename (must be last)
80 self.command_argv.append(str(output_filename))
81
82 # Store the command for later retrieval
83 self._executed_commands.append(' '.join(self.command_argv))
84
85 # Check if we're in check mode
86 if self.module.check_mode:
87 # In check mode, don't execute the command but return success
88 return 0, "Would convert image from %s to %s" % (filename, output_filename), ""
89
90 # Execute the command
91 rc, stdout, stderr = self.module.run_command(
92 self.command_argv, check_rc=False)
93
94 return rc, stdout, stderr
95
96 def info(self, filename, source_format=None,
97 backing_chain=False):
98 """
99 Build and execute qemu-img info command
100
101 This operation is read-only and does not respect check_mode
102 as it doesn't modify the system state.
103 """
104 self._reset_command()
105 self.command_argv.append('info')
106
107 if source_format:
108 self._add_option('-f', source_format)
109
110 if backing_chain:
111 self._add_flag('--backing-chain')
112
113 self._add_option('--output', "json")
114 # Add disk image filename
115 self.command_argv.append(str(filename))
116
117 # Execute the command
118 rc, stdout, stderr = self.module.run_command(
119 self.command_argv, check_rc=False)
120
121 # Parse output based on format
122 parsed_output = dict()
123 if rc == 0 and stdout.strip():
124 try:
125 parsed_output = json.loads(stdout)
126 except ValueError as e:
127 # If JSON parsing fails, add warning
128 self.warnings.append(
129 "Failed to parse JSON output: %s" % str(e))
130
131 return rc, parsed_output, stderr
132
133 def resize(self, filename, size, source_format=None,
134 preallocation=None, shrink=False):
135 """
136 Build and execute qemu-img resize command
137
138 This operation modifies an existing image file and respects check_mode.
139 In check_mode, the command is built but not executed.
140
141 Args:
142 filename (str): Image file path
143 size (str): New size with optional +/- prefix and size suffixes (k, M, G, T)
144 Examples: '10G', '+1G', '-500M'
145 source_format (str): Disk image format (auto-detected if None)
146 preallocation (str): Preallocation mode ('off', 'metadata', 'falloc', 'full')
147 shrink (bool): Allow shrinking (required for size reduction)
148
149 Returns:
150 tuple: (rc, stdout, stderr)
151 """
152 self._reset_command()
153 self.command_argv.append('resize')
154
155 if source_format:
156 self._add_option('-f', source_format)
157
158 if preallocation:
159 self._add_option('--preallocation', preallocation)
160
161 if shrink:
162 self._add_flag('--shrink')
163
164 # Add disk image filename
165 self.command_argv.append(str(filename))
166
167 # Add size (must be last)
168 self.command_argv.append(str(size))
169
170 # Store the command for later retrieval
171 self._executed_commands.append(' '.join(self.command_argv))
172
173 # Check if we're in check mode
174 if self.module.check_mode:
175 # In check mode, don't execute the command but return success
176 return 0, "Would resize image %s to %s" % (filename, size), ""
177
178 # Execute the command
179 rc, stdout, stderr = self.module.run_command(
180 self.command_argv, check_rc=False)
181
182 return rc, stdout, stderr