Debian Codegraph @

ansible_collections/amazon/aws/plugins/plugin_utils/ssm/filetransfermanager.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright: Contributors to the Ansible project
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from typing import Any
7 from typing import Callable
8 from typing import Dict
9 from typing import Optional
10
11 from ansible.errors import AnsibleError
12 from ansible.module_utils.common.text.converters import to_bytes
13
14 from ansible_collections.amazon.aws.plugins.plugin_utils.ssm.common import CommandResult
15 from ansible_collections.amazon.aws.plugins.plugin_utils.ssm.common import ssm_retry
16
17
18 class FileTransferManager:
19 """Manages file transfers using S3 as an intermediary."""
20
21 def __init__(
22 self,
23 bucket_name: str,
24 instance_id: str,
25 s3_client,
26 reconnection_retries: int,
27 verbosity_display: Callable[[int, str], None],
28 close: Callable[[], None],
29 exec_command: Callable[[str, Optional[bool], Optional[bool]], CommandResult],
30 ):
31 """
32 Initializes the FileTransferManager with a given connection.
33
34 :param connection: The connection object used for S3 and remote execution.
35 """
36 self.bucket_name = bucket_name
37 self.instance_id = instance_id
38 self.s3_client = s3_client
39 self.reconnection_retries = reconnection_retries
40 self.verbosity_display = verbosity_display
41 self.close = close
42 self.exec_command = exec_command
43
44 @ssm_retry
45 def _file_transport_command(
46 self,
47 in_path: str,
48 out_path: str,
49 ssm_action: str,
50 command: str,
51 put_args: Dict[str, Any],
52 s3_path: str,
53 ) -> CommandResult:
54 """
55 Transfers files to or from a remote host using S3.
56
57 :param in_path: The local path of the file to be transferred.
58 :param out_path: The remote path where the file should be placed.
59 :param ssm_action: The action to perform, either 'get' (download) or 'put' (upload).
60 :param command: A shell command string
61 :param put_args: Additional arguments for S3 upload.
62 :param s3_path: The S3 path where the file is stored.
63 :return: A CommandResult dictionary containing execution results.
64 """
65 try:
66 if ssm_action == "get":
67 return self._handle_get(in_path, out_path, command, s3_path)
68 return self._handle_put(in_path, out_path, command, s3_path, put_args)
69 finally:
70 self.s3_client.delete_object(Bucket=self.bucket_name, Key=s3_path)
71
72 def _handle_get(self, in_path: str, out_path: str, command: str, s3_path: str) -> CommandResult:
73 """
74 Handles downloading a file from the remote host via S3.
75
76 :param in_path: The local destination path for the file.
77 :param out_path: The remote source path of the file.
78 :param commands: The transport commands to execute.
79 :param s3_path: The S3 path where the file is stored.
80 :return: A CommandResult dictionary containing execution results.
81 """
82
83 result = self._exec_transport_commands(in_path, out_path, command)
84 with open(to_bytes(out_path, errors="surrogate_or_strict"), "wb") as data:
85 self.s3_client.download_fileobj(self.bucket_name, s3_path, data)
86
87 return result
88
89 def _handle_put(
90 self, in_path: str, out_path: str, command: str, s3_path: str, put_args: Dict[str, Any]
91 ) -> CommandResult:
92 """
93 Handles uploading a file to the remote host via S3.
94
95 :param in_path: The local source path of the file.
96 :param out_path: The remote destination path for the file.
97 :param commands: The transport commands to execute.
98 :param s3_path: The S3 path where the file will be stored.
99 :param put_args: Additional arguments for S3 upload.
100 :return: A CommandResult dictionary containing execution results.
101 """
102
103 with open(to_bytes(in_path, errors="surrogate_or_strict"), "rb") as data:
104 self.s3_client.upload_fileobj(data, self.bucket_name, s3_path, ExtraArgs=put_args)
105
106 result = self._exec_transport_commands(in_path, out_path, command)
107
108 return result
109
110 def _exec_transport_commands(self, in_path: str, out_path: str, command: str) -> CommandResult:
111 """
112 Executes the provided transport commands.
113
114 :param in_path: The input path.
115 :param out_path: The output path.
116 :param commands: A list of command dictionaries containing the command string and metadata.
117 :return: A CommandResult dictionary containing execution results.
118 """
119 returncode, stdout, stderr = self.exec_command(command, in_data=None, sudoable=False)
120
121 # Check the return code
122 if returncode != 0:
123 raise AnsibleError(f"failed to transfer file to {in_path} {out_path}:\n{stdout}\n{stderr}")
124
125 return {"returncode": returncode, "stdout": stdout, "stderr": stderr}