Debian Codegraph @

ansible_collections/kubernetes/core/plugins/module_utils/copy.py

raw symbols SCIP
1 # Copyright [2021] [Red Hat, Inc.]
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15
16 from __future__ import absolute_import, division, print_function
17
18 __metaclass__ = type
19
20 import os
21 import tarfile
22 from abc import ABCMeta, abstractmethod
23 from select import select
24 from tempfile import NamedTemporaryFile, TemporaryFile
25
26 from ansible.module_utils.common.text.converters import to_native
27
28 # from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import AnsibleModule
29 from ansible_collections.kubernetes.core.plugins.module_utils.k8s.exceptions import (
30 CoreException,
31 )
32
33 try:
34 from kubernetes.client.api import core_v1_api
35 from kubernetes.stream import stream
36 from kubernetes.stream.ws_client import (
37 ABNF,
38 ERROR_CHANNEL,
39 STDERR_CHANNEL,
40 STDOUT_CHANNEL,
41 )
42 except ImportError:
43 pass
44
45 try:
46 import yaml
47 except ImportError:
48 # ImportError are managed by the common module already.
49 pass
50
51
52 class K8SCopy(metaclass=ABCMeta):
53 def __init__(self, module, client):
54 self.client = client
55 self.module = module
56 self.api_instance = core_v1_api.CoreV1Api(client.client)
57
58 self.local_path = module.params.get("local_path")
59 self.name = module.params.get("pod")
60 self.namespace = module.params.get("namespace")
61 self.remote_path = module.params.get("remote_path")
62 self.content = module.params.get("content")
63
64 self.no_preserve = module.params.get("no_preserve")
65 self.container_arg = {}
66 if module.params.get("container"):
67 self.container_arg["container"] = module.params.get("container")
68 self.check_mode = self.module.check_mode
69
70 def _run_from_pod(self, cmd):
71 try:
72 resp = stream(
73 self.api_instance.connect_get_namespaced_pod_exec,
74 self.name,
75 self.namespace,
76 command=cmd,
77 async_req=False,
78 stderr=True,
79 stdin=False,
80 stdout=True,
81 tty=False,
82 _preload_content=False,
83 **self.container_arg,
84 )
85
86 stderr, stdout = [], []
87 while resp.is_open():
88 resp.update(timeout=1)
89 if resp.peek_stdout():
90 stdout.extend(resp.read_stdout().rstrip("\n").split("\n"))
91 if resp.peek_stderr():
92 stderr.extend(resp.read_stderr().rstrip("\n").split("\n"))
93 error = resp.read_channel(ERROR_CHANNEL)
94 resp.close()
95 error = yaml.safe_load(error)
96 return error, stdout, stderr
97 except Exception as e:
98 self.module.fail_json(
99 msg="Error while running/parsing from pod {0}/{1} command='{2}' : {3}".format(
100 self.namespace, self.name, cmd, to_native(e)
101 )
102 )
103
104 def is_directory_path_from_pod(self, file_path, failed_if_not_exists=True):
105 # check if file exists
106 error, out, err = self._run_from_pod(cmd=["test", "-e", file_path])
107 if error.get("status") != "Success":
108 if failed_if_not_exists:
109 return None, "%s does not exist in remote pod filesystem" % file_path
110 return False, None
111 error, out, err = self._run_from_pod(cmd=["test", "-d", file_path])
112 return error.get("status") == "Success", None
113
114 @abstractmethod
115 def run(self):
116 pass
117
118
119 class K8SCopyFromPod(K8SCopy):
120 """
121 Copy files/directory from Pod into local filesystem
122 """
123
124 def __init__(self, module, client):
125 super(K8SCopyFromPod, self).__init__(module, client)
126 self.is_remote_path_dir = None
127 self.files_to_copy = []
128 self._shellname = None
129
130 @property
131 def pod_shell(self):
132 if self._shellname is None:
133 for s in ("/bin/sh", "/bin/bash"):
134 error, out, err = self._run_from_pod(s)
135 if error.get("status") == "Success":
136 self._shellname = s
137 break
138 return self._shellname
139
140 def listfiles_with_find(self, path):
141 find_cmd = ["find", path, "-type", "f"]
142 error, files, err = self._run_from_pod(cmd=find_cmd)
143 if error.get("status") != "Success":
144 self.module.fail_json(msg=error.get("message"))
145 return files
146
147 def listfile_with_echo(self, path):
148 echo_cmd = [
149 self.pod_shell,
150 "-c",
151 "echo {path}/* {path}/.*".format(
152 path=path.translate(str.maketrans({" ": r"\ "}))
153 ),
154 ]
155 error, out, err = self._run_from_pod(cmd=echo_cmd)
156 if error.get("status") != "Success":
157 self.module.fail_json(msg=error.get("message"))
158
159 files = []
160 if out:
161 output = out[0] + " "
162 files = [
163 os.path.join(path, p[:-1])
164 for p in output.split(f"{path}/")
165 if p and p[:-1] not in (".", "..")
166 ]
167
168 result = []
169 for f in files:
170 is_dir, err = self.is_directory_path_from_pod(f)
171 if err:
172 continue
173 if not is_dir:
174 result.append(f)
175 continue
176 result += self.listfile_with_echo(f)
177 return result
178
179 def list_remote_files(self):
180 """
181 This method will check if the remote path is a dir or file
182 if it is a directory the file list will be updated accordingly
183 """
184 # check is remote path exists and is a file or directory
185 is_dir, error = self.is_directory_path_from_pod(self.remote_path)
186 if error:
187 self.module.fail_json(msg=error)
188
189 if not is_dir:
190 return [self.remote_path]
191 else:
192 # find executable to list dir with
193 executables = dict(
194 find=self.listfiles_with_find,
195 echo=self.listfile_with_echo,
196 )
197 for item in executables:
198 error, out, err = self._run_from_pod(item)
199 if error.get("status") == "Success":
200 return executables.get(item)(self.remote_path)
201
202 def read(self):
203 self.stdout = None
204 self.stderr = None
205
206 if self.response.is_open():
207 if not self.response.sock.connected:
208 self.response._connected = False
209 else:
210 ret, out, err = select((self.response.sock.sock,), (), (), 0)
211 if ret:
212 code, frame = self.response.sock.recv_data_frame(True)
213 if code == ABNF.OPCODE_CLOSE:
214 self.response._connected = False
215 elif (
216 code in (ABNF.OPCODE_BINARY, ABNF.OPCODE_TEXT)
217 and len(frame.data) > 1
218 ):
219 channel = frame.data[0]
220 content = frame.data[1:]
221 if content:
222 if channel == STDOUT_CHANNEL:
223 self.stdout = content
224 elif channel == STDERR_CHANNEL:
225 self.stderr = content.decode("utf-8", "replace")
226
227 def copy(self):
228 is_remote_path_dir = (
229 len(self.files_to_copy) > 1 or self.files_to_copy[0] != self.remote_path
230 )
231 relpath_start = self.remote_path
232 if is_remote_path_dir and os.path.isdir(self.local_path):
233 relpath_start = os.path.dirname(self.remote_path)
234
235 if not self.check_mode:
236 for remote_file in self.files_to_copy:
237 dest_file = self.local_path
238 if is_remote_path_dir:
239 dest_file = os.path.join(
240 self.local_path,
241 os.path.relpath(remote_file, start=relpath_start),
242 )
243 # create directory to copy file in
244 os.makedirs(os.path.dirname(dest_file), exist_ok=True)
245
246 pod_command = ["cat", remote_file]
247 self.response = stream(
248 self.api_instance.connect_get_namespaced_pod_exec,
249 self.name,
250 self.namespace,
251 command=pod_command,
252 stderr=True,
253 stdin=True,
254 stdout=True,
255 tty=False,
256 _preload_content=False,
257 **self.container_arg,
258 )
259 errors = []
260 with open(dest_file, "wb") as fh:
261 while self.response._connected:
262 self.read()
263 if self.stdout:
264 fh.write(self.stdout)
265 if self.stderr:
266 errors.append(self.stderr)
267 if errors:
268 self.module.fail_json(
269 msg="Failed to copy file from Pod: {0}".format("".join(errors))
270 )
271 self.module.exit_json(
272 changed=True,
273 result="{0} successfully copied locally into {1}".format(
274 self.remote_path, self.local_path
275 ),
276 )
277
278 def run(self):
279 self.files_to_copy = self.list_remote_files()
280 if self.files_to_copy == []:
281 # Using warn method instead of passing warnings to exit_json as it is
282 # deprecated in ansible-core>=2.19.0
283 self._module.warn(
284 "No file found from directory '{0}' into remote Pod.".format(
285 self.remote_path
286 )
287 )
288 self.module.exit_json(
289 changed=False,
290 )
291 self.copy()
292
293
294 class K8SCopyToPod(K8SCopy):
295 """
296 Copy files/directory from local filesystem into remote Pod
297 """
298
299 def __init__(self, module, client):
300 super(K8SCopyToPod, self).__init__(module, client)
301 self.files_to_copy = list()
302
303 def close_temp_file(self):
304 if self.named_temp_file:
305 self.named_temp_file.close()
306
307 def run(self):
308 # remove trailing slash from destination path
309 dest_file = self.remote_path.rstrip("/")
310 src_file = self.local_path
311 self.named_temp_file = None
312 if self.content:
313 self.named_temp_file = NamedTemporaryFile(mode="w")
314 self.named_temp_file.write(self.content)
315 self.named_temp_file.flush()
316 src_file = self.named_temp_file.name
317 else:
318 if not os.path.exists(self.local_path):
319 self.module.fail_json(
320 msg="{0} does not exist in local filesystem".format(self.local_path)
321 )
322 if not os.access(self.local_path, os.R_OK):
323 self.module.fail_json(msg="{0} not readable".format(self.local_path))
324
325 is_dir, err = self.is_directory_path_from_pod(
326 self.remote_path, failed_if_not_exists=False
327 )
328 if err:
329 self.module.fail_json(msg=err)
330 if is_dir:
331 if self.content:
332 self.module.fail_json(
333 msg="When content is specified, remote path should not be an existing directory"
334 )
335 else:
336 dest_file = os.path.join(dest_file, os.path.basename(src_file))
337
338 if not self.check_mode:
339 if self.no_preserve:
340 tar_command = [
341 "tar",
342 "--no-same-permissions",
343 "--no-same-owner",
344 "-xmf",
345 "-",
346 ]
347 else:
348 tar_command = ["tar", "-xmf", "-"]
349
350 if dest_file.startswith("/"):
351 tar_command.extend(["-C", "/"])
352
353 response = stream(
354 self.api_instance.connect_get_namespaced_pod_exec,
355 self.name,
356 self.namespace,
357 command=tar_command,
358 stderr=True,
359 stdin=True,
360 stdout=True,
361 tty=False,
362 _preload_content=False,
363 **self.container_arg,
364 )
365 with TemporaryFile() as tar_buffer:
366 with tarfile.open(fileobj=tar_buffer, mode="w") as tar:
367 tar.add(src_file, dest_file)
368 tar_buffer.seek(0)
369 commands = []
370 # push command in chunk mode
371 size = 1024 * 1024
372 while True:
373 data = tar_buffer.read(size)
374 if not data:
375 break
376 commands.append(data)
377
378 stderr, stdout = [], []
379 while response.is_open():
380 if response.peek_stdout():
381 stdout.append(response.read_stdout().rstrip("\n"))
382 if response.peek_stderr():
383 stderr.append(response.read_stderr().rstrip("\n"))
384 if commands:
385 cmd = commands.pop(0)
386 response.write_stdin(cmd)
387 else:
388 break
389 response.close()
390 if stderr:
391 self.close_temp_file()
392 self.module.fail_json(
393 command=tar_command,
394 msg="Failed to copy local file/directory into Pod due to: {0}".format(
395 "".join(stderr)
396 ),
397 )
398 self.close_temp_file()
399 if self.content:
400 self.module.exit_json(
401 changed=True,
402 result="Content successfully copied into {0} on remote Pod".format(
403 self.remote_path
404 ),
405 )
406 self.module.exit_json(
407 changed=True,
408 result="{0} successfully copied into remote Pod into {1}".format(
409 self.local_path, self.remote_path
410 ),
411 )
412
413
414 def check_pod(svc):
415 module = svc.module
416 namespace = module.params.get("namespace")
417 name = module.params.get("pod")
418 container = module.params.get("container")
419
420 try:
421 resource = svc.find_resource("Pod", None, True)
422 except CoreException as e:
423 module.fail_json(msg=to_native(e))
424
425 def _fail(exc):
426 arg = {}
427 if hasattr(exc, "body"):
428 msg = (
429 "Namespace={0} Kind=Pod Name={1}: Failed requested object: {2}".format(
430 namespace, name, exc.body
431 )
432 )
433 else:
434 msg = to_native(exc)
435 for attr in ["status", "reason"]:
436 if hasattr(exc, attr):
437 arg[attr] = getattr(exc, attr)
438 module.fail_json(msg=msg, **arg)
439
440 try:
441 result = svc.client.get(resource, name=name, namespace=namespace)
442 containers = dict(
443 {
444 c["name"]: c
445 for cl in ["initContainerStatuses", "containerStatuses"]
446 for c in result.to_dict()["status"].get(cl, [])
447 }
448 )
449 if container and container not in containers.keys():
450 module.fail_json(msg="Pod has no container {0}".format(container))
451 if (
452 container
453 and container in containers
454 and not bool(containers[container].get("started", False))
455 ):
456 module.fail_json(msg="Pod container {0} is not started".format(container))
457 return containers.keys()
458 except Exception as exc:
459 _fail(exc)