Debian Codegraph @

ansible_collections/community/libvirt/plugins/connection/libvirt_lxc.py

raw
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 - Michael Scherer (@mscherer) <[email protected]>
15 name: libvirt_lxc
16 short_description: Run tasks in lxc containers via libvirt
17 description:
18 - Run commands or put/fetch files to an existing lxc container using libvirt.
19 options:
20 remote_addr:
21 description:
22 - Container identifier.
23 default: The set user as per docker's configuration
24 vars:
25 - name: ansible_host
26 - name: ansible_libvirt_lxc_host
27 libvirt_lxc_noseclabel:
28 description:
29 - "This setting causes libvirt to connect to LXC containers by passing ``--noseclabel`` parameter to ``virsh`` command."
30 - This is necessary when running on systems which do not have SELinux.
31 default: False
32 version_added: '1.4.0'
33 type: boolean
34 ini:
35 - section: selinux
36 key: 'libvirt_lxc_noseclabel'
37 env:
38 - name: ANSIBLE_LIBVIRT_LXC_NOSECLABEL
39 vars:
40 - name: ansible_libvirt_lxc_noseclabel
41 '''
42
43 import os
44 import os.path
45 import subprocess
46 import traceback
47
48 from ansible import constants as C
49 from ansible.errors import AnsibleError
50 from ansible.module_utils.six.moves import shlex_quote
51 from ansible.module_utils.common.process import get_bin_path
52 from ansible.module_utils._text import to_bytes
53 from ansible.plugins.connection import ConnectionBase, BUFSIZE
54 from ansible.utils.display import Display
55
56 display = Display()
57
58
59 class Connection(ConnectionBase):
60 ''' Local lxc based connections '''
61
62 transport = 'community.general.libvirt_lxc'
63 has_pipelining = True
64 # su currently has an undiagnosed issue with calculating the file
65 # checksums (so copy, for instance, doesn't work right)
66 # Have to look into that before re-enabling this
67 default_user = 'root'
68 has_tty = False
69
70 def __init__(self, play_context, new_stdin, *args, **kwargs):
71 super(Connection, self).__init__(play_context, new_stdin, *args, **kwargs)
72 self.lxc = self._play_context.remote_addr
73
74 self.virsh = self._search_executable('virsh')
75
76 self._check_domain(self.lxc)
77
78 def _search_executable(self, executable):
79 try:
80 return get_bin_path(executable)
81 except ValueError:
82 raise AnsibleError("%s command not found in PATH") % executable
83
84 def _check_domain(self, domain):
85 p = subprocess.Popen([self.virsh, '-q', '-c', 'lxc:///', 'dominfo', to_bytes(domain)],
86 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
87 p.communicate()
88 if p.returncode:
89 raise AnsibleError("%s is not a lxc defined in libvirt" % domain)
90
91 def _connect(self):
92 ''' connect to the lxc; nothing to do here '''
93 super(Connection, self)._connect()
94 if not self._connected:
95 display.vvv("THIS IS A LOCAL LXC DIR", host=self.lxc)
96 self._connected = True
97
98 def _buffered_exec_command(self, cmd, stdin=subprocess.PIPE):
99 ''' run a command on the chroot. This is only needed for implementing
100 put_file() get_file() so that we don't have to read the whole file
101 into memory.
102
103 compared to exec_command() it looses some niceties like being able to
104 return the process's exit code immediately.
105 '''
106 executable = C.DEFAULT_EXECUTABLE.split()[0] if C.DEFAULT_EXECUTABLE else '/bin/sh'
107 local_cmd = [self.virsh, '-q', '-c', 'lxc:///', 'lxc-enter-namespace']
108
109 if self.get_option("libvirt_lxc_noseclabel"):
110 local_cmd += ['--noseclabel']
111
112 local_cmd += [self.lxc, '--', executable, '-c', cmd]
113
114 display.vvv("EXEC %s" % (local_cmd,), host=self.lxc)
115 local_cmd = [to_bytes(i, errors='surrogate_or_strict') for i in local_cmd]
116 p = subprocess.Popen(local_cmd, shell=False, stdin=stdin,
117 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
118
119 return p
120
121 def exec_command(self, cmd, in_data=None, sudoable=False):
122 ''' run a command on the chroot '''
123 super(Connection, self).exec_command(cmd, in_data=in_data, sudoable=sudoable)
124
125 p = self._buffered_exec_command(cmd)
126
127 stdout, stderr = p.communicate(in_data)
128 return (p.returncode, stdout, stderr)
129
130 def _prefix_login_path(self, remote_path):
131 ''' Make sure that we put files into a standard path
132
133 If a path is relative, then we need to choose where to put it.
134 ssh chooses $HOME but we aren't guaranteed that a home dir will
135 exist in any given chroot. So for now we're choosing "/" instead.
136 This also happens to be the former default.
137
138 Can revisit using $HOME instead if it's a problem
139 '''
140 if not remote_path.startswith(os.path.sep):
141 remote_path = os.path.join(os.path.sep, remote_path)
142 return os.path.normpath(remote_path)
143
144 def put_file(self, in_path, out_path):
145 ''' transfer a file from local to lxc '''
146 super(Connection, self).put_file(in_path, out_path)
147 display.vvv("PUT %s TO %s" % (in_path, out_path), host=self.lxc)
148
149 out_path = shlex_quote(self._prefix_login_path(out_path))
150 try:
151 with open(to_bytes(in_path, errors='surrogate_or_strict'), 'rb') as in_file:
152 if not os.fstat(in_file.fileno()).st_size:
153 count = ' count=0'
154 else:
155 count = ''
156 try:
157 p = self._buffered_exec_command('dd of=%s bs=%s%s' % (out_path, BUFSIZE, count), stdin=in_file)
158 except OSError:
159 raise AnsibleError("chroot connection requires dd command in the chroot")
160 try:
161 stdout, stderr = p.communicate()
162 except Exception:
163 traceback.print_exc()
164 raise AnsibleError("failed to transfer file %s to %s" % (in_path, out_path))
165 if p.returncode != 0:
166 raise AnsibleError("failed to transfer file %s to %s:\n%s\n%s" % (in_path, out_path, stdout, stderr))
167 except IOError:
168 raise AnsibleError("file or module does not exist at: %s" % in_path)
169
170 def fetch_file(self, in_path, out_path):
171 ''' fetch a file from lxc to local '''
172 super(Connection, self).fetch_file(in_path, out_path)
173 display.vvv("FETCH %s TO %s" % (in_path, out_path), host=self.lxc)
174
175 in_path = shlex_quote(self._prefix_login_path(in_path))
176 try:
177 p = self._buffered_exec_command('dd if=%s bs=%s' % (in_path, BUFSIZE))
178 except OSError:
179 raise AnsibleError("chroot connection requires dd command in the chroot")
180
181 with open(to_bytes(out_path, errors='surrogate_or_strict'), 'wb+') as out_file:
182 try:
183 chunk = p.stdout.read(BUFSIZE)
184 while chunk:
185 out_file.write(chunk)
186 chunk = p.stdout.read(BUFSIZE)
187 except Exception:
188 traceback.print_exc()
189 raise AnsibleError("failed to transfer file %s to %s" % (in_path, out_path))
190 stdout, stderr = p.communicate()
191 if p.returncode != 0:
192 raise AnsibleError("failed to transfer file %s to %s:\n%s\n%s" % (in_path, out_path, stdout, stderr))
193
194 def close(self):
195 ''' terminate the connection; nothing to do here '''
196 super(Connection, self).close()
197 self._connected = False