| 1 |
# Copyright (c) 2021 Ansible Project |
| 2 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 3 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 4 |
|
| 5 |
from __future__ import annotations |
| 6 |
|
| 7 |
DOCUMENTATION = r""" |
| 8 |
name: xen_orchestra |
| 9 |
short_description: Xen Orchestra inventory source |
| 10 |
version_added: 4.1.0 |
| 11 |
author: |
| 12 |
- Dom Del Nano (@ddelnano) <[email protected]> |
| 13 |
- Samori Gorse (@shinuza) <[email protected]> |
| 14 |
requirements: |
| 15 |
- websocket-client >= 1.0.0 |
| 16 |
description: |
| 17 |
- Get inventory hosts from a Xen Orchestra deployment. |
| 18 |
- Uses a configuration file as an inventory source, it must end in C(.xen_orchestra.yml) or C(.xen_orchestra.yaml). |
| 19 |
extends_documentation_fragment: |
| 20 |
- ansible.builtin.constructed |
| 21 |
- ansible.builtin.inventory_cache |
| 22 |
options: |
| 23 |
plugin: |
| 24 |
description: The name of this plugin, it should always be set to V(community.general.xen_orchestra) for this plugin to |
| 25 |
recognize it as its own. |
| 26 |
required: true |
| 27 |
choices: ['community.general.xen_orchestra'] |
| 28 |
type: str |
| 29 |
api_host: |
| 30 |
description: |
| 31 |
- API host to XOA API. |
| 32 |
- If the value is not specified in the inventory configuration, the value of environment variable E(ANSIBLE_XO_HOST) |
| 33 |
is used instead. |
| 34 |
type: str |
| 35 |
env: |
| 36 |
- name: ANSIBLE_XO_HOST |
| 37 |
user: |
| 38 |
description: |
| 39 |
- Xen Orchestra user. |
| 40 |
- If the value is not specified in the inventory configuration, the value of environment variable E(ANSIBLE_XO_USER) |
| 41 |
is used instead. |
| 42 |
required: true |
| 43 |
type: str |
| 44 |
env: |
| 45 |
- name: ANSIBLE_XO_USER |
| 46 |
password: |
| 47 |
description: |
| 48 |
- Xen Orchestra password. |
| 49 |
- If the value is not specified in the inventory configuration, the value of environment variable E(ANSIBLE_XO_PASSWORD) |
| 50 |
is used instead. |
| 51 |
required: true |
| 52 |
type: str |
| 53 |
env: |
| 54 |
- name: ANSIBLE_XO_PASSWORD |
| 55 |
validate_certs: |
| 56 |
description: Verify TLS certificate if using HTTPS. |
| 57 |
type: boolean |
| 58 |
default: true |
| 59 |
use_ssl: |
| 60 |
description: Use wss when connecting to the Xen Orchestra API. |
| 61 |
type: boolean |
| 62 |
default: true |
| 63 |
use_vm_uuid: |
| 64 |
description: |
| 65 |
- Import Xen VMs to inventory using their UUID as the VM entry name. |
| 66 |
- If set to V(false) use VM name labels instead of UUIDs. |
| 67 |
type: boolean |
| 68 |
default: true |
| 69 |
version_added: 10.4.0 |
| 70 |
use_host_uuid: |
| 71 |
description: |
| 72 |
- Import Xen Hosts to inventory using their UUID as the Host entry name. |
| 73 |
- If set to V(false) use Host name labels instead of UUIDs. |
| 74 |
type: boolean |
| 75 |
default: true |
| 76 |
version_added: 10.4.0 |
| 77 |
""" |
| 78 |
|
| 79 |
|
| 80 |
EXAMPLES = r""" |
| 81 |
--- |
| 82 |
# file must be named xen_orchestra.yaml or xen_orchestra.yml |
| 83 |
plugin: community.general.xen_orchestra |
| 84 |
api_host: 192.168.1.255 |
| 85 |
user: xo |
| 86 |
password: xo_pwd |
| 87 |
validate_certs: true |
| 88 |
use_ssl: true |
| 89 |
groups: |
| 90 |
kube_nodes: "'kube_node' in tags" |
| 91 |
compose: |
| 92 |
ansible_port: 2222 |
| 93 |
use_vm_uuid: false |
| 94 |
use_host_uuid: true |
| 95 |
""" |
| 96 |
|
| 97 |
import json |
| 98 |
import ssl |
| 99 |
from time import sleep |
| 100 |
|
| 101 |
from ansible.errors import AnsibleError |
| 102 |
from ansible.plugins.inventory import BaseInventoryPlugin, Cacheable, Constructable |
| 103 |
|
| 104 |
from ansible_collections.community.general.plugins.module_utils._version import LooseVersion |
| 105 |
from ansible_collections.community.general.plugins.plugin_utils._unsafe import make_unsafe |
| 106 |
|
| 107 |
# 3rd party imports |
| 108 |
try: |
| 109 |
HAS_WEBSOCKET = True |
| 110 |
import websocket |
| 111 |
from websocket import create_connection |
| 112 |
|
| 113 |
if LooseVersion(websocket.__version__) <= LooseVersion("1.0.0"): |
| 114 |
raise ImportError |
| 115 |
except ImportError: |
| 116 |
HAS_WEBSOCKET = False |
| 117 |
|
| 118 |
|
| 119 |
HALTED = "Halted" |
| 120 |
PAUSED = "Paused" |
| 121 |
RUNNING = "Running" |
| 122 |
SUSPENDED = "Suspended" |
| 123 |
POWER_STATES = [RUNNING, HALTED, SUSPENDED, PAUSED] |
| 124 |
HOST_GROUP = "xo_hosts" |
| 125 |
POOL_GROUP = "xo_pools" |
| 126 |
|
| 127 |
|
| 128 |
def clean_group_name(label): |
| 129 |
return label.lower().replace(" ", "-").replace("-", "_") |
| 130 |
|
| 131 |
|
| 132 |
class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable): |
| 133 |
"""Host inventory parser for ansible using XenOrchestra as source.""" |
| 134 |
|
| 135 |
NAME = "community.general.xen_orchestra" |
| 136 |
|
| 137 |
def __init__(self): |
| 138 |
super().__init__() |
| 139 |
|
| 140 |
# from config |
| 141 |
self.counter = -1 |
| 142 |
self.session = None |
| 143 |
self.cache_key = None |
| 144 |
self.use_cache = None |
| 145 |
|
| 146 |
@property |
| 147 |
def pointer(self): |
| 148 |
self.counter += 1 |
| 149 |
return self.counter |
| 150 |
|
| 151 |
def create_connection(self, xoa_api_host): |
| 152 |
validate_certs = self.get_option("validate_certs") |
| 153 |
use_ssl = self.get_option("use_ssl") |
| 154 |
proto = "wss" if use_ssl else "ws" |
| 155 |
|
| 156 |
sslopt = None if validate_certs else {"cert_reqs": ssl.CERT_NONE} |
| 157 |
self.conn = create_connection(f"{proto}://{xoa_api_host}/api/", sslopt=sslopt) |
| 158 |
|
| 159 |
CALL_TIMEOUT = 100 |
| 160 |
"""Number of 1/10ths of a second to wait before method call times out.""" |
| 161 |
|
| 162 |
def call(self, method, params): |
| 163 |
"""Calls a method on the XO server with the provided parameters.""" |
| 164 |
id = self.pointer |
| 165 |
self.conn.send(json.dumps({"id": id, "jsonrpc": "2.0", "method": method, "params": params})) |
| 166 |
|
| 167 |
waited = 0 |
| 168 |
while waited < self.CALL_TIMEOUT: |
| 169 |
response = json.loads(self.conn.recv()) |
| 170 |
if "id" in response and response["id"] == id: |
| 171 |
return response |
| 172 |
else: |
| 173 |
sleep(0.1) |
| 174 |
waited += 1 |
| 175 |
|
| 176 |
raise AnsibleError(f"Method call {method} timed out after {self.CALL_TIMEOUT / 10} seconds.") |
| 177 |
|
| 178 |
def login(self, user, password): |
| 179 |
result = self.call("session.signIn", {"username": user, "password": password}) |
| 180 |
|
| 181 |
if "error" in result: |
| 182 |
raise AnsibleError(f"Could not connect: {result['error']}") |
| 183 |
|
| 184 |
def get_object(self, name): |
| 185 |
answer = self.call("xo.getAllObjects", {"filter": {"type": name}}) |
| 186 |
|
| 187 |
if "error" in answer: |
| 188 |
raise AnsibleError(f"Could not request: {answer['error']}") |
| 189 |
|
| 190 |
return answer["result"] |
| 191 |
|
| 192 |
def _get_objects(self): |
| 193 |
self.create_connection(self.xoa_api_host) |
| 194 |
self.login(self.xoa_user, self.xoa_password) |
| 195 |
|
| 196 |
return { |
| 197 |
"vms": self.get_object("VM"), |
| 198 |
"pools": self.get_object("pool"), |
| 199 |
"hosts": self.get_object("host"), |
| 200 |
} |
| 201 |
|
| 202 |
def _apply_constructable(self, name, variables): |
| 203 |
strict = self.get_option("strict") |
| 204 |
self._add_host_to_composed_groups(self.get_option("groups"), variables, name, strict=strict) |
| 205 |
self._add_host_to_keyed_groups(self.get_option("keyed_groups"), variables, name, strict=strict) |
| 206 |
self._set_composite_vars(self.get_option("compose"), variables, name, strict=strict) |
| 207 |
|
| 208 |
def _add_vms(self, vms, hosts, pools): |
| 209 |
vm_name_list = [] |
| 210 |
for uuid, vm in vms.items(): |
| 211 |
if self.vm_entry_name_type == "name_label": |
| 212 |
if vm["name_label"] not in vm_name_list: |
| 213 |
entry_name = vm["name_label"] |
| 214 |
vm_name_list.append(vm["name_label"]) |
| 215 |
else: |
| 216 |
vm_duplicate_count = vm_name_list.count(vm["name_label"]) |
| 217 |
entry_name = f"{vm['name_label']}_{vm_duplicate_count}" |
| 218 |
vm_name_list.append(vm["name_label"]) |
| 219 |
else: |
| 220 |
entry_name = uuid |
| 221 |
group = "with_ip" |
| 222 |
ip = vm.get("mainIpAddress") |
| 223 |
power_state = vm["power_state"].lower() |
| 224 |
pool_name = self._pool_group_name_for_uuid(pools, vm["$poolId"]) |
| 225 |
host_name = self._host_group_name_for_uuid(hosts, vm["$container"]) |
| 226 |
|
| 227 |
self.inventory.add_host(entry_name) |
| 228 |
|
| 229 |
# Grouping by power state |
| 230 |
self.inventory.add_child(power_state, entry_name) |
| 231 |
|
| 232 |
# Grouping by host |
| 233 |
if host_name: |
| 234 |
self.inventory.add_child(host_name, entry_name) |
| 235 |
|
| 236 |
# Grouping by pool |
| 237 |
if pool_name: |
| 238 |
self.inventory.add_child(pool_name, entry_name) |
| 239 |
|
| 240 |
# Grouping VMs with an IP together |
| 241 |
if ip is None: |
| 242 |
group = "without_ip" |
| 243 |
self.inventory.add_group(group) |
| 244 |
self.inventory.add_child(group, entry_name) |
| 245 |
|
| 246 |
# Adding meta |
| 247 |
self.inventory.set_variable(entry_name, "uuid", uuid) |
| 248 |
self.inventory.set_variable(entry_name, "ip", ip) |
| 249 |
self.inventory.set_variable(entry_name, "ansible_host", ip) |
| 250 |
self.inventory.set_variable(entry_name, "power_state", power_state) |
| 251 |
self.inventory.set_variable(entry_name, "name_label", vm["name_label"]) |
| 252 |
self.inventory.set_variable(entry_name, "type", vm["type"]) |
| 253 |
self.inventory.set_variable(entry_name, "cpus", vm["CPUs"]["number"]) |
| 254 |
self.inventory.set_variable(entry_name, "tags", vm["tags"]) |
| 255 |
self.inventory.set_variable(entry_name, "memory", vm["memory"]["size"]) |
| 256 |
self.inventory.set_variable(entry_name, "has_ip", group == "with_ip") |
| 257 |
self.inventory.set_variable(entry_name, "is_managed", vm.get("managementAgentDetected", False)) |
| 258 |
self.inventory.set_variable(entry_name, "os_version", vm["os_version"]) |
| 259 |
|
| 260 |
self._apply_constructable(entry_name, self.inventory.get_host(entry_name).get_vars()) |
| 261 |
|
| 262 |
def _add_hosts(self, hosts, pools): |
| 263 |
host_name_list = [] |
| 264 |
for host in hosts.values(): |
| 265 |
if self.host_entry_name_type == "name_label": |
| 266 |
if host["name_label"] not in host_name_list: |
| 267 |
entry_name = host["name_label"] |
| 268 |
host_name_list.append(host["name_label"]) |
| 269 |
else: |
| 270 |
host_duplicate_count = host_name_list.count(host["name_label"]) |
| 271 |
entry_name = f"{host['name_label']}_{host_duplicate_count}" |
| 272 |
host_name_list.append(host["name_label"]) |
| 273 |
else: |
| 274 |
entry_name = host["uuid"] |
| 275 |
|
| 276 |
group_name = f"xo_host_{clean_group_name(host['name_label'])}" |
| 277 |
pool_name = self._pool_group_name_for_uuid(pools, host["$poolId"]) |
| 278 |
|
| 279 |
self.inventory.add_group(group_name) |
| 280 |
self.inventory.add_host(entry_name) |
| 281 |
self.inventory.add_child(HOST_GROUP, entry_name) |
| 282 |
self.inventory.add_child(pool_name, entry_name) |
| 283 |
|
| 284 |
self.inventory.set_variable(entry_name, "enabled", host["enabled"]) |
| 285 |
self.inventory.set_variable(entry_name, "hostname", host["hostname"]) |
| 286 |
self.inventory.set_variable(entry_name, "memory", host["memory"]) |
| 287 |
self.inventory.set_variable(entry_name, "address", host["address"]) |
| 288 |
self.inventory.set_variable(entry_name, "cpus", host["cpus"]) |
| 289 |
self.inventory.set_variable(entry_name, "type", "host") |
| 290 |
self.inventory.set_variable(entry_name, "tags", host["tags"]) |
| 291 |
self.inventory.set_variable(entry_name, "version", host["version"]) |
| 292 |
self.inventory.set_variable(entry_name, "power_state", host["power_state"].lower()) |
| 293 |
self.inventory.set_variable(entry_name, "product_brand", host["productBrand"]) |
| 294 |
|
| 295 |
for pool in pools.values(): |
| 296 |
group_name = f"xo_pool_{clean_group_name(pool['name_label'])}" |
| 297 |
|
| 298 |
self.inventory.add_group(group_name) |
| 299 |
|
| 300 |
def _add_pools(self, pools): |
| 301 |
for pool in pools.values(): |
| 302 |
group_name = f"xo_pool_{clean_group_name(pool['name_label'])}" |
| 303 |
|
| 304 |
self.inventory.add_group(group_name) |
| 305 |
|
| 306 |
# TODO: Refactor |
| 307 |
def _pool_group_name_for_uuid(self, pools, pool_uuid): |
| 308 |
for pool in pools: |
| 309 |
if pool == pool_uuid: |
| 310 |
return f"xo_pool_{clean_group_name(pools[pool_uuid]['name_label'])}" |
| 311 |
|
| 312 |
# TODO: Refactor |
| 313 |
def _host_group_name_for_uuid(self, hosts, host_uuid): |
| 314 |
for host in hosts: |
| 315 |
if host == host_uuid: |
| 316 |
return f"xo_host_{clean_group_name(hosts[host_uuid]['name_label'])}" |
| 317 |
|
| 318 |
def _populate(self, objects): |
| 319 |
# Prepare general groups |
| 320 |
self.inventory.add_group(HOST_GROUP) |
| 321 |
self.inventory.add_group(POOL_GROUP) |
| 322 |
for group in POWER_STATES: |
| 323 |
self.inventory.add_group(group.lower()) |
| 324 |
|
| 325 |
self._add_pools(objects["pools"]) |
| 326 |
self._add_hosts(objects["hosts"], objects["pools"]) |
| 327 |
self._add_vms(objects["vms"], objects["hosts"], objects["pools"]) |
| 328 |
|
| 329 |
def verify_file(self, path): |
| 330 |
valid = False |
| 331 |
if super().verify_file(path): |
| 332 |
if path.endswith(("xen_orchestra.yaml", "xen_orchestra.yml")): |
| 333 |
valid = True |
| 334 |
else: |
| 335 |
self.display.vvv( |
| 336 |
'Skipping due to inventory source not ending in "xen_orchestra.yaml" nor "xen_orchestra.yml"' |
| 337 |
) |
| 338 |
return valid |
| 339 |
|
| 340 |
def parse(self, inventory, loader, path, cache=True): |
| 341 |
if not HAS_WEBSOCKET: |
| 342 |
raise AnsibleError( |
| 343 |
"This plugin requires websocket-client 1.0.0 or higher: " |
| 344 |
"https://github.com/websocket-client/websocket-client." |
| 345 |
) |
| 346 |
|
| 347 |
super().parse(inventory, loader, path) |
| 348 |
|
| 349 |
# read config from file, this sets 'options' |
| 350 |
self._read_config_data(path) |
| 351 |
self.inventory = inventory |
| 352 |
|
| 353 |
self.protocol = "wss" |
| 354 |
self.xoa_api_host = self.get_option("api_host") |
| 355 |
self.xoa_user = self.get_option("user") |
| 356 |
self.xoa_password = self.get_option("password") |
| 357 |
self.cache_key = self.get_cache_key(path) |
| 358 |
self.use_cache = cache and self.get_option("cache") |
| 359 |
|
| 360 |
self.validate_certs = self.get_option("validate_certs") |
| 361 |
if not self.get_option("use_ssl"): |
| 362 |
self.protocol = "ws" |
| 363 |
|
| 364 |
self.vm_entry_name_type = "uuid" |
| 365 |
if not self.get_option("use_vm_uuid"): |
| 366 |
self.vm_entry_name_type = "name_label" |
| 367 |
|
| 368 |
self.host_entry_name_type = "uuid" |
| 369 |
if not self.get_option("use_host_uuid"): |
| 370 |
self.host_entry_name_type = "name_label" |
| 371 |
|
| 372 |
objects = self._get_objects() |
| 373 |
self._populate(make_unsafe(objects)) |