Debian Codegraph @

lib/ansible/galaxy/role.py

raw
1 ########################################################################
2 #
3 # (C) 2015, Brian Coca <[email protected]>
4 #
5 # This file is part of Ansible
6 #
7 # Ansible is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Ansible is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
19 #
20 ########################################################################
21
22 from __future__ import annotations
23
24 import errno
25 import datetime
26 import os
27 import tarfile
28 import tempfile
29
30 from collections.abc import MutableSequence
31 from shutil import rmtree
32
33 from ansible import context
34 from ansible.errors import AnsibleError, AnsibleParserError
35 from ansible.galaxy.api import GalaxyAPI
36 from ansible.galaxy.user_agent import user_agent
37 from ansible.module_utils.common.text.converters import to_native, to_text
38 from ansible.module_utils.common.yaml import yaml_dump, yaml_load
39 from ansible.module_utils.compat.version import LooseVersion
40 from ansible.module_utils.urls import open_url
41 from ansible.playbook.role.requirement import RoleRequirement
42 from ansible.utils.display import Display
43 from ansible.utils.path import is_subpath, unfrackpath
44
45 display = Display()
46
47
48 class GalaxyRole(object):
49
50 SUPPORTED_SCMS = set(['git', 'hg'])
51 META_MAIN = (os.path.join('meta', 'main.yml'), os.path.join('meta', 'main.yaml'))
52 META_INSTALL = os.path.join('meta', '.galaxy_install_info')
53 META_REQUIREMENTS = (os.path.join('meta', 'requirements.yml'), os.path.join('meta', 'requirements.yaml'))
54 ROLE_DIRS = ('defaults', 'files', 'handlers', 'meta', 'tasks', 'templates', 'vars', 'tests')
55
56 def __init__(self, galaxy, api, name, src=None, version=None, scm=None, path=None):
57
58 self._metadata = None
59 self._metadata_dependencies = None
60 self._requirements = None
61 self._install_info = None
62 self._validate_certs = not context.CLIARGS['ignore_certs']
63
64 display.debug('Validate TLS certificates: %s' % self._validate_certs)
65
66 self.galaxy = galaxy
67 self._api = api
68
69 self.name = name
70 self.version = version
71 self.src = src or name
72 self.download_url = None
73 self.scm = scm
74 self.paths = [os.path.join(x, self.name) for x in galaxy.roles_paths]
75
76 if path is not None:
77 if not path.endswith(os.path.join(os.path.sep, self.name)):
78 path = os.path.join(path, self.name)
79 else:
80 # Look for a meta/main.ya?ml inside the potential role dir in case
81 # the role name is the same as parent directory of the role.
82 #
83 # Example:
84 # ./roles/testing/testing/meta/main.yml
85 for meta_main in self.META_MAIN:
86 if os.path.exists(os.path.join(path, name, meta_main)):
87 path = os.path.join(path, self.name)
88 break
89 self.path = path
90 else:
91 # use the first path by default
92 self.path = self.paths[0]
93
94 def __repr__(self):
95 """
96 Returns "rolename (version)" if version is not null
97 Returns "rolename" otherwise
98 """
99 if self.version:
100 return "%s (%s)" % (self.name, self.version)
101 else:
102 return self.name
103
104 def __eq__(self, other):
105 return self.name == other.name
106
107 @property
108 def api(self):
109 if not isinstance(self._api, GalaxyAPI):
110 return self._api.api
111 return self._api
112
113 @property
114 def metadata(self):
115 """
116 Returns role metadata
117 """
118 if self._metadata is None:
119 for path in self.paths:
120 for meta_main in self.META_MAIN:
121 meta_path = os.path.join(path, meta_main)
122 if os.path.isfile(meta_path):
123 try:
124 with open(meta_path, 'r') as f:
125 self._metadata = yaml_load(f)
126 except Exception:
127 display.vvvvv("Unable to load metadata for %s" % self.name)
128 return False
129 break
130
131 return self._metadata
132
133 @property
134 def metadata_dependencies(self):
135 """
136 Returns a list of dependencies from role metadata
137 """
138 if self._metadata_dependencies is None:
139 self._metadata_dependencies = []
140
141 if self.metadata is not None:
142 self._metadata_dependencies = self.metadata.get('dependencies') or []
143
144 if not isinstance(self._metadata_dependencies, MutableSequence):
145 raise AnsibleParserError(
146 f"Expected role dependencies to be a list. Role {self} has meta/main.yml with dependencies {self._metadata_dependencies}"
147 )
148
149 return self._metadata_dependencies
150
151 @property
152 def install_info(self):
153 """
154 Returns role install info
155 """
156 if self._install_info is None:
157
158 info_path = os.path.join(self.path, self.META_INSTALL)
159 if os.path.isfile(info_path):
160 try:
161 with open(info_path, 'r') as f:
162 self._install_info = yaml_load(f)
163 except Exception:
164 display.vvvvv("Unable to load Galaxy install info for %s" % self.name)
165 return False
166 return self._install_info
167
168 @property
169 def _exists(self):
170 for path in self.paths:
171 if os.path.isdir(path):
172 return True
173
174 return False
175
176 def _write_galaxy_install_info(self):
177 """
178 Writes a YAML-formatted file to the role's meta/ directory
179 (named .galaxy_install_info) which contains some information
180 we can use later for commands like 'list' and 'info'.
181 """
182
183 info = dict(
184 version=self.version,
185 install_date=datetime.datetime.now(datetime.timezone.utc).strftime("%c"),
186 )
187 if not os.path.exists(os.path.join(self.path, 'meta')):
188 os.makedirs(os.path.join(self.path, 'meta'))
189 info_path = os.path.join(self.path, self.META_INSTALL)
190 with open(info_path, 'w+') as f:
191 try:
192 self._install_info = yaml_dump(info, f)
193 except Exception:
194 return False
195
196 return True
197
198 def remove(self):
199 """
200 Removes the specified role from the roles path.
201 There is a sanity check to make sure there's a meta/main.yml file at this
202 path so the user doesn't blow away random directories.
203 """
204 if self.metadata:
205 try:
206 rmtree(self.path)
207 return True
208 except Exception:
209 pass
210
211 return False
212
213 def fetch(self, role_data):
214 """
215 Downloads the archived role to a temp location based on role data
216 """
217 if role_data:
218
219 # first grab the file and save it to a temp location
220 if self.download_url is not None:
221 archive_url = self.download_url
222 elif "github_user" in role_data and "github_repo" in role_data:
223 archive_url = 'https://github.com/%s/%s/archive/%s.tar.gz' % (role_data["github_user"], role_data["github_repo"], self.version)
224 else:
225 archive_url = self.src
226
227 display.display("- downloading role from %s" % archive_url)
228
229 try:
230 url_file = open_url(archive_url, validate_certs=self._validate_certs, http_agent=user_agent(), timeout=60)
231 temp_file = tempfile.NamedTemporaryFile(delete=False)
232 data = url_file.read()
233 while data:
234 temp_file.write(data)
235 data = url_file.read()
236 temp_file.close()
237 return temp_file.name
238 except Exception as e:
239 display.error(u"failed to download the file: %s" % to_text(e))
240
241 return False
242
243 def install(self):
244
245 if self.scm:
246 # create tar file from scm url
247 tmp_file = RoleRequirement.scm_archive_role(keep_scm_meta=context.CLIARGS['keep_scm_meta'], **self.spec)
248 elif self.src:
249 if os.path.isfile(self.src):
250 tmp_file = self.src
251 elif '://' in self.src:
252 role_data = self.src
253 tmp_file = self.fetch(role_data)
254 else:
255 role_data = self.api.lookup_role_by_name(self.src)
256 if not role_data:
257 raise AnsibleError("- sorry, %s was not found on %s." % (self.src, self.api.api_server))
258
259 if role_data.get('role_type') == 'APP':
260 # Container Role
261 display.warning("%s is a Container App role, and should only be installed using Ansible "
262 "Container" % self.name)
263
264 role_versions = self.api.fetch_role_related('versions', role_data['id'])
265 if not self.version:
266 # convert the version names to LooseVersion objects
267 # and sort them to get the latest version. If there
268 # are no versions in the list, we'll grab the head
269 # of the master branch
270 if len(role_versions) > 0:
271 loose_versions = [v for a in role_versions if (v := LooseVersion()) and v.parse(a.get('name') or '') is None]
272 try:
273 loose_versions.sort()
274 except TypeError:
275 raise AnsibleError(
276 'Unable to compare role versions (%s) to determine the most recent version due to incompatible version formats. '
277 'Please contact the role author to resolve versioning conflicts, or specify an explicit role version to '
278 'install.' % ', '.join([v.vstring for v in loose_versions])
279 )
280 self.version = to_text(loose_versions[-1])
281 elif role_data.get('github_branch', None):
282 self.version = role_data['github_branch']
283 else:
284 self.version = 'master'
285 elif self.version != 'master':
286 if role_versions and to_text(self.version) not in [a.get('name', None) for a in role_versions]:
287 raise AnsibleError("- the specified version (%s) of %s was not found in the list of available versions (%s)." % (self.version,
288 self.name,
289 role_versions))
290
291 # check if there's a source link/url for our role_version
292 for role_version in role_versions:
293 if role_version['name'] == self.version and 'source' in role_version:
294 self.src = role_version['source']
295 if role_version['name'] == self.version and 'download_url' in role_version:
296 self.download_url = role_version['download_url']
297
298 tmp_file = self.fetch(role_data)
299
300 else:
301 raise AnsibleError("No valid role data found")
302
303 if tmp_file:
304
305 display.debug("installing from %s" % tmp_file)
306
307 if not tarfile.is_tarfile(tmp_file):
308 raise AnsibleError("the downloaded file does not appear to be a valid tar archive.")
309 else:
310 role_tar_file = tarfile.open(tmp_file, "r")
311 # verify the role's meta file
312 meta_file = None
313 members = role_tar_file.getmembers()
314 # next find the metadata file
315 for member in members:
316 for meta_main in self.META_MAIN:
317 if meta_main in member.name:
318 # Look for parent of meta/main.yml
319 # Due to possibility of sub roles each containing meta/main.yml
320 # look for shortest length parent
321 meta_parent_dir = os.path.dirname(os.path.dirname(member.name))
322 if not meta_file:
323 archive_parent_dir = meta_parent_dir
324 meta_file = member
325 else:
326 if len(meta_parent_dir) < len(archive_parent_dir):
327 archive_parent_dir = meta_parent_dir
328 meta_file = member
329 if not meta_file:
330 raise AnsibleError("this role does not appear to have a meta/main.yml file.")
331 else:
332 try:
333 self._metadata = yaml_load(role_tar_file.extractfile(meta_file))
334 except Exception:
335 raise AnsibleError("this role does not appear to have a valid meta/main.yml file.")
336
337 paths = self.paths
338 if self.path != paths[0]:
339 # path can be passed though __init__
340 # FIXME should this be done in __init__?
341 paths[:0] = self.path
342 paths_len = len(paths)
343 for idx, path in enumerate(paths):
344 self.path = path
345 display.display("- extracting %s to %s" % (self.name, self.path))
346 try:
347 if os.path.exists(self.path):
348 if not os.path.isdir(self.path):
349 raise AnsibleError("the specified roles path exists and is not a directory.")
350 elif not context.CLIARGS.get("force", False):
351 raise AnsibleError("the specified role %s appears to already exist. Use --force to replace it." % self.name)
352 else:
353 # using --force, remove the old path
354 if not self.remove():
355 raise AnsibleError("%s doesn't appear to contain a role.\n please remove this directory manually if you really "
356 "want to put the role here." % self.path)
357 else:
358 os.makedirs(self.path)
359
360 resolved_archive = unfrackpath(archive_parent_dir, follow=False)
361
362 # We strip off any higher-level directories for all of the files
363 # contained within the tar file here. The default is 'github_repo-target'.
364 # Gerrit instances, on the other hand, does not have a parent directory at all.
365 for member in members:
366 # we only extract files, and remove any relative path
367 # bits that might be in the file for security purposes
368 # and drop any containing directory, as mentioned above
369 if not (member.isreg() or member.issym()):
370 continue
371
372 for attr in ('name', 'linkname'):
373 if not (attr_value := getattr(member, attr, None)):
374 continue
375
376 if attr == 'linkname':
377 # Symlinks are relative to the link
378 relative_to = os.path.dirname(getattr(member, 'name', ''))
379 else:
380 # Normalize paths that start with the archive dir
381 attr_value = attr_value.replace(archive_parent_dir, "", 1)
382 attr_value = os.path.join(*attr_value.split(os.sep)) # remove leading os.sep
383 relative_to = ''
384
385 full_path = os.path.join(resolved_archive, relative_to, attr_value)
386 if not is_subpath(full_path, resolved_archive, real=True):
387 err = f"Invalid {attr} for tarfile member: path {full_path} is not a subpath of the role {resolved_archive}"
388 raise AnsibleError(err)
389
390 relative_path_dir = os.path.join(resolved_archive, relative_to)
391 relative_path = os.path.join(*full_path.replace(relative_path_dir, "", 1).split(os.sep))
392 setattr(member, attr, relative_path)
393
394 role_tar_file.extract(member, to_native(self.path), filter='data')
395
396 # write out the install info file for later use
397 self._write_galaxy_install_info()
398 break
399 except OSError as e:
400 if e.errno == errno.EACCES and idx < paths_len - 1:
401 continue
402 raise AnsibleError("Could not update files in %s: %s" % (self.path, to_native(e)))
403
404 # return the parsed yaml metadata
405 display.display("- %s was installed successfully" % str(self))
406 if not (self.src and os.path.isfile(self.src)):
407 try:
408 os.unlink(tmp_file)
409 except OSError as ex:
410 display.error_as_warning(f"Unable to remove tmp file {tmp_file!r}.", exception=ex)
411 return True
412
413 return False
414
415 @property
416 def spec(self):
417 """
418 Returns role spec info
419 {
420 'scm': 'git',
421 'src': 'http://git.example.com/repos/repo.git',
422 'version': 'v1.0',
423 'name': 'repo'
424 }
425 """
426 return dict(scm=self.scm, src=self.src, version=self.version, name=self.name)
427
428 @property
429 def requirements(self):
430 """
431 Returns role requirements
432 """
433 if self._requirements is None:
434 self._requirements = []
435 for meta_requirements in self.META_REQUIREMENTS:
436 meta_path = os.path.join(self.path, meta_requirements)
437 if os.path.isfile(meta_path):
438 try:
439 with open(meta_path, 'r') as f:
440 self._requirements = yaml_load(f)
441 except Exception:
442 display.vvvvv("Unable to load requirements for %s" % self.name)
443
444 break
445
446 if not isinstance(self._requirements, MutableSequence):
447 raise AnsibleParserError(f"Expected role dependencies to be a list. Role {self} has meta/requirements.yml {self._requirements}")
448
449 return self._requirements