| 1 |
# Based on local.py (c) 2012, Michael DeHaan <[email protected]> |
| 2 |
# Based on chroot.py (c) 2013, Maykel Moya <[email protected]> |
| 3 |
# (c) 2013, Michael Scherer <[email protected]> |
| 4 |
# (c) 2015, Toshio Kuratomi <[email protected]> |
| 5 |
# (c) 2017 Ansible Project |
| 6 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 7 |
|
| 8 |
from __future__ import (absolute_import, division, print_function) |
| 9 |
__metaclass__ = type |
| 10 |
|
| 11 |
DOCUMENTATION = """ |
| 12 |
--- |
| 13 |
author: |
| 14 |
- Jesse Pretorius (@odyssey4me) <[email protected]> |
| 15 |
name: libvirt_qemu |
| 16 |
short_description: Run tasks on libvirt/qemu virtual machines |
| 17 |
description: |
| 18 |
- Run commands or put/fetch files to libvirt/qemu virtual machines using the qemu agent API. |
| 19 |
notes: |
| 20 |
- Currently DOES NOT work with selinux set to enforcing in the VM. |
| 21 |
- Requires the qemu-agent installed in the VM. |
| 22 |
- Requires access to the qemu-ga commands guest-exec, guest-exec-status, guest-file-close, guest-file-open, guest-file-read, guest-file-write. |
| 23 |
extends_documentation_fragment: |
| 24 |
- community.libvirt.requirements |
| 25 |
version_added: "2.10.0" |
| 26 |
options: |
| 27 |
remote_addr: |
| 28 |
description: Virtual machine name. |
| 29 |
default: inventory_hostname |
| 30 |
vars: |
| 31 |
- name: ansible_host |
| 32 |
- name: inventory_hostname |
| 33 |
executable: |
| 34 |
description: |
| 35 |
- Shell to use for execution inside container. |
| 36 |
- Set this to 'cmd' or 'powershell' for Windows VMs. |
| 37 |
default: /bin/sh |
| 38 |
vars: |
| 39 |
- name: ansible_shell_type |
| 40 |
virt_uri: |
| 41 |
description: Libvirt URI to connect to to access the virtual machine. |
| 42 |
default: qemu:///system |
| 43 |
vars: |
| 44 |
- name: ansible_libvirt_uri |
| 45 |
""" |
| 46 |
|
| 47 |
import base64 |
| 48 |
import json |
| 49 |
import re |
| 50 |
import shlex |
| 51 |
import time |
| 52 |
import traceback |
| 53 |
|
| 54 |
try: |
| 55 |
import libvirt |
| 56 |
import libvirt_qemu |
| 57 |
except ImportError as imp_exc: |
| 58 |
LIBVIRT_IMPORT_ERROR = imp_exc |
| 59 |
else: |
| 60 |
LIBVIRT_IMPORT_ERROR = None |
| 61 |
|
| 62 |
from ansible.errors import AnsibleError, AnsibleConnectionFailure, AnsibleFileNotFound |
| 63 |
from ansible.module_utils._text import to_bytes, to_native, to_text |
| 64 |
from ansible.module_utils.six import raise_from |
| 65 |
from ansible.plugins.connection import ConnectionBase, BUFSIZE |
| 66 |
from ansible.utils.display import Display |
| 67 |
from ansible_collections.community.libvirt.plugins.module_utils.powershell import _parse_clixml |
| 68 |
from functools import partial |
| 69 |
from os.path import exists |
| 70 |
|
| 71 |
display = Display() |
| 72 |
|
| 73 |
|
| 74 |
REQUIRED_CAPABILITIES = [ |
| 75 |
{'enabled': True, 'name': 'guest-exec', 'success-response': True}, |
| 76 |
{'enabled': True, 'name': 'guest-exec-status', 'success-response': True}, |
| 77 |
{'enabled': True, 'name': 'guest-file-close', 'success-response': True}, |
| 78 |
{'enabled': True, 'name': 'guest-file-open', 'success-response': True}, |
| 79 |
{'enabled': True, 'name': 'guest-file-read', 'success-response': True}, |
| 80 |
{'enabled': True, 'name': 'guest-file-write', 'success-response': True} |
| 81 |
] |
| 82 |
|
| 83 |
|
| 84 |
class Connection(ConnectionBase): |
| 85 |
''' Local libvirt qemu based connections ''' |
| 86 |
|
| 87 |
transport = 'community.libvirt.libvirt_qemu' |
| 88 |
# TODO(odyssey4me): |
| 89 |
# Figure out why pipelining does not work and fix it |
| 90 |
has_pipelining = False |
| 91 |
has_tty = False |
| 92 |
|
| 93 |
def __init__(self, play_context, new_stdin, *args, **kwargs): |
| 94 |
if LIBVIRT_IMPORT_ERROR: |
| 95 |
raise_from( |
| 96 |
AnsibleError('libvirt python bindings must be installed to use this plugin'), |
| 97 |
LIBVIRT_IMPORT_ERROR) |
| 98 |
|
| 99 |
super(Connection, self).__init__(play_context, new_stdin, *args, **kwargs) |
| 100 |
|
| 101 |
self._host = self._play_context.remote_addr |
| 102 |
self._user_homedir = None |
| 103 |
|
| 104 |
# Windows operates differently from a POSIX connection/shell plugin, |
| 105 |
# we need to set various properties to ensure SSH on Windows continues |
| 106 |
# to work |
| 107 |
# Ensure that any Windows hosts in your inventory have one of the |
| 108 |
# following set, in order to trigger this code: |
| 109 |
# ansible_shell_type: cmd |
| 110 |
# ansible_shell_type: powershell |
| 111 |
if getattr(self._shell, "_IS_WINDOWS", False): |
| 112 |
self.has_native_async = True |
| 113 |
self.always_pipeline_modules = True |
| 114 |
self.module_implementation_preferences = ('.ps1', '.exe', '') |
| 115 |
self.allow_executable = False |
| 116 |
|
| 117 |
def _connect(self): |
| 118 |
''' connect to the virtual machine; nothing to do here ''' |
| 119 |
super(Connection, self)._connect() |
| 120 |
if not self._connected: |
| 121 |
|
| 122 |
self._virt_uri = self.get_option('virt_uri') |
| 123 |
|
| 124 |
self._display.vvv(u"CONNECT TO {0}".format(self._virt_uri), host=self._host) |
| 125 |
try: |
| 126 |
self.conn = libvirt.open(self._virt_uri) |
| 127 |
except libvirt.libvirtError as err: |
| 128 |
raise AnsibleConnectionFailure(to_native(err)) |
| 129 |
|
| 130 |
self._display.vvv(u"FIND DOMAIN {0}".format(self._host), host=self._host) |
| 131 |
try: |
| 132 |
self.domain = self.conn.lookupByName(self._host) |
| 133 |
except libvirt.libvirtError as err: |
| 134 |
raise AnsibleConnectionFailure(to_native(err)) |
| 135 |
|
| 136 |
request_cap = json.dumps({'execute': 'guest-info'}) |
| 137 |
response_cap = json.loads(libvirt_qemu.qemuAgentCommand(self.domain, request_cap, 5, 0)) |
| 138 |
self.capabilities = response_cap['return']['supported_commands'] |
| 139 |
self._display.vvvvv(u"GUEST CAPABILITIES: {0}".format(self.capabilities), host=self._host) |
| 140 |
missing_caps = [] |
| 141 |
for cap in REQUIRED_CAPABILITIES: |
| 142 |
if cap not in self.capabilities: |
| 143 |
missing_caps.append(cap['name']) |
| 144 |
if len(missing_caps) > 0: |
| 145 |
self._display.vvv(u"REQUIRED CAPABILITIES MISSING: {0}".format(missing_caps), host=self._host) |
| 146 |
raise AnsibleConnectionFailure('Domain does not have required capabilities') |
| 147 |
|
| 148 |
display.vvv(u"ESTABLISH {0} CONNECTION".format(self.transport), host=self._host) |
| 149 |
self._connected = True |
| 150 |
|
| 151 |
@property |
| 152 |
def user_homedir(self): |
| 153 |
""" the resolved user homedir on the remote """ |
| 154 |
if self._user_homedir: |
| 155 |
return self._user_homedir |
| 156 |
exitcode, stdout, stderr = self.exec_command("/bin/sh -c 'getent passwd $(id -un) | cut -d: -f6'") |
| 157 |
self._user_homedir = to_text(stdout).strip() |
| 158 |
return self._user_homedir |
| 159 |
|
| 160 |
def _resolve_tilde(self, string): |
| 161 |
""" resolve file paths or commands that begin with '~/' to the remote user's homedir """ |
| 162 |
if re.search(r"~\/", string): |
| 163 |
return re.sub(r"~\/", self.user_homedir + r"/", string) |
| 164 |
return string |
| 165 |
|
| 166 |
def exec_command(self, cmd, in_data=None, sudoable=True): |
| 167 |
""" execute a command on the virtual machine host """ |
| 168 |
super(Connection, self).exec_command(cmd, in_data=in_data, sudoable=sudoable) |
| 169 |
|
| 170 |
self._display.vvv(u"EXEC {0}".format(cmd), host=self._host) |
| 171 |
|
| 172 |
cmd_args_list = shlex.split(to_native(cmd, errors='surrogate_or_strict')) |
| 173 |
cmd_args_list = list(map(self._resolve_tilde, cmd_args_list)) |
| 174 |
|
| 175 |
if getattr(self._shell, "_IS_WINDOWS", False): |
| 176 |
# Become method 'runas' is done in the wrapper that is executed, |
| 177 |
# need to disable sudoable so the bare_run is not waiting for a |
| 178 |
# prompt that will not occur |
| 179 |
sudoable = False |
| 180 |
|
| 181 |
# Make sure our first command is to set the console encoding to |
| 182 |
# utf-8, this must be done via chcp to get utf-8 (65001) |
| 183 |
cmd = ' '.join(["chcp.com", "65001", self._shell._SHELL_REDIRECT_ALLNULL, self._shell._SHELL_AND, cmd]) |
| 184 |
|
| 185 |
# Generate powershell commands |
| 186 |
cmd_args_list = self._shell._encode_script(cmd, as_list=True, strict_mode=False, preserve_rc=False) |
| 187 |
|
| 188 |
# TODO(odyssey4me): |
| 189 |
# Implement buffering much like the other connection plugins |
| 190 |
# Implement 'env' for the environment settings |
| 191 |
# Implement 'input-data' for whatever it might be useful for |
| 192 |
request_exec = { |
| 193 |
'execute': 'guest-exec', |
| 194 |
'arguments': { |
| 195 |
'path': cmd_args_list[0], |
| 196 |
'capture-output': True, |
| 197 |
'arg': cmd_args_list[1:] |
| 198 |
} |
| 199 |
} |
| 200 |
request_exec_json = json.dumps(request_exec) |
| 201 |
|
| 202 |
display.vvv(u"GA send: {0}".format(request_exec_json), host=self._host) |
| 203 |
|
| 204 |
# TODO(odyssey4me): |
| 205 |
# Add timeout parameter |
| 206 |
result_exec = json.loads(libvirt_qemu.qemuAgentCommand(self.domain, request_exec_json, 5, 0)) |
| 207 |
|
| 208 |
display.vvv(u"GA return: {0}".format(result_exec), host=self._host) |
| 209 |
|
| 210 |
command_start = time.clock_gettime(time.CLOCK_MONOTONIC) |
| 211 |
|
| 212 |
request_status = { |
| 213 |
'execute': 'guest-exec-status', |
| 214 |
'arguments': { |
| 215 |
'pid': result_exec['return']['pid'] |
| 216 |
} |
| 217 |
} |
| 218 |
request_status_json = json.dumps(request_status) |
| 219 |
|
| 220 |
display.vvv(u"GA send: {0}".format(request_status_json), host=self._host) |
| 221 |
|
| 222 |
# TODO(odyssey4me): |
| 223 |
# Work out a better way to wait until the command has exited |
| 224 |
result_status = json.loads(libvirt_qemu.qemuAgentCommand(self.domain, request_status_json, 5, 0)) |
| 225 |
|
| 226 |
display.vvv(u"GA return: {0}".format(result_status), host=self._host) |
| 227 |
|
| 228 |
while not result_status['return']['exited']: |
| 229 |
# Wait for 5% of the time already elapsed |
| 230 |
sleep_time = (time.clock_gettime(time.CLOCK_MONOTONIC) - command_start) * (5 / 100) |
| 231 |
if sleep_time < 0.0002: |
| 232 |
sleep_time = 0.0002 |
| 233 |
elif sleep_time > 1: |
| 234 |
sleep_time = 1 |
| 235 |
time.sleep(sleep_time) |
| 236 |
result_status = json.loads(libvirt_qemu.qemuAgentCommand(self.domain, request_status_json, 5, 0)) |
| 237 |
|
| 238 |
display.vvv(u"GA return: {0}".format(result_status), host=self._host) |
| 239 |
|
| 240 |
if result_status['return'].get('out-data'): |
| 241 |
stdout = base64.b64decode(result_status['return']['out-data']) |
| 242 |
else: |
| 243 |
stdout = b'' |
| 244 |
|
| 245 |
if result_status['return'].get('err-data'): |
| 246 |
stderr = base64.b64decode(result_status['return']['err-data']) |
| 247 |
else: |
| 248 |
stderr = b'' |
| 249 |
|
| 250 |
# Decode xml from windows |
| 251 |
if getattr(self._shell, "_IS_WINDOWS", False) and stdout.startswith(b"#< CLIXML"): |
| 252 |
stdout = _parse_clixml(stdout) |
| 253 |
|
| 254 |
display.vvv(u"GA stdout: {0}".format(to_text(stdout)), host=self._host) |
| 255 |
display.vvv(u"GA stderr: {0}".format(to_text(stderr)), host=self._host) |
| 256 |
|
| 257 |
return result_status['return']['exitcode'], stdout, stderr |
| 258 |
|
| 259 |
def put_file(self, in_path, out_path): |
| 260 |
''' transfer a file from local to domain ''' |
| 261 |
super(Connection, self).put_file(in_path, out_path) |
| 262 |
out_path = self._resolve_tilde(out_path) |
| 263 |
display.vvv("PUT %s TO %s" % (in_path, out_path), host=self._host) |
| 264 |
|
| 265 |
if not exists(to_bytes(in_path, errors='surrogate_or_strict')): |
| 266 |
raise AnsibleFileNotFound( |
| 267 |
"file or module does not exist: %s" % in_path) |
| 268 |
|
| 269 |
request_handle = { |
| 270 |
'execute': 'guest-file-open', |
| 271 |
'arguments': { |
| 272 |
'path': out_path, |
| 273 |
'mode': 'wb+' |
| 274 |
} |
| 275 |
} |
| 276 |
request_handle_json = json.dumps(request_handle) |
| 277 |
|
| 278 |
display.vvv(u"GA send: {0}".format(request_handle_json), host=self._host) |
| 279 |
|
| 280 |
result_handle = json.loads(libvirt_qemu.qemuAgentCommand(self.domain, request_handle_json, 5, 0)) |
| 281 |
|
| 282 |
display.vvv(u"GA return: {0}".format(result_handle), host=self._host) |
| 283 |
|
| 284 |
# TODO(odyssey4me): |
| 285 |
# Handle exception for file/path IOError |
| 286 |
with open(to_bytes(in_path, errors='surrogate_or_strict'), 'rb') as in_file: |
| 287 |
for chunk in iter(partial(in_file.read, BUFSIZE), b''): |
| 288 |
try: |
| 289 |
request_write = { |
| 290 |
'execute': 'guest-file-write', |
| 291 |
'arguments': { |
| 292 |
'handle': result_handle['return'], |
| 293 |
'buf-b64': base64.b64encode(chunk).decode() |
| 294 |
} |
| 295 |
} |
| 296 |
request_write_json = json.dumps(request_write) |
| 297 |
|
| 298 |
display.vvvvv(u"GA send: {0}".format(request_write_json), host=self._host) |
| 299 |
|
| 300 |
result_write = json.loads(libvirt_qemu.qemuAgentCommand(self.domain, request_write_json, 5, 0)) |
| 301 |
|
| 302 |
display.vvvvv(u"GA return: {0}".format(result_write), host=self._host) |
| 303 |
|
| 304 |
except Exception: |
| 305 |
traceback.print_exc() |
| 306 |
raise AnsibleError("failed to transfer file %s to %s" % (in_path, out_path)) |
| 307 |
|
| 308 |
request_close = { |
| 309 |
'execute': 'guest-file-close', |
| 310 |
'arguments': { |
| 311 |
'handle': result_handle['return'] |
| 312 |
} |
| 313 |
} |
| 314 |
request_close_json = json.dumps(request_close) |
| 315 |
|
| 316 |
display.vvv(u"GA send: {0}".format(request_close_json), host=self._host) |
| 317 |
|
| 318 |
result_close = json.loads(libvirt_qemu.qemuAgentCommand(self.domain, request_close_json, 5, 0)) |
| 319 |
|
| 320 |
display.vvv(u"GA return: {0}".format(result_close), host=self._host) |
| 321 |
|
| 322 |
def fetch_file(self, in_path, out_path): |
| 323 |
''' fetch a file from domain to local ''' |
| 324 |
super(Connection, self).fetch_file(in_path, out_path) |
| 325 |
in_path = self._resolve_tilde(in_path) |
| 326 |
display.vvv("FETCH %s TO %s" % (in_path, out_path), host=self._host) |
| 327 |
|
| 328 |
request_handle = { |
| 329 |
'execute': 'guest-file-open', |
| 330 |
'arguments': { |
| 331 |
'path': in_path, |
| 332 |
'mode': 'r' |
| 333 |
} |
| 334 |
} |
| 335 |
request_handle_json = json.dumps(request_handle) |
| 336 |
|
| 337 |
display.vvv(u"GA send: {0}".format(request_handle_json), host=self._host) |
| 338 |
|
| 339 |
result_handle = json.loads(libvirt_qemu.qemuAgentCommand(self.domain, request_handle_json, 5, 0)) |
| 340 |
|
| 341 |
display.vvv(u"GA return: {0}".format(result_handle), host=self._host) |
| 342 |
|
| 343 |
request_read = { |
| 344 |
'execute': 'guest-file-read', |
| 345 |
'arguments': { |
| 346 |
'handle': result_handle['return'], |
| 347 |
'count': BUFSIZE |
| 348 |
} |
| 349 |
} |
| 350 |
request_read_json = json.dumps(request_read) |
| 351 |
|
| 352 |
display.vvv(u"GA send: {0}".format(request_read_json), host=self._host) |
| 353 |
|
| 354 |
with open(to_bytes(out_path, errors='surrogate_or_strict'), 'wb+') as out_file: |
| 355 |
try: |
| 356 |
result_read = json.loads(libvirt_qemu.qemuAgentCommand(self.domain, request_read_json, 5, 0)) |
| 357 |
display.vvvvv(u"GA return: {0}".format(result_read), host=self._host) |
| 358 |
out_file.write(base64.b64decode(result_read['return']['buf-b64'])) |
| 359 |
while not result_read['return']['eof']: |
| 360 |
result_read = json.loads(libvirt_qemu.qemuAgentCommand(self.domain, request_read_json, 5, 0)) |
| 361 |
display.vvvvv(u"GA return: {0}".format(result_read), host=self._host) |
| 362 |
out_file.write(base64.b64decode(result_read['return']['buf-b64'])) |
| 363 |
|
| 364 |
except Exception: |
| 365 |
traceback.print_exc() |
| 366 |
raise AnsibleError("failed to transfer file %s to %s" % (in_path, out_path)) |
| 367 |
|
| 368 |
request_close = { |
| 369 |
'execute': 'guest-file-close', |
| 370 |
'arguments': { |
| 371 |
'handle': result_handle['return'] |
| 372 |
} |
| 373 |
} |
| 374 |
request_close_json = json.dumps(request_close) |
| 375 |
|
| 376 |
display.vvv(u"GA send: {0}".format(request_close_json), host=self._host) |
| 377 |
|
| 378 |
result_close = json.loads(libvirt_qemu.qemuAgentCommand(self.domain, request_close_json, 5, 0)) |
| 379 |
|
| 380 |
display.vvv(u"GA return: {0}".format(result_close), host=self._host) |
| 381 |
|
| 382 |
def close(self): |
| 383 |
''' terminate the connection; nothing to do here ''' |
| 384 |
super(Connection, self).close() |
| 385 |
self._connected = False |