| 1 |
# (c) 2025, Denys Mishchenko <[email protected]> |
| 2 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 3 |
|
| 4 |
import abc |
| 5 |
from dataclasses import dataclass |
| 6 |
from dataclasses import asdict |
| 7 |
from dataclasses import field |
| 8 |
from typing import Dict |
| 9 |
from typing import List |
| 10 |
from typing import Union |
| 11 |
|
| 12 |
from ansible.module_utils.basic import AnsibleModule |
| 13 |
from ansible.module_utils.basic import missing_required_lib |
| 14 |
from ansible_collections.community.libvirt.plugins.module_utils.libvirt import ( |
| 15 |
LibvirtConnection) |
| 16 |
|
| 17 |
try: |
| 18 |
import libvirt |
| 19 |
LIBVIRT_IMPORT_ERR = None |
| 20 |
except ImportError as libvirt_import_exception: |
| 21 |
LIBVIRT_IMPORT_ERR = libvirt_import_exception |
| 22 |
|
| 23 |
|
| 24 |
try: |
| 25 |
from lxml import etree |
| 26 |
LXML_IMPORT_ERR = None |
| 27 |
except ImportError as lxml_import_exception: |
| 28 |
LXML_IMPORT_ERR = lxml_import_exception |
| 29 |
import xml.etree.ElementTree as etree |
| 30 |
|
| 31 |
try: |
| 32 |
from yaml import safe_dump |
| 33 |
except ImportError as safe_dump_import_exception: |
| 34 |
SAFE_DUMP_IMPORT_ERR = safe_dump_import_exception |
| 35 |
else: |
| 36 |
SAFE_DUMP_IMPORT_ERR = None |
| 37 |
|
| 38 |
|
| 39 |
STATE_CHOICES = ['present', 'absent'] |
| 40 |
|
| 41 |
|
| 42 |
def compare_dicts(dict_one: dict, dict_two: dict) -> bool: |
| 43 |
""" Compare two dicts. |
| 44 |
|
| 45 |
Return True if two dict contents are equal |
| 46 |
""" |
| 47 |
for item, value in dict_one.items(): |
| 48 |
if item not in dict_two.keys(): |
| 49 |
return False |
| 50 |
if isinstance(value, dict): |
| 51 |
if not compare_dicts(value, dict_two[item]): |
| 52 |
return False |
| 53 |
continue |
| 54 |
if isinstance(value, list): |
| 55 |
if not compare_lists(value, dict_two[item]): |
| 56 |
return False |
| 57 |
continue |
| 58 |
if value != dict_two[item]: |
| 59 |
return False |
| 60 |
return True |
| 61 |
|
| 62 |
|
| 63 |
def compare_lists(list_one: list, list_two: list) -> bool: |
| 64 |
""" Compare two unsorted lists """ |
| 65 |
if list_one == list_two: |
| 66 |
return True |
| 67 |
# Lists are not sorted and compare is faster than sorting or copying, so... |
| 68 |
# it might be that I am re-inventing the wheel here... |
| 69 |
for item in list_one: |
| 70 |
if item not in list_two: |
| 71 |
return False |
| 72 |
for item in list_two: |
| 73 |
if item not in list_one: |
| 74 |
return False |
| 75 |
return True |
| 76 |
|
| 77 |
|
| 78 |
def libvirt_error_to_none(func): |
| 79 |
""" Decorator to replace libvirt errors to None value return |
| 80 |
|
| 81 |
When we search for absent object in libvirt we get exception, but |
| 82 |
sometimes we just want a None value to be returned instead. |
| 83 |
|
| 84 |
:param func: Callable function to wrap and check the status. |
| 85 |
""" |
| 86 |
|
| 87 |
def wrapper(self, **kwargs): |
| 88 |
try: |
| 89 |
return func(self, **kwargs) |
| 90 |
except libvirt.libvirtError: |
| 91 |
return None |
| 92 |
return wrapper |
| 93 |
|
| 94 |
|
| 95 |
@dataclass |
| 96 |
class ModuleStatus: |
| 97 |
""" Ansible module status """ |
| 98 |
changed: bool = False |
| 99 |
failed: bool = False |
| 100 |
msg: Union[str, None] = None # linter refuse 'str | None' |
| 101 |
exception: Union[str, ImportError, None] = None |
| 102 |
before: Dict = field(default_factory=dict) |
| 103 |
after: Dict = field(default_factory=dict) |
| 104 |
warnings: List[str] = field(default_factory=list) |
| 105 |
data: Dict = field(default_factory=dict) |
| 106 |
|
| 107 |
@property |
| 108 |
def report(self): |
| 109 |
""" Forms a dict suitable for ansible return """ |
| 110 |
ansible_report = { |
| 111 |
"changed": self.changed, |
| 112 |
"failed": self.failed, |
| 113 |
"msg": self.msg |
| 114 |
} |
| 115 |
if self.failed and self.exception is not None: |
| 116 |
ansible_report['exception'] = self.exception |
| 117 |
return ansible_report |
| 118 |
if self.changed: |
| 119 |
# changes may have diff definition, so diff should be added |
| 120 |
ansible_report['diff'] = { |
| 121 |
'before': safe_dump(self.before), |
| 122 |
'after': safe_dump(self.after)} |
| 123 |
# TODO: Add sort on results to produce better diff |
| 124 |
# We may have additional data supplied for the return from module |
| 125 |
if self.data != {}: |
| 126 |
ansible_report.update(self.data) |
| 127 |
return ansible_report |
| 128 |
|
| 129 |
|
| 130 |
def data_as_dict(structure): |
| 131 |
""" Transform dataclass instances to a regular dict """ |
| 132 |
result = [] |
| 133 |
for item in structure: |
| 134 |
if isinstance(item, list) or isinstance(item, dict) == dict: |
| 135 |
dict_item = data_as_dict(item) |
| 136 |
else: |
| 137 |
dict_item = asdict(item) |
| 138 |
result.append(dict_item) |
| 139 |
return result |
| 140 |
|
| 141 |
|
| 142 |
def parse_xml_etree(xml: str) -> dict: |
| 143 |
""" Parse xml etree and return it as dict """ |
| 144 |
result = {} |
| 145 |
for element in etree.fromstring(xml).iterchildren(): |
| 146 |
if len(element.items()) > 0: |
| 147 |
result[element.tag] = element.items() |
| 148 |
continue |
| 149 |
result[element.tag] = element.text |
| 150 |
return result |
| 151 |
|
| 152 |
|
| 153 |
class VirtModule(): |
| 154 |
""" Virt Ansible module is a base class for all Virt Module classes """ |
| 155 |
|
| 156 |
def __init__(self, **module_kwargs: dict): |
| 157 |
""" Initialize Virt base class """ |
| 158 |
self.mod_status = ModuleStatus() |
| 159 |
# Might be a bad idea and all possible varnames needs to be listed, but |
| 160 |
# initialization of AnsibleModule will definetely validate the input... |
| 161 |
self.ansible = AnsibleModule(**module_kwargs) |
| 162 |
self.check = self.ansible.check_mode |
| 163 |
self.warn = self.ansible.warn |
| 164 |
self.check_imports() |
| 165 |
uri = self.ansible.params.get('uri', 'qemu:///system') |
| 166 |
self.libvirt = LibvirtConnection(uri, self.ansible) |
| 167 |
self.conn = self.libvirt.conn |
| 168 |
|
| 169 |
def check_imports(self): |
| 170 |
""" Check imports and fail if libraries imports wasn't successfull """ |
| 171 |
if LIBVIRT_IMPORT_ERR: |
| 172 |
self.mod_status.msg = missing_required_lib("libvirt") |
| 173 |
self.mod_status.exception = LIBVIRT_IMPORT_ERR |
| 174 |
self.mod_status.failed = True |
| 175 |
self.exit() |
| 176 |
if LXML_IMPORT_ERR: |
| 177 |
self.mod_status.msg = missing_required_lib("lxml") |
| 178 |
self.mod_status.exception = LXML_IMPORT_ERR |
| 179 |
self.mod_status.failed = True |
| 180 |
self.exit() |
| 181 |
if SAFE_DUMP_IMPORT_ERR: |
| 182 |
self.mod_status.msg = missing_required_lib("pyYAML") |
| 183 |
self.mod_status.exception = SAFE_DUMP_IMPORT_ERR |
| 184 |
self.mod_status.failed = True |
| 185 |
self.exit() |
| 186 |
|
| 187 |
def _request_cred(self, credentials, user_data): |
| 188 |
""" a callable function for libvirt sasl auth |
| 189 |
|
| 190 |
:param credentials: list of credential, type, prompt, result, output... |
| 191 |
:user_data: being passed, but isn't used in the example |
| 192 |
:return: 0 which means success |
| 193 |
""" |
| 194 |
for credential in credentials: |
| 195 |
if credential[0] == libvirt.VIR_CRED_AUTHNAME: |
| 196 |
credential[4] = self.ansible.params.get('auth_user', '') |
| 197 |
elif credential[0] == libvirt.VIR_CRED_PASSPHRASE: |
| 198 |
credential[4] = self.ansible.params.get('auth_password', '') |
| 199 |
return 0 |
| 200 |
|
| 201 |
def libvirt_auth_connect(self): |
| 202 |
""" Connects to libvirt and returns libvirt.virConnect object """ |
| 203 |
uri = self.ansible.params.get('uri', 'qemu:///system') |
| 204 |
try: |
| 205 |
auth = [[ |
| 206 |
libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE], |
| 207 |
self._request_cred, |
| 208 |
None] |
| 209 |
return libvirt.openAuth(uri, auth, 0) |
| 210 |
except libvirt.libvirtError as exception: |
| 211 |
self.mod_status.msg = "hypervisor connection failure" |
| 212 |
self.mod_status.exception = exception |
| 213 |
self.ansible.fail_json(**self.mod_status.report) |
| 214 |
return None |
| 215 |
|
| 216 |
@abc.abstractmethod |
| 217 |
def logic(self): |
| 218 |
""" Abstract methog definition for the module logic """ |
| 219 |
|
| 220 |
def run(self): |
| 221 |
""" Select which function to call based on arguments |
| 222 |
|
| 223 |
If ansible params contains command it will try to match its value to |
| 224 |
a function name and execute that function. Otherwise it will fallback |
| 225 |
to a logic function which must be defined in a chaild classes. |
| 226 |
""" |
| 227 |
command = self.ansible.params.get('command') |
| 228 |
if command: |
| 229 |
the_func = getattr(self, command) |
| 230 |
else: |
| 231 |
the_func = self.logic |
| 232 |
return the_func() |
| 233 |
|
| 234 |
def exit(self): |
| 235 |
""" Module exit logic """ |
| 236 |
if self.mod_status.failed: |
| 237 |
self.ansible.fail_json(**self.mod_status.report) |
| 238 |
else: |
| 239 |
self.ansible.exit_json(**self.mod_status.report) |