Debian Codegraph @

ansible_collections/community/general/plugins/connection/zone.py

raw
1 # Based on local.py (c) 2012, Michael DeHaan <[email protected]>
2 # and chroot.py (c) 2013, Maykel Moya <[email protected]>
3 # and jail.py (c) 2013, Michael Scherer <[email protected]>
4 # (c) 2015, Dagobert Michelsen <[email protected]>
5 # (c) 2015, Toshio Kuratomi <[email protected]>
6 # Copyright (c) 2017 Ansible Project
7 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
8 # SPDX-License-Identifier: GPL-3.0-or-later
9
10 from __future__ import annotations
11
12 DOCUMENTATION = r"""
13 author: Ansible Core Team
14 name: zone
15 short_description: Run tasks in a zone instance
16 description:
17 - Run commands or put/fetch files to an existing zone.
18 options:
19 remote_addr:
20 description:
21 - Zone identifier.
22 type: string
23 default: inventory_hostname
24 vars:
25 - name: ansible_host
26 - name: ansible_zone_host
27 """
28
29 import os
30 import os.path
31 import subprocess
32 import traceback
33 from shlex import quote as shlex_quote
34
35 from ansible.errors import AnsibleError
36 from ansible.module_utils.common.process import get_bin_path
37 from ansible.module_utils.common.text.converters import to_bytes
38 from ansible.plugins.connection import BUFSIZE, ConnectionBase
39 from ansible.utils.display import Display
40
41 display = Display()
42
43
44 class Connection(ConnectionBase):
45 """Local zone based connections"""
46
47 transport = "community.general.zone"
48 has_pipelining = True
49 has_tty = False
50
51 def __init__(self, play_context, new_stdin, *args, **kwargs):
52 super().__init__(play_context, new_stdin, *args, **kwargs)
53
54 self.zone = self._play_context.remote_addr
55
56 if os.geteuid() != 0:
57 raise AnsibleError("zone connection requires running as root")
58
59 self.zoneadm_cmd = to_bytes(self._search_executable("zoneadm"))
60 self.zlogin_cmd = to_bytes(self._search_executable("zlogin"))
61
62 if self.zone not in self.list_zones():
63 raise AnsibleError(f"incorrect zone name {self.zone}")
64
65 @staticmethod
66 def _search_executable(executable):
67 try:
68 return get_bin_path(executable)
69 except ValueError as e:
70 raise AnsibleError(f"{executable} command not found in PATH") from e
71
72 def list_zones(self):
73 process = subprocess.Popen(
74 [self.zoneadm_cmd, "list", "-ip"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE
75 )
76
77 zones = []
78 for line in process.stdout.readlines():
79 # 1:work:running:/zones/work:3126dc59-9a07-4829-cde9-a816e4c5040e:native:shared
80 s = line.split(":")
81 if s[1] != "global":
82 zones.append(s[1])
83
84 return zones
85
86 def get_zone_path(self):
87 # solaris10vm# zoneadm -z cswbuild list -p
88 # -:cswbuild:installed:/zones/cswbuild:479f3c4b-d0c6-e97b-cd04-fd58f2c0238e:native:shared
89 process = subprocess.Popen(
90 [self.zoneadm_cmd, "-z", to_bytes(self.zone), "list", "-p"],
91 stdin=subprocess.PIPE,
92 stdout=subprocess.PIPE,
93 stderr=subprocess.PIPE,
94 )
95
96 # stdout, stderr = p.communicate()
97 path = process.stdout.readlines()[0].split(":")[3]
98 return f"{path}/root"
99
100 def _connect(self):
101 """connect to the zone; nothing to do here"""
102 super()._connect()
103 if not self._connected:
104 display.vvv("THIS IS A LOCAL ZONE DIR", host=self.zone)
105 self._connected = True
106
107 def _buffered_exec_command(self, cmd, stdin=subprocess.PIPE):
108 """run a command on the zone. This is only needed for implementing
109 put_file() get_file() so that we don't have to read the whole file
110 into memory.
111
112 compared to exec_command() it looses some niceties like being able to
113 return the process's exit code immediately.
114 """
115 # NOTE: zlogin invokes a shell (just like ssh does) so we do not pass
116 # this through /bin/sh -c here. Instead it goes through the shell
117 # that zlogin selects.
118 local_cmd = [self.zlogin_cmd, self.zone, cmd]
119 local_cmd = map(to_bytes, local_cmd)
120
121 display.vvv(f"EXEC {local_cmd}", host=self.zone)
122 p = subprocess.Popen(local_cmd, shell=False, stdin=stdin, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
123
124 return p
125
126 def exec_command(self, cmd, in_data=None, sudoable=False):
127 """run a command on the zone"""
128 super().exec_command(cmd, in_data=in_data, sudoable=sudoable)
129
130 p = self._buffered_exec_command(cmd)
131
132 stdout, stderr = p.communicate(in_data)
133 return p.returncode, stdout, stderr
134
135 def _prefix_login_path(self, remote_path):
136 """Make sure that we put files into a standard path
137
138 If a path is relative, then we need to choose where to put it.
139 ssh chooses $HOME but we aren't guaranteed that a home dir will
140 exist in any given chroot. So for now we're choosing "/" instead.
141 This also happens to be the former default.
142
143 Can revisit using $HOME instead if it is a problem
144 """
145 if not remote_path.startswith(os.path.sep):
146 remote_path = os.path.join(os.path.sep, remote_path)
147 return os.path.normpath(remote_path)
148
149 def put_file(self, in_path, out_path):
150 """transfer a file from local to zone"""
151 super().put_file(in_path, out_path)
152 display.vvv(f"PUT {in_path} TO {out_path}", host=self.zone)
153
154 out_path = shlex_quote(self._prefix_login_path(out_path))
155 try:
156 with open(in_path, "rb") as in_file:
157 if not os.fstat(in_file.fileno()).st_size:
158 count = " count=0"
159 else:
160 count = ""
161 try:
162 p = self._buffered_exec_command(f"dd of={out_path} bs={BUFSIZE}{count}", stdin=in_file)
163 except OSError as e:
164 raise AnsibleError("jail connection requires dd command in the jail") from e
165 try:
166 stdout, stderr = p.communicate()
167 except Exception as e:
168 traceback.print_exc()
169 raise AnsibleError(f"failed to transfer file {in_path} to {out_path}") from e
170 if p.returncode != 0:
171 raise AnsibleError(f"failed to transfer file {in_path} to {out_path}:\n{stdout}\n{stderr}")
172 except OSError as e:
173 raise AnsibleError(f"file or module does not exist at: {in_path}") from e
174
175 def fetch_file(self, in_path, out_path):
176 """fetch a file from zone to local"""
177 super().fetch_file(in_path, out_path)
178 display.vvv(f"FETCH {in_path} TO {out_path}", host=self.zone)
179
180 in_path = shlex_quote(self._prefix_login_path(in_path))
181 try:
182 p = self._buffered_exec_command(f"dd if={in_path} bs={BUFSIZE}")
183 except OSError as e:
184 raise AnsibleError("zone connection requires dd command in the zone") from e
185
186 with open(out_path, "wb+") as out_file:
187 try:
188 chunk = p.stdout.read(BUFSIZE)
189 while chunk:
190 out_file.write(chunk)
191 chunk = p.stdout.read(BUFSIZE)
192 except Exception as e:
193 traceback.print_exc()
194 raise AnsibleError(f"failed to transfer file {in_path} to {out_path}") from e
195 stdout, stderr = p.communicate()
196 if p.returncode != 0:
197 raise AnsibleError(f"failed to transfer file {in_path} to {out_path}:\n{stdout}\n{stderr}")
198
199 def close(self):
200 """terminate the connection; nothing to do here"""
201 super().close()
202 self._connected = False