| 1 |
# Copyright: (c) 2012, Jan-Piet Mens <jpmens () gmail.com> |
| 2 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 3 |
|
| 4 |
from __future__ import annotations |
| 5 |
|
| 6 |
from collections.abc import MutableMapping, MutableSet, MutableSequence |
| 7 |
from pathlib import Path |
| 8 |
|
| 9 |
import yaml |
| 10 |
|
| 11 |
from ansible import constants as C |
| 12 |
from ansible.release import __version__ as ansible_version |
| 13 |
from ansible.errors import AnsibleError, AnsibleParserError, AnsiblePluginNotFound |
| 14 |
from ansible.module_utils._internal import _no_six |
| 15 |
from ansible.module_utils.common.text.converters import to_native |
| 16 |
from ansible.parsing.plugin_docs import read_docstring |
| 17 |
from ansible.parsing.yaml.loader import AnsibleLoader |
| 18 |
from ansible.utils.display import Display |
| 19 |
from ansible.utils.sentinel import Sentinel |
| 20 |
from ansible._internal._datatag import _tags |
| 21 |
|
| 22 |
_FRAGMENTABLE = ('DOCUMENTATION', 'RETURN') |
| 23 |
display = Display() |
| 24 |
|
| 25 |
|
| 26 |
def merge_fragment(target, source): |
| 27 |
|
| 28 |
for key, value in source.items(): |
| 29 |
if key in target: |
| 30 |
# assumes both structures have same type |
| 31 |
if isinstance(target[key], MutableMapping): |
| 32 |
value.update(target[key]) |
| 33 |
elif isinstance(target[key], MutableSet): |
| 34 |
value.add(target[key]) |
| 35 |
elif isinstance(target[key], MutableSequence): |
| 36 |
value = sorted(frozenset(value + target[key])) |
| 37 |
else: |
| 38 |
raise Exception("Attempt to extend a documentation fragment, invalid type for %s" % key) |
| 39 |
target[key] = value |
| 40 |
|
| 41 |
|
| 42 |
def _process_versions_and_dates(fragment, is_module, return_docs, callback): |
| 43 |
def process_deprecation(deprecation, top_level=False): |
| 44 |
collection_name = 'removed_from_collection' if top_level else 'collection_name' |
| 45 |
if not isinstance(deprecation, MutableMapping): |
| 46 |
return |
| 47 |
if (is_module or top_level) and 'removed_in' in deprecation: # used in module deprecations |
| 48 |
callback(deprecation, 'removed_in', collection_name) |
| 49 |
if 'removed_at_date' in deprecation: |
| 50 |
callback(deprecation, 'removed_at_date', collection_name) |
| 51 |
if not (is_module or top_level) and 'version' in deprecation: # used in plugin option deprecations |
| 52 |
callback(deprecation, 'version', collection_name) |
| 53 |
|
| 54 |
def process_option_specifiers(specifiers): |
| 55 |
for specifier in specifiers: |
| 56 |
if not isinstance(specifier, MutableMapping): |
| 57 |
continue |
| 58 |
if 'version_added' in specifier: |
| 59 |
callback(specifier, 'version_added', 'version_added_collection') |
| 60 |
if isinstance(specifier.get('deprecated'), MutableMapping): |
| 61 |
process_deprecation(specifier['deprecated']) |
| 62 |
|
| 63 |
def process_options(options): |
| 64 |
for option in options.values(): |
| 65 |
if not isinstance(option, MutableMapping): |
| 66 |
continue |
| 67 |
if 'version_added' in option: |
| 68 |
callback(option, 'version_added', 'version_added_collection') |
| 69 |
if not is_module: |
| 70 |
if isinstance(option.get('env'), list): |
| 71 |
process_option_specifiers(option['env']) |
| 72 |
if isinstance(option.get('ini'), list): |
| 73 |
process_option_specifiers(option['ini']) |
| 74 |
if isinstance(option.get('vars'), list): |
| 75 |
process_option_specifiers(option['vars']) |
| 76 |
if isinstance(option.get('deprecated'), MutableMapping): |
| 77 |
process_deprecation(option['deprecated']) |
| 78 |
if isinstance(option.get('suboptions'), MutableMapping): |
| 79 |
process_options(option['suboptions']) |
| 80 |
|
| 81 |
def process_return_values(return_values): |
| 82 |
for return_value in return_values.values(): |
| 83 |
if not isinstance(return_value, MutableMapping): |
| 84 |
continue |
| 85 |
if 'version_added' in return_value: |
| 86 |
callback(return_value, 'version_added', 'version_added_collection') |
| 87 |
if isinstance(return_value.get('contains'), MutableMapping): |
| 88 |
process_return_values(return_value['contains']) |
| 89 |
|
| 90 |
def process_attributes(attributes): |
| 91 |
for attribute in attributes.values(): |
| 92 |
if not isinstance(attribute, MutableMapping): |
| 93 |
continue |
| 94 |
if 'version_added' in attribute: |
| 95 |
callback(attribute, 'version_added', 'version_added_collection') |
| 96 |
|
| 97 |
if not fragment: |
| 98 |
return |
| 99 |
|
| 100 |
if return_docs: |
| 101 |
process_return_values(fragment) |
| 102 |
return |
| 103 |
|
| 104 |
if 'version_added' in fragment: |
| 105 |
callback(fragment, 'version_added', 'version_added_collection') |
| 106 |
if isinstance(fragment.get('deprecated'), MutableMapping): |
| 107 |
process_deprecation(fragment['deprecated'], top_level=True) |
| 108 |
if isinstance(fragment.get('options'), MutableMapping): |
| 109 |
process_options(fragment['options']) |
| 110 |
if isinstance(fragment.get('attributes'), MutableMapping): |
| 111 |
process_attributes(fragment['attributes']) |
| 112 |
|
| 113 |
|
| 114 |
def add_collection_to_versions_and_dates(fragment, collection_name, is_module, return_docs=False): |
| 115 |
def add(options, option, collection_name_field): |
| 116 |
if collection_name_field not in options: |
| 117 |
options[collection_name_field] = collection_name |
| 118 |
|
| 119 |
_process_versions_and_dates(fragment, is_module, return_docs, add) |
| 120 |
|
| 121 |
|
| 122 |
def remove_current_collection_from_versions_and_dates(fragment, collection_name, is_module, return_docs=False): |
| 123 |
def remove(options, option, collection_name_field): |
| 124 |
if options.get(collection_name_field) == collection_name: |
| 125 |
del options[collection_name_field] |
| 126 |
|
| 127 |
_process_versions_and_dates(fragment, is_module, return_docs, remove) |
| 128 |
|
| 129 |
|
| 130 |
class AnsibleFragmentError(AnsibleError): |
| 131 |
pass |
| 132 |
|
| 133 |
|
| 134 |
def add_fragments(doc, filename, fragment_loader, is_module=False, section='DOCUMENTATION'): |
| 135 |
|
| 136 |
if section not in _FRAGMENTABLE: |
| 137 |
raise AnsibleError(f"Invalid fragment section ({section}) passed to render {filename}, it can only be one of {_FRAGMENTABLE!r}") |
| 138 |
|
| 139 |
fragments = doc.pop('extends_documentation_fragment', []) |
| 140 |
|
| 141 |
if isinstance(fragments, str): |
| 142 |
fragments = fragments.split(',') |
| 143 |
|
| 144 |
unknown_fragments = [] |
| 145 |
|
| 146 |
# doc_fragments are allowed to specify a fragment var other than DOCUMENTATION or RETURN |
| 147 |
# with a . separator; this is complicated by collections-hosted doc_fragments that |
| 148 |
# use the same separator. Assume it's collection-hosted normally first, try to load |
| 149 |
# as-specified. If failure, assume the right-most component is a var, split it off, |
| 150 |
# and retry the load. |
| 151 |
for fragment_slug in fragments: |
| 152 |
fragment_name = fragment_slug.strip() |
| 153 |
fragment_var = section |
| 154 |
|
| 155 |
fragment_class = fragment_loader.get(fragment_name) |
| 156 |
if fragment_class is None and '.' in fragment_slug: |
| 157 |
splitname = fragment_slug.rsplit('.', 1) |
| 158 |
fragment_name = splitname[0] |
| 159 |
fragment_var = splitname[1].upper() |
| 160 |
fragment_class = fragment_loader.get(fragment_name) |
| 161 |
|
| 162 |
if fragment_class is None: |
| 163 |
unknown_fragments.append(fragment_slug) |
| 164 |
continue |
| 165 |
|
| 166 |
# trust-tagged source propagates to loaded values; expressions and templates in config require trust |
| 167 |
fragment_yaml = _tags.TrustedAsTemplate().tag(getattr(fragment_class, fragment_var, None)) |
| 168 |
if fragment_yaml is None: |
| 169 |
if fragment_var not in _FRAGMENTABLE: |
| 170 |
# if it's asking for something specific that's missing, that's an error |
| 171 |
unknown_fragments.append(fragment_slug) |
| 172 |
continue |
| 173 |
else: |
| 174 |
fragment_yaml = '{}' # TODO: this is still an error later since we require 'options' below... |
| 175 |
|
| 176 |
fragment = yaml.load(_tags.Origin(path=filename).tag(fragment_yaml), Loader=AnsibleLoader) |
| 177 |
|
| 178 |
real_fragment_name = getattr(fragment_class, 'ansible_name') |
| 179 |
real_collection_name = '.'.join(real_fragment_name.split('.')[0:2]) if '.' in real_fragment_name else '' |
| 180 |
add_collection_to_versions_and_dates(fragment, real_collection_name, is_module=is_module, return_docs=(section == 'RETURN')) |
| 181 |
|
| 182 |
if section == 'DOCUMENTATION': |
| 183 |
# notes, seealso, options and attributes entries are specifically merged, but only occur in documentation section |
| 184 |
for doc_key in ['notes', 'seealso']: |
| 185 |
if doc_key in fragment: |
| 186 |
entries = fragment.pop(doc_key) |
| 187 |
if entries: |
| 188 |
if doc_key not in doc: |
| 189 |
doc[doc_key] = [] |
| 190 |
doc[doc_key].extend(entries) |
| 191 |
|
| 192 |
if 'options' not in fragment and 'attributes' not in fragment: |
| 193 |
raise AnsibleFragmentError("missing options or attributes in fragment (%s), possibly misformatted?: %s" % (fragment_name, filename)) |
| 194 |
|
| 195 |
# ensure options themselves are directly merged |
| 196 |
for doc_key in ['options', 'attributes']: |
| 197 |
if doc_key in fragment: |
| 198 |
if doc_key in doc: |
| 199 |
try: |
| 200 |
merge_fragment(doc[doc_key], fragment.pop(doc_key)) |
| 201 |
except Exception as e: |
| 202 |
raise AnsibleFragmentError("%s %s (%s) of unknown type: %s" % (to_native(e), doc_key, fragment_name, filename)) |
| 203 |
else: |
| 204 |
doc[doc_key] = fragment.pop(doc_key) |
| 205 |
|
| 206 |
# merge rest of the sections |
| 207 |
try: |
| 208 |
merge_fragment(doc, fragment) |
| 209 |
except Exception as e: |
| 210 |
raise AnsibleFragmentError("%s (%s) of unknown type: %s" % (to_native(e), fragment_name, filename)) |
| 211 |
|
| 212 |
if unknown_fragments: |
| 213 |
raise AnsibleFragmentError('unknown doc_fragment(s) in file {0}: {1}'.format(filename, to_native(', '.join(unknown_fragments)))) |
| 214 |
|
| 215 |
|
| 216 |
def get_docstring(filename, fragment_loader, verbose=False, ignore_errors=False, collection_name=None, is_module=Sentinel, plugin_type=None): |
| 217 |
""" |
| 218 |
DOCUMENTATION can be extended using documentation fragments loaded by the PluginLoader from the doc_fragments plugins. |
| 219 |
""" |
| 220 |
|
| 221 |
if is_module is Sentinel: |
| 222 |
is_module = None |
| 223 |
else: |
| 224 |
display.deprecated( |
| 225 |
msg="The is_module argument is deprecated.", |
| 226 |
version="2.25", |
| 227 |
help_text="Use plugin_type='module' instead.", |
| 228 |
) |
| 229 |
if is_module is None: |
| 230 |
if plugin_type is None: |
| 231 |
is_module = False |
| 232 |
else: |
| 233 |
is_module = (plugin_type == 'module') |
| 234 |
|
| 235 |
data = read_docstring(filename, verbose=verbose, ignore_errors=ignore_errors) |
| 236 |
|
| 237 |
if data.get('doc', False): |
| 238 |
# add collection name to versions and dates |
| 239 |
if collection_name is not None: |
| 240 |
add_collection_to_versions_and_dates(data['doc'], collection_name, is_module=is_module) |
| 241 |
|
| 242 |
# add fragments to documentation |
| 243 |
add_fragments(data['doc'], filename, fragment_loader=fragment_loader, is_module=is_module, section='DOCUMENTATION') |
| 244 |
|
| 245 |
if data.get('returndocs', False): |
| 246 |
# add collection name to versions and dates |
| 247 |
if collection_name is not None: |
| 248 |
add_collection_to_versions_and_dates(data['returndocs'], collection_name, is_module=is_module, return_docs=True) |
| 249 |
|
| 250 |
# add fragments to return |
| 251 |
add_fragments(data['returndocs'], filename, fragment_loader=fragment_loader, is_module=is_module, section='RETURN') |
| 252 |
|
| 253 |
return data['doc'], data['plainexamples'], data['returndocs'], data['metadata'] |
| 254 |
|
| 255 |
|
| 256 |
def get_versioned_doclink(path): |
| 257 |
""" |
| 258 |
returns a versioned documentation link for the current Ansible major.minor version; used to generate |
| 259 |
in-product warning/error links to the configured DOCSITE_ROOT_URL |
| 260 |
(eg, https://docs.ansible.com/ansible/2.8/somepath/doc.html) |
| 261 |
|
| 262 |
:param path: relative path to a document under docs/docsite/rst; |
| 263 |
:return: absolute URL to the specified doc for the current version of Ansible |
| 264 |
""" |
| 265 |
path = to_native(path) |
| 266 |
try: |
| 267 |
base_url = C.config.get_config_value('DOCSITE_ROOT_URL') |
| 268 |
if not base_url.endswith('/'): |
| 269 |
base_url += '/' |
| 270 |
if path.startswith('/'): |
| 271 |
path = path[1:] |
| 272 |
split_ver = ansible_version.split('.') |
| 273 |
if len(split_ver) < 3: |
| 274 |
raise RuntimeError('invalid version ({0})'.format(ansible_version)) |
| 275 |
|
| 276 |
doc_version = '{0}.{1}'.format(split_ver[0], split_ver[1]) |
| 277 |
|
| 278 |
# check to see if it's a X.Y.0 non-rc prerelease or dev release, if so, assume devel (since the X.Y doctree |
| 279 |
# isn't published until beta-ish) |
| 280 |
if split_ver[2].startswith('0'): |
| 281 |
# exclude rc; we should have the X.Y doctree live by rc1 |
| 282 |
if any((pre in split_ver[2]) for pre in ['a', 'b']) or len(split_ver) > 3 and 'dev' in split_ver[3]: |
| 283 |
doc_version = 'devel' |
| 284 |
|
| 285 |
return '{0}{1}/{2}'.format(base_url, doc_version, path) |
| 286 |
except Exception as ex: |
| 287 |
return '(unable to create versioned doc link for path {0}: {1})'.format(path, to_native(ex)) |
| 288 |
|
| 289 |
|
| 290 |
def _find_adjacent(path, plugin, extensions): |
| 291 |
|
| 292 |
adjacent = Path(path) |
| 293 |
|
| 294 |
plugin_base_name = plugin.split('.')[-1] |
| 295 |
if adjacent.stem != plugin_base_name: |
| 296 |
# this should only affect filters/tests |
| 297 |
adjacent = adjacent.with_name(plugin_base_name) |
| 298 |
|
| 299 |
paths = [] |
| 300 |
for ext in extensions: |
| 301 |
candidate = adjacent.with_suffix(ext) |
| 302 |
if candidate == adjacent: |
| 303 |
# we're looking for an adjacent file, skip this since it's identical |
| 304 |
continue |
| 305 |
if candidate.exists(): |
| 306 |
paths.append(to_native(candidate)) |
| 307 |
|
| 308 |
return paths |
| 309 |
|
| 310 |
|
| 311 |
def find_plugin_docfile(plugin, plugin_type, loader): |
| 312 |
""" if the plugin lives in a non-python file (eg, win_X.ps1), require the corresponding 'sidecar' file for docs """ |
| 313 |
|
| 314 |
context = loader.find_plugin_with_context(plugin, ignore_deprecated=False, check_aliases=True) |
| 315 |
if (not context or not context.resolved) and plugin_type in ('filter', 'test'): |
| 316 |
# should only happen for filters/test |
| 317 |
plugin_obj, context = loader.get_with_context(plugin) |
| 318 |
|
| 319 |
if not context or not context.resolved: |
| 320 |
raise AnsiblePluginNotFound('%s was not found' % (plugin), plugin_load_context=context) |
| 321 |
|
| 322 |
docfile = Path(context.plugin_resolved_path) |
| 323 |
if docfile.suffix not in C.DOC_EXTENSIONS: |
| 324 |
# only look for adjacent if plugin file does not support documents |
| 325 |
filenames = _find_adjacent(docfile, plugin, C.DOC_EXTENSIONS) |
| 326 |
filename = filenames[0] if filenames else None |
| 327 |
else: |
| 328 |
filename = to_native(docfile) |
| 329 |
|
| 330 |
if filename is None: |
| 331 |
raise AnsibleError('%s cannot contain DOCUMENTATION nor does it have a companion documentation file' % (plugin)) |
| 332 |
|
| 333 |
return filename, context |
| 334 |
|
| 335 |
|
| 336 |
def get_plugin_docs(plugin, plugin_type, loader, fragment_loader, verbose): |
| 337 |
|
| 338 |
# find plugin doc file, if it doesn't exist this will throw error, we let it through |
| 339 |
# can raise exception and short circuit when 'not found' |
| 340 |
filename, context = find_plugin_docfile(plugin, plugin_type, loader) |
| 341 |
collection_name = context.plugin_resolved_collection |
| 342 |
|
| 343 |
try: |
| 344 |
docs = get_docstring( |
| 345 |
filename=filename, |
| 346 |
fragment_loader=fragment_loader, |
| 347 |
verbose=verbose, |
| 348 |
collection_name=collection_name, |
| 349 |
plugin_type=plugin_type, |
| 350 |
) |
| 351 |
except Exception as ex: |
| 352 |
raise AnsibleParserError(f'{plugin_type} plugin {plugin!r} did not contain a DOCUMENTATION attribute in {filename!r}.') from ex |
| 353 |
|
| 354 |
# no good? try adjacent |
| 355 |
if not docs[0]: |
| 356 |
for newfile in _find_adjacent(filename, plugin, C.DOC_EXTENSIONS): |
| 357 |
try: |
| 358 |
docs = get_docstring( |
| 359 |
filename=newfile, |
| 360 |
fragment_loader=fragment_loader, |
| 361 |
verbose=verbose, |
| 362 |
collection_name=collection_name, |
| 363 |
plugin_type=plugin_type, |
| 364 |
) |
| 365 |
filename = newfile |
| 366 |
if docs[0] is not None: |
| 367 |
break |
| 368 |
except Exception as ex: |
| 369 |
raise AnsibleParserError(f'{plugin_type} plugin {plugin!r} adjacent file did not contain a DOCUMENTATION attribute in {filename!r}.') from ex |
| 370 |
|
| 371 |
# add extra data to docs[0] (aka 'DOCUMENTATION') |
| 372 |
if docs[0] is None: |
| 373 |
raise AnsibleParserError(f'No documentation available for {plugin_type} plugin {plugin!r} in {filename!r}.') |
| 374 |
|
| 375 |
docs[0]['filename'] = filename |
| 376 |
docs[0]['collection'] = collection_name |
| 377 |
docs[0]['plugin_name'] = context.resolved_fqcn |
| 378 |
|
| 379 |
return docs |
| 380 |
|
| 381 |
|
| 382 |
def __getattr__(importable_name): |
| 383 |
return _no_six.deprecate(importable_name, __name__, "string_types") |