Debian Codegraph @

lib/ansible/utils/display.py

raw
1 # (c) 2014, Michael DeHaan <[email protected]>
2 #
3 # This file is part of Ansible
4 #
5 # Ansible is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Ansible is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
17
18 from __future__ import annotations
19
20 import contextlib
21
22 from ansible.module_utils.secrets import register_secret, mask_secrets
23
24 try:
25 import curses
26 except ImportError:
27 HAS_CURSES = False
28 else:
29 # this will be set to False if curses.setupterm() fails
30 HAS_CURSES = True
31
32 import collections.abc as c
33 import codecs
34 import ctypes.util
35 import fcntl
36 import getpass
37 import io
38 import logging
39 import os
40 import secrets
41 import subprocess
42 import sys
43 import termios
44 import threading
45 import time
46 import tty
47 import typing as t
48
49 from functools import wraps
50 from struct import unpack, pack
51
52 from ansible import constants as C
53 from ansible.constants import config
54 from ansible.errors import AnsibleAssertionError, AnsiblePromptInterrupt, AnsiblePromptNoninteractive, AnsibleError
55 from ansible._internal._errors import _error_utils, _error_factory
56 from ansible._internal import _display_utils
57 from ansible.module_utils._internal import _deprecator, _messages, _no_six
58 from ansible.module_utils.common.text.converters import to_bytes, to_text
59 from ansible.module_utils.datatag import deprecator_from_collection_name
60 from ansible._internal._datatag._tags import TrustedAsTemplate
61 from ansible.module_utils._internal import _traceback, _errors
62 from ansible.utils.color import stringc
63 from ansible.utils.multiprocessing import context as multiprocessing_context
64 from ansible.utils.singleton import Singleton
65
66 if t.TYPE_CHECKING:
67 # avoid circular import at runtime
68 from ansible.executor.task_queue_manager import FinalQueue
69
70 _LIBC = ctypes.cdll.LoadLibrary(ctypes.util.find_library('c'))
71 # Set argtypes, to avoid segfault if the wrong type is provided,
72 # restype is assumed to be c_int
73 _LIBC.wcwidth.argtypes = (ctypes.c_wchar,)
74 _LIBC.wcswidth.argtypes = (ctypes.c_wchar_p, ctypes.c_int)
75 # Max for c_int
76 _MAX_INT = 2 ** (ctypes.sizeof(ctypes.c_int) * 8 - 1) - 1
77
78 MOVE_TO_BOL = b'\r'
79 CLEAR_TO_EOL = b'\x1b[K'
80
81
82 def _is_controller_traceback_enabled(event: _traceback.TracebackEvent) -> bool:
83 """Controller utility function to determine if traceback collection is enabled for the specified event."""
84 flag_values: set[str] = set(value for value in C.config.get_config_value('DISPLAY_TRACEBACK'))
85
86 if 'always' in flag_values:
87 return True
88
89 if 'never' in flag_values:
90 return False
91
92 if _traceback.TracebackEvent.DEPRECATED_VALUE.name.lower() in flag_values:
93 flag_values.add(_traceback.TracebackEvent.DEPRECATED.name.lower()) # DEPRECATED_VALUE implies DEPRECATED
94
95 return event.name.lower() in flag_values
96
97
98 _traceback._is_traceback_enabled = _is_controller_traceback_enabled
99
100
101 def _deprecation_warnings_enabled() -> bool:
102 """Return True if deprecation warnings are enabled for the current calling context, otherwise False."""
103 # DTFIX-FUTURE: move this capability into config using an AmbientContext-derived TaskContext (once it exists)
104 if warning_ctx := _display_utils.DeferredWarningContext.current(optional=True):
105 variables = warning_ctx._variables
106 else:
107 variables = None
108
109 return C.config.get_config_value('DEPRECATION_WARNINGS', variables=variables)
110
111
112 def get_text_width(text: str) -> int:
113 """Function that utilizes ``wcswidth`` or ``wcwidth`` to determine the
114 number of columns used to display a text string.
115
116 We try first with ``wcswidth``, and fallback to iterating each
117 character and using wcwidth individually, falling back to a value of 0
118 for non-printable wide characters.
119 """
120 if not isinstance(text, str):
121 raise TypeError('get_text_width requires text, not %s' % type(text))
122
123 try:
124 width = _LIBC.wcswidth(text, _MAX_INT)
125 except ctypes.ArgumentError:
126 width = -1
127 if width != -1:
128 return width
129
130 width = 0
131 counter = 0
132 for c in text:
133 counter += 1
134 if c in (u'\x08', u'\x7f', u'\x94', u'\x1b'):
135 # A few characters result in a subtraction of length:
136 # BS, DEL, CCH, ESC
137 # ESC is slightly different in that it's part of an escape sequence, and
138 # while ESC is non printable, it's part of an escape sequence, which results
139 # in a single non printable length
140 width -= 1
141 counter -= 1
142 continue
143
144 try:
145 w = _LIBC.wcwidth(c)
146 except ctypes.ArgumentError:
147 w = -1
148 if w == -1:
149 # -1 signifies a non-printable character
150 # use 0 here as a best effort
151 w = 0
152 width += w
153
154 if width == 0 and counter:
155 raise EnvironmentError(
156 'get_text_width could not calculate text width of %r' % text
157 )
158
159 # It doesn't make sense to have a negative printable width
160 return width if width >= 0 else 0
161
162
163 class FilterDenyList(logging.Filter):
164 def __init__(self, denylist):
165 self.denylist = [logging.Filter(name) for name in denylist]
166
167 def filter(self, record):
168 return not any(f.filter(record) for f in self.denylist)
169
170
171 class FilterUserInjector(logging.Filter):
172 """
173 This is a filter which injects the current user as the 'user' attribute on each record. We need to add this filter
174 to all logger handlers so that 3rd party libraries won't print an exception due to user not being defined.
175 """
176
177 try:
178 username = getpass.getuser()
179 except OSError:
180 # people like to make containers w/o actual valid passwd/shadow and use host uids
181 username = 'uid=%s' % os.getuid()
182
183 def filter(self, record):
184 record.user = FilterUserInjector.username
185 return True
186
187
188 logger = None
189 # TODO: make this a callback event instead
190 if getattr(C, 'DEFAULT_LOG_PATH'):
191 path = C.DEFAULT_LOG_PATH
192 if path and (os.path.exists(path) and os.access(path, os.W_OK)) or os.access(os.path.dirname(path), os.W_OK):
193 if not os.path.isdir(path):
194 # NOTE: level is kept at INFO to avoid security disclosures caused by certain libraries when using DEBUG
195 logging.basicConfig(filename=path, level=logging.INFO, # DO NOT set to logging.DEBUG
196 format='%(asctime)s p=%(process)d u=%(user)s n=%(name)s %(levelname)s| %(message)s')
197
198 logger = logging.getLogger('ansible')
199 for handler in logging.root.handlers:
200 handler.addFilter(FilterDenyList(getattr(C, 'DEFAULT_LOG_FILTER', [])))
201 handler.addFilter(FilterUserInjector())
202 else:
203 print(f"[WARNING]: DEFAULT_LOG_PATH can not be a directory '{path}', aborting", file=sys.stderr)
204 else:
205 print(f"[WARNING]: log file at '{path}' is not writeable and we cannot create it, aborting\n", file=sys.stderr)
206
207 # map color to log levels, in order of priority (low to high)
208 color_to_log_level = {C.COLOR_DEBUG: logging.DEBUG,
209 C.COLOR_VERBOSE: logging.INFO,
210 C.COLOR_OK: logging.INFO,
211 C.COLOR_INCLUDED: logging.INFO,
212 C.COLOR_CHANGED: logging.INFO,
213 C.COLOR_SKIP: logging.WARNING,
214 C.COLOR_DEPRECATE: logging.WARNING,
215 C.COLOR_WARN: logging.WARNING,
216 C.COLOR_UNREACHABLE: logging.ERROR,
217 C.COLOR_ERROR: logging.ERROR}
218
219 b_COW_PATHS = (
220 b"/usr/bin/cowsay",
221 b"/usr/games/cowsay",
222 b"/usr/local/bin/cowsay", # BSD path for cowsay
223 b"/opt/local/bin/cowsay", # MacPorts path for cowsay
224 )
225
226
227 def _synchronize_textiowrapper(tio: t.TextIO, lock: threading.RLock):
228 """
229 This decorator ensures that the supplied RLock is held before invoking the wrapped methods.
230 It is intended to prevent background threads from holding the Python stdout/stderr buffer lock on a file object during a fork.
231 Since background threads are abandoned in child forks, locks they hold are orphaned in a locked state.
232 Attempts to acquire an orphaned lock in this state will block forever, effectively hanging the child process on stdout/stderr writes.
233 The shared lock is permanently disabled immediately after a fork.
234 This prevents hangs in early post-fork code (e.g., stdio writes from pydevd, coverage, etc.) before user code has resumed and released the lock.
235 """
236
237 def _wrap_with_lock(f, lock):
238 def disable_lock():
239 nonlocal lock
240 lock = contextlib.nullcontext()
241
242 os.register_at_fork(after_in_child=disable_lock)
243
244 @wraps(f)
245 def locking_wrapper(*args, **kwargs):
246 with lock:
247 return f(*args, **kwargs)
248
249 return locking_wrapper
250
251 buffer = tio.buffer
252
253 # monkeypatching the underlying file-like object isn't great, but likely safer than subclassing
254 buffer.write = _wrap_with_lock(buffer.write, lock) # type: ignore[method-assign]
255 buffer.flush = _wrap_with_lock(buffer.flush, lock) # type: ignore[method-assign]
256
257
258 def setraw(fd: int, when: int = termios.TCSAFLUSH) -> None:
259 """Put terminal into a raw mode.
260
261 Copied from ``tty`` from CPython 3.11.0, and modified to not remove OPOST from OFLAG
262
263 OPOST is kept to prevent an issue with multi line prompts from being corrupted now that display
264 is proxied via the queue from forks. The problem is a race condition, in that we proxy the display
265 over the fork, but before it can be displayed, this plugin will have continued executing, potentially
266 setting stdout and stdin to raw which remove output post processing that commonly converts NL to CRLF
267 """
268 mode = termios.tcgetattr(fd)
269 mode[tty.IFLAG] = mode[tty.IFLAG] & ~(termios.BRKINT | termios.ICRNL | termios.INPCK | termios.ISTRIP | termios.IXON)
270 mode[tty.OFLAG] = mode[tty.OFLAG] & ~(termios.OPOST)
271 mode[tty.CFLAG] = mode[tty.CFLAG] & ~(termios.CSIZE | termios.PARENB)
272 mode[tty.CFLAG] = mode[tty.CFLAG] | termios.CS8
273 mode[tty.LFLAG] = mode[tty.LFLAG] & ~(termios.ECHO | termios.ICANON | termios.IEXTEN | termios.ISIG)
274 mode[tty.CC][termios.VMIN] = 1
275 mode[tty.CC][termios.VTIME] = 0
276 termios.tcsetattr(fd, when, mode)
277
278
279 def clear_line(stdout: t.BinaryIO) -> None:
280 stdout.write(b'\x1b[%s' % MOVE_TO_BOL)
281 stdout.write(b'\x1b[%s' % CLEAR_TO_EOL)
282
283
284 def setup_prompt(stdin_fd: int, stdout_fd: int, seconds: int, echo: bool) -> None:
285 setraw(stdin_fd)
286
287 # Only set stdout to raw mode if it is a TTY. This is needed when redirecting
288 # stdout to a file since a file cannot be set to raw mode.
289 if os.isatty(stdout_fd):
290 setraw(stdout_fd)
291
292 if echo:
293 new_settings = termios.tcgetattr(stdin_fd)
294 new_settings[3] = new_settings[3] | termios.ECHO
295 termios.tcsetattr(stdin_fd, termios.TCSANOW, new_settings)
296
297
298 def setupterm() -> None:
299 # Nest the try except since curses.error is not available if curses did not import
300 try:
301 curses.setupterm()
302 except (curses.error, TypeError, io.UnsupportedOperation):
303 global HAS_CURSES
304 HAS_CURSES = False
305 else:
306 global MOVE_TO_BOL
307 global CLEAR_TO_EOL
308 # curses.tigetstr() returns None in some circumstances
309 MOVE_TO_BOL = curses.tigetstr('cr') or MOVE_TO_BOL
310 CLEAR_TO_EOL = curses.tigetstr('el') or CLEAR_TO_EOL
311
312
313 class Display(metaclass=Singleton):
314
315 def __init__(self, verbosity: int = 0) -> None:
316
317 self._final_q: FinalQueue | None = None
318
319 # NB: this lock is used to both prevent intermingled output between threads and to block writes during forks.
320 # Do not change the type of this lock or upgrade to a shared lock (eg multiprocessing.RLock).
321 self._lock = threading.RLock()
322
323 self.columns = None
324 self.verbosity = verbosity
325
326 if C.LOG_VERBOSITY is None:
327 self.log_verbosity = verbosity
328 else:
329 self.log_verbosity = max(verbosity, C.LOG_VERBOSITY)
330
331 # list of all deprecation messages to prevent duplicate display
332 self._deprecations: set[str] = set()
333 self._warns: set[str] = set()
334 self._errors: set[str] = set()
335
336 self.b_cowsay: bytes | None = None
337 self.noncow = C.ANSIBLE_COW_SELECTION
338
339 self.set_cowsay_info()
340
341 if self.b_cowsay:
342 try:
343 cmd = subprocess.Popen([self.b_cowsay, "-l"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
344 (out, err) = cmd.communicate()
345 if cmd.returncode:
346 raise Exception
347 self.cows_available: set[str] = {to_text(c) for c in out.split()}
348 if C.ANSIBLE_COW_ACCEPTLIST and any(C.ANSIBLE_COW_ACCEPTLIST):
349 self.cows_available = set(C.ANSIBLE_COW_ACCEPTLIST).intersection(self.cows_available)
350 except Exception:
351 # could not execute cowsay for some reason
352 self.b_cowsay = None
353
354 self._set_column_width()
355
356 try:
357 # NB: we're relying on the display singleton behavior to ensure this only runs once
358 _synchronize_textiowrapper(sys.stdout, self._lock)
359 _synchronize_textiowrapper(sys.stderr, self._lock)
360 except Exception as ex:
361 self.warning(f"failed to patch stdout/stderr for fork-safety: {ex}")
362
363 codecs.register_error('_replacing_warning_handler', self._replacing_warning_handler)
364 try:
365 sys.stdout.reconfigure(errors='_replacing_warning_handler') # type: ignore[union-attr]
366 sys.stderr.reconfigure(errors='_replacing_warning_handler') # type: ignore[union-attr]
367 except Exception as ex:
368 self.warning(f"failed to reconfigure stdout/stderr with custom encoding error handler: {ex}")
369
370 self.setup_curses = False
371
372 def _replacing_warning_handler(self, exception: UnicodeError) -> tuple[str | bytes, int]:
373 # This can't be removed as long as we have the possibility of encountering un-renderable strings
374 # created with `surrogateescape`; the alternative of having display methods hard fail is untenable.
375 self.warning('Non UTF-8 encoded data replaced with "?" while displaying text to stdout/stderr.')
376 return '?', exception.end
377
378 def set_queue(self, queue: FinalQueue) -> None:
379 """Set the _final_q on Display, so that we know to proxy display over the queue
380 instead of directly writing to stdout/stderr from forks
381
382 This is only needed in ansible.executor.process.worker:WorkerProcess._run
383 """
384 if multiprocessing_context.parent_process() is None:
385 raise RuntimeError('queue cannot be set in parent process')
386 self._final_q = queue
387
388 def set_cowsay_info(self) -> None:
389 if C.ANSIBLE_NOCOWS:
390 return
391
392 if C.ANSIBLE_COW_PATH:
393 self.b_cowsay = C.ANSIBLE_COW_PATH
394 else:
395 for b_cow_path in b_COW_PATHS:
396 if os.path.exists(b_cow_path):
397 self.b_cowsay = b_cow_path
398
399 @staticmethod
400 def _proxy[**P](
401 func: c.Callable[t.Concatenate[Display, P], None]
402 ) -> c.Callable[..., None]:
403 @wraps(func)
404 def wrapper(self, *args: P.args, **kwargs: P.kwargs) -> None:
405 if self._final_q:
406 # If _final_q is set, that means we are in a WorkerProcess
407 # and instead of displaying messages directly from the fork
408 # we will proxy them through the queue
409 return self._final_q.send_display(func.__name__, *args, **kwargs)
410 return func(self, *args, **kwargs)
411 return wrapper
412
413 @staticmethod
414 def _meets_debug(
415 func: c.Callable[..., None]
416 ) -> c.Callable[..., None]:
417 """This method ensures that debug is enabled before delegating to the proxy
418 """
419 @wraps(func)
420 def wrapper(self, msg: str, host: str | None = None) -> None:
421 if not C.DEFAULT_DEBUG:
422 return
423 return func(self, msg, host=host)
424 return wrapper
425
426 @staticmethod
427 def _meets_verbosity(
428 func: c.Callable[..., None]
429 ) -> c.Callable[..., None]:
430 """This method ensures the verbosity has been met before delegating to the proxy
431
432 Currently this method is unused, and the logic is handled directly in ``verbose``
433 """
434 @wraps(func)
435 def wrapper(self, msg: str, host: str | None = None, caplevel: int = None) -> None:
436 if self.verbosity > caplevel:
437 return func(self, msg, host=host, caplevel=caplevel)
438 return
439 return wrapper
440
441 @_proxy
442 def display(
443 self,
444 msg: str,
445 color: str | None = None,
446 stderr: bool = False,
447 screen_only: bool = False,
448 log_only: bool = False,
449 newline: bool = True,
450 caplevel: int | None = None,
451 ) -> None:
452 """ Display a message to the user
453
454 Note: msg *must* be a unicode string to prevent UnicodeError tracebacks.
455 """
456
457 if not isinstance(msg, str):
458 raise TypeError(f'Display message must be str, not: {msg.__class__.__name__}')
459
460 msg = mask_secrets(msg)
461
462 # Convert Windows newlines to Unix newlines.
463 # Some environments, such as Azure Pipelines, render `\r` as an additional `\n`.
464 msg = msg.replace('\r\n', '\n')
465
466 nocolor = msg
467
468 if not log_only:
469
470 has_newline = msg.endswith(u'\n')
471 if has_newline:
472 msg2 = msg[:-1]
473 else:
474 msg2 = msg
475
476 if color:
477 msg2 = stringc(msg2, color)
478
479 if has_newline or newline:
480 msg2 = msg2 + u'\n'
481
482 # Note: After Display() class is refactored need to update the log capture
483 # code in 'cli/scripts/ansible_connection_cli_stub.py' (and other relevant places).
484 if not stderr:
485 fileobj = sys.stdout
486 else:
487 fileobj = sys.stderr
488
489 with self._lock:
490 fileobj.write(msg2)
491
492 # With locks, and the fact that we aren't printing from forks
493 # just write, and let the system flush. Everything should come out peachy
494 # I've left this code for historical purposes, or in case we need to add this
495 # back at a later date. For now ``TaskQueueManager.cleanup`` will perform a
496 # final flush at shutdown.
497 # try:
498 # fileobj.flush()
499 # except OSError as e:
500 # # Ignore EPIPE in case fileobj has been prematurely closed, eg.
501 # # when piping to "head -n1"
502 # if e.errno != errno.EPIPE:
503 # raise
504
505 if logger and not screen_only:
506 self._log(nocolor, color, caplevel)
507
508 def _log(self, msg: str, color: str | None = None, caplevel: int | None = None):
509
510 if logger and (caplevel is None or self.log_verbosity > caplevel):
511 msg2 = msg.lstrip('\n')
512
513 if caplevel is None or caplevel > 0:
514 lvl = logging.INFO
515 elif caplevel == -1:
516 lvl = logging.ERROR
517 elif caplevel == -2:
518 lvl = logging.WARNING
519 elif caplevel == -3:
520 lvl = logging.DEBUG
521 elif color:
522 # set logger level based on color (not great)
523 # but last resort and backwards compatible
524 try:
525 lvl = color_to_log_level[color]
526 except KeyError:
527 # this should not happen if mapping is updated with new color configs, but JIC
528 raise AnsibleAssertionError('Invalid color supplied to display: %s' % color)
529
530 # actually log
531 logger.log(lvl, msg2)
532
533 def v(self, msg: str, host: str | None = None) -> None:
534 return self.verbose(msg, host=host, caplevel=0)
535
536 def vv(self, msg: str, host: str | None = None) -> None:
537 return self.verbose(msg, host=host, caplevel=1)
538
539 def vvv(self, msg: str, host: str | None = None) -> None:
540 return self.verbose(msg, host=host, caplevel=2)
541
542 def vvvv(self, msg: str, host: str | None = None) -> None:
543 return self.verbose(msg, host=host, caplevel=3)
544
545 def vvvvv(self, msg: str, host: str | None = None) -> None:
546 return self.verbose(msg, host=host, caplevel=4)
547
548 def vvvvvv(self, msg: str, host: str | None = None) -> None:
549 return self.verbose(msg, host=host, caplevel=5)
550
551 def verbose(self, msg: str, host: str | None = None, caplevel: int = 2) -> None:
552 if self.verbosity > caplevel:
553 self._verbose_display(msg, host=host, caplevel=caplevel)
554
555 if self.log_verbosity > self.verbosity and self.log_verbosity > caplevel:
556 self._verbose_log(msg, host=host, caplevel=caplevel)
557
558 @_proxy
559 def _verbose_display(self, msg: str, host: str | None = None, caplevel: int = 2) -> None:
560 to_stderr = C.VERBOSE_TO_STDERR
561 if host is None:
562 self.display(msg, color=C.COLOR_VERBOSE, stderr=to_stderr)
563 else:
564 self.display("<%s> %s" % (host, msg), color=C.COLOR_VERBOSE, stderr=to_stderr)
565
566 @_proxy
567 def _verbose_log(self, msg: str, host: str | None = None, caplevel: int = 2) -> None:
568 # we send to log if log was configured with higher verbosity
569 if host is not None:
570 msg = "<%s> %s" % (host, msg)
571 self._log(msg, C.COLOR_VERBOSE, caplevel)
572
573 @_meets_debug
574 @_proxy
575 def debug(self, msg: str, host: str | None = None) -> None:
576 prefix = "%6d %0.5f" % (os.getpid(), time.time())
577 if host is not None:
578 prefix += f" [{host}]"
579 self.display(f"{prefix}: {msg}", color=C.COLOR_DEBUG, caplevel=-3)
580
581 def get_deprecation_message(
582 self,
583 msg: str,
584 version: str | None = None,
585 removed: bool = False,
586 date: str | None = None,
587 collection_name: str | None = None,
588 ) -> str:
589 """Return a deprecation message and help text for non-display purposes (e.g., exception messages)."""
590 self.deprecated(
591 msg="The `get_deprecation_message` method is deprecated.",
592 help_text="Use the `deprecated` method instead.",
593 version="2.23",
594 )
595
596 msg = _display_utils.get_deprecation_message_with_plugin_info(
597 msg=msg,
598 version=version,
599 removed=removed,
600 date=date,
601 deprecator=deprecator_from_collection_name(collection_name),
602 )
603
604 if removed:
605 msg = f'[DEPRECATED]: {msg}'
606 else:
607 msg = f'[DEPRECATION WARNING]: {msg}'
608
609 return msg
610
611 @staticmethod
612 def _deduplicate(msg: str, messages: set[str]) -> bool:
613 """
614 Return True if the given message was previously seen, otherwise record the message as seen and return False.
615 This is done very late (at display-time) to avoid loss of attribution of messages to individual tasks.
616 Duplicates included in task results will always be visible to registered variables and callbacks.
617 """
618
619 if msg in messages:
620 return True
621
622 messages.add(msg)
623
624 return False
625
626 def deprecated(
627 self,
628 msg: str,
629 version: str | None = None,
630 removed: bool = False,
631 date: str | None = None,
632 collection_name: str | None = None,
633 *,
634 deprecator: _messages.PluginInfo | None = None,
635 help_text: str | None = None,
636 obj: t.Any = None,
637 ) -> None:
638 """
639 Display a deprecation warning message, if enabled.
640 Most callers do not need to provide `collection_name` or `deprecator` -- but provide only one if needed.
641 Specify `version` or `date`, but not both.
642 If `date` is a string, it must be in the form `YYYY-MM-DD`.
643 """
644 # DTFIX3: are there any deprecation calls where the feature is switching from enabled to disabled, rather than being removed entirely?
645 # DTFIX3: are there deprecated features which should going through deferred deprecation instead?
646
647 _skip_stackwalk = True
648
649 self._deprecated_with_plugin_info(
650 msg=msg,
651 version=version,
652 removed=removed,
653 date=date,
654 help_text=help_text,
655 obj=obj,
656 deprecator=_deprecator.get_best_deprecator(deprecator=deprecator, collection_name=collection_name),
657 formatted_traceback=_traceback.maybe_capture_traceback(msg, _traceback.TracebackEvent.DEPRECATED),
658 )
659
660 def _deprecated_with_plugin_info(
661 self,
662 *,
663 msg: str,
664 version: str | None,
665 removed: bool = False,
666 date: str | None,
667 help_text: str | None,
668 obj: t.Any,
669 deprecator: _messages.PluginInfo | None,
670 formatted_traceback: str | None = None,
671 ) -> None:
672 """
673 This is the internal pre-proxy half of the `deprecated` implementation.
674 Any logic that must occur on workers needs to be implemented here.
675 """
676 _skip_stackwalk = True
677
678 if removed:
679 formatted_msg = _display_utils.get_deprecation_message_with_plugin_info(
680 msg=msg,
681 version=version,
682 removed=removed,
683 date=date,
684 deprecator=deprecator,
685 )
686
687 raise AnsibleError(formatted_msg)
688
689 if source_context := _error_utils.SourceContext.from_value(obj):
690 formatted_source_context = str(source_context)
691 else:
692 formatted_source_context = None
693
694 deprecation = _messages.DeprecationSummary(
695 event=_messages.Event(
696 msg=msg,
697 formatted_source_context=formatted_source_context,
698 help_text=help_text,
699 formatted_traceback=formatted_traceback,
700 ),
701 version=version,
702 date=date,
703 deprecator=deprecator,
704 )
705
706 if warning_ctx := _display_utils.DeferredWarningContext.current(optional=True):
707 warning_ctx.capture(deprecation)
708 return
709
710 self._deprecated(deprecation)
711
712 @_proxy
713 def _deprecated(self, warning: _messages.DeprecationSummary) -> None:
714 """Internal implementation detail, use `deprecated` instead."""
715
716 # This is the post-proxy half of the `deprecated` implementation.
717 # Any logic that must occur in the primary controller process needs to be implemented here.
718
719 if not _deprecation_warnings_enabled():
720 return
721
722 self.warning('Deprecation warnings can be disabled by setting `deprecation_warnings=False` in ansible.cfg.')
723
724 msg = _display_utils.format_message(warning, _traceback.is_traceback_enabled(_traceback.TracebackEvent.DEPRECATED))
725 msg = f'[DEPRECATION WARNING]: {msg}'
726
727 if self._deduplicate(msg, self._deprecations):
728 return
729
730 self.display(msg, color=C.config.get_config_value('COLOR_DEPRECATE'), stderr=True)
731
732 def warning(
733 self,
734 msg: str,
735 formatted: bool = False,
736 *,
737 help_text: str | None = None,
738 obj: t.Any = None
739 ) -> None:
740 """Display a warning message."""
741 _skip_stackwalk = True
742
743 # deprecated: description='The formatted argument has no effect.' core_version='2.23'
744
745 # This is the pre-proxy half of the `warning` implementation.
746 # Any logic that must occur on workers needs to be implemented here.
747
748 if source_context := _error_utils.SourceContext.from_value(obj):
749 formatted_source_context = str(source_context)
750 else:
751 formatted_source_context = None
752
753 warning = _messages.WarningSummary(
754 event=_messages.Event(
755 msg=msg,
756 help_text=help_text,
757 formatted_source_context=formatted_source_context,
758 formatted_traceback=_traceback.maybe_capture_traceback(msg, _traceback.TracebackEvent.WARNING),
759 ),
760 )
761
762 if warning_ctx := _display_utils.DeferredWarningContext.current(optional=True):
763 warning_ctx.capture(warning)
764 return
765
766 self._warning(warning)
767
768 @_proxy
769 def _warning(self, warning: _messages.WarningSummary) -> None:
770 """Internal implementation detail, use `warning` instead."""
771
772 # This is the post-proxy half of the `warning` implementation.
773 # Any logic that must occur in the primary controller process needs to be implemented here.
774
775 msg = _display_utils.format_message(warning, _traceback.is_traceback_enabled(_traceback.TracebackEvent.WARNING))
776 msg = f"[WARNING]: {msg}"
777
778 if self._deduplicate(msg, self._warns):
779 return
780
781 self.display(msg, color=C.config.get_config_value('COLOR_WARN'), stderr=True, caplevel=-2)
782
783 @_proxy
784 def system_warning(self, msg: str) -> None:
785 if C.SYSTEM_WARNINGS:
786 self.warning(msg)
787
788 @_proxy
789 def banner(self, msg: str, color: str | None = None, cows: bool = True) -> None:
790 """
791 Prints a header-looking line with cowsay or stars with length depending on terminal width (3 minimum)
792 """
793 msg = to_text(msg)
794
795 if self.b_cowsay and cows:
796 try:
797 self.banner_cowsay(msg)
798 return
799 except OSError:
800 self.warning("somebody cleverly deleted cowsay or something during the PB run. heh.")
801
802 msg = msg.strip()
803 try:
804 star_len = self.columns - get_text_width(msg)
805 except EnvironmentError:
806 star_len = self.columns - len(msg)
807 if star_len <= 3:
808 star_len = 3
809 stars = u"*" * star_len
810 self.display(u"\n%s %s" % (msg, stars), color=color)
811
812 @_proxy
813 def banner_cowsay(self, msg: str, color: str | None = None) -> None:
814 if u": [" in msg:
815 msg = msg.replace(u"[", u"")
816 if msg.endswith(u"]"):
817 msg = msg[:-1]
818 runcmd = [self.b_cowsay, b"-W", b"60"]
819 if self.noncow:
820 thecow = self.noncow
821 if thecow == 'random':
822 thecow = secrets.choice(list(self.cows_available))
823 runcmd.append(b'-f')
824 runcmd.append(to_bytes(thecow))
825 runcmd.append(to_bytes(msg))
826 cmd = subprocess.Popen(runcmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
827 (out, err) = cmd.communicate()
828 self.display(u"%s\n" % to_text(out), color=color)
829
830 def error_as_warning(
831 self,
832 msg: str | None,
833 exception: BaseException,
834 *,
835 help_text: str | None = None,
836 obj: t.Any = None,
837 ) -> None:
838 """Display an exception as a warning."""
839 _skip_stackwalk = True
840
841 event = _error_factory.ControllerEventFactory.from_exception(exception, _traceback.is_traceback_enabled(_traceback.TracebackEvent.WARNING))
842
843 if msg:
844 if source_context := _error_utils.SourceContext.from_value(obj):
845 formatted_source_context = str(source_context)
846 else:
847 formatted_source_context = None
848
849 event = _messages.Event(
850 msg=msg,
851 help_text=help_text,
852 formatted_source_context=formatted_source_context,
853 formatted_traceback=_traceback.maybe_capture_traceback(msg, _traceback.TracebackEvent.WARNING),
854 chain=_messages.EventChain(
855 msg_reason=_errors.MSG_REASON_DIRECT_CAUSE,
856 traceback_reason=_errors.TRACEBACK_REASON_EXCEPTION_DIRECT_WARNING,
857 event=event,
858 ),
859 )
860
861 warning = _messages.WarningSummary(
862 event=event,
863 )
864
865 if warning_ctx := _display_utils.DeferredWarningContext.current(optional=True):
866 warning_ctx.capture(warning)
867 return
868
869 self._warning(warning)
870
871 def error(self, msg: str | BaseException, wrap_text: bool = True, stderr: bool = True) -> None:
872 """Display an error message."""
873 _skip_stackwalk = True
874
875 # deprecated: description='The wrap_text argument has no effect.' core_version='2.23'
876 # deprecated: description='The stderr argument has no effect.' core_version='2.23'
877
878 # This is the pre-proxy half of the `error` implementation.
879 # Any logic that must occur on workers needs to be implemented here.
880
881 if isinstance(msg, BaseException):
882 event = _error_factory.ControllerEventFactory.from_exception(msg, _traceback.is_traceback_enabled(_traceback.TracebackEvent.ERROR))
883 else:
884 event = _messages.Event(
885 msg=msg,
886 formatted_traceback=_traceback.maybe_capture_traceback(msg, _traceback.TracebackEvent.ERROR),
887 )
888
889 error = _messages.ErrorSummary(
890 event=event,
891 )
892
893 self._error(error, stderr=True)
894
895 @_proxy
896 def _error(self, error: _messages.ErrorSummary, stderr: bool) -> None:
897 """Internal implementation detail, use `error` instead."""
898
899 # This is the post-proxy half of the `error` implementation.
900 # Any logic that must occur in the primary controller process needs to be implemented here.
901
902 msg = _display_utils.format_message(error, _traceback.is_traceback_enabled(_traceback.TracebackEvent.ERROR))
903 msg = f'[ERROR]: {msg}'
904
905 if self._deduplicate(msg, self._errors):
906 return
907
908 self.display(msg, color=C.config.get_config_value('COLOR_ERROR'), stderr=stderr, caplevel=-1)
909
910 @staticmethod
911 def prompt(msg: str, private: bool = False) -> str:
912 if private:
913 return getpass.getpass(msg)
914 else:
915 return input(msg)
916
917 def do_var_prompt(
918 self,
919 varname: str,
920 private: bool = True,
921 prompt: str | None = None,
922 encrypt: str | None = None,
923 confirm: bool = False,
924 salt_size: int | None = None,
925 salt: str | None = None,
926 default: str | None = None,
927 unsafe: bool = False,
928 ) -> str:
929 result = None
930 if sys.__stdin__.isatty():
931
932 do_prompt = self.prompt
933
934 if prompt and default is not None:
935 msg = "%s [%s]: " % (prompt, default)
936 elif prompt:
937 msg = "%s: " % prompt
938 else:
939 msg = 'input for %s: ' % varname
940
941 if confirm:
942 while True:
943 result = do_prompt(msg, private)
944 second = do_prompt("confirm " + msg, private)
945 if result == second:
946 break
947 self.display("***** VALUES ENTERED DO NOT MATCH ****")
948 else:
949 result = do_prompt(msg, private)
950 else:
951 result = None
952 self.warning("Not prompting as we are not in interactive mode")
953
954 # if result is false and default is not None
955 if not result and default is not None:
956 result = default
957
958 # handle utf-8 chars
959 result_str = to_text(result, errors='surrogate_or_strict')
960
961 if private and result:
962 register_secret(result_str)
963
964 if encrypt:
965 # Circular import because encrypt needs a display class
966 from ansible.utils.encrypt import do_encrypt
967 result_str = do_encrypt(result_str, encrypt, salt_size=salt_size, salt=salt)
968
969 if not unsafe:
970 # to maintain backward compatibility, assume these values are safe to template
971 result_str = TrustedAsTemplate().tag(result_str)
972
973 return result_str
974
975 def _set_column_width(self) -> None:
976 if os.isatty(1):
977 tty_size = unpack('HHHH', fcntl.ioctl(1, termios.TIOCGWINSZ, pack('HHHH', 0, 0, 0, 0)))[1]
978 else:
979 tty_size = 0
980 self.columns = max(79, tty_size - 1)
981
982 def prompt_until(
983 self,
984 msg: str,
985 private: bool = False,
986 seconds: int | None = None,
987 interrupt_input: c.Iterable[bytes] | None = None,
988 complete_input: c.Iterable[bytes] | None = None,
989 ) -> bytes:
990 if self._final_q:
991 from ansible.executor.process.worker import current_worker
992 self._final_q.send_prompt(
993 worker_id=current_worker.worker_id, prompt=msg, private=private, seconds=seconds,
994 interrupt_input=interrupt_input, complete_input=complete_input
995 )
996 return current_worker.worker_queue.get()
997
998 if HAS_CURSES and not self.setup_curses:
999 setupterm()
1000 self.setup_curses = True
1001
1002 if (
1003 self._stdin_fd is None
1004 or not os.isatty(self._stdin_fd)
1005 # Compare the current process group to the process group associated
1006 # with terminal of the given file descriptor to determine if the process
1007 # is running in the background.
1008 or os.getpgrp() != os.tcgetpgrp(self._stdin_fd)
1009 ):
1010 raise AnsiblePromptNoninteractive('stdin is not interactive')
1011
1012 # When seconds/interrupt_input/complete_input are all None, this does mostly the same thing as input/getpass,
1013 # but self.prompt may raise a KeyboardInterrupt, which must be caught in the main thread.
1014 # If the main thread handled this, it would also need to send a newline to the tty of any hanging pids.
1015 # if seconds is None and interrupt_input is None and complete_input is None:
1016 # try:
1017 # return self.prompt(msg, private=private)
1018 # except KeyboardInterrupt:
1019 # # can't catch in the results_thread_main daemon thread
1020 # raise AnsiblePromptInterrupt('user interrupt')
1021
1022 self.display(msg)
1023 result = b''
1024 with self._lock:
1025 original_stdin_settings = termios.tcgetattr(self._stdin_fd)
1026 try:
1027 setup_prompt(self._stdin_fd, self._stdout_fd, seconds, not private)
1028
1029 # flush the buffer to make sure no previous key presses
1030 # are read in below
1031 termios.tcflush(self._stdin, termios.TCIFLUSH)
1032
1033 # read input 1 char at a time until the optional timeout or complete/interrupt condition is met
1034 return self._read_non_blocking_stdin(echo=not private, seconds=seconds, interrupt_input=interrupt_input, complete_input=complete_input)
1035 finally:
1036 # restore the old settings for the duped stdin stdin_fd
1037 termios.tcsetattr(self._stdin_fd, termios.TCSADRAIN, original_stdin_settings)
1038
1039 def _read_non_blocking_stdin(
1040 self,
1041 echo: bool = False,
1042 seconds: int | None = None,
1043 interrupt_input: c.Iterable[bytes] | None = None,
1044 complete_input: c.Iterable[bytes] | None = None,
1045 ) -> bytes:
1046 if self._final_q:
1047 raise NotImplementedError
1048
1049 if seconds is not None:
1050 start = time.time()
1051 if interrupt_input is None:
1052 try:
1053 interrupt = termios.tcgetattr(sys.stdin.buffer.fileno())[6][termios.VINTR]
1054 except Exception:
1055 interrupt = b'\x03' # value for Ctrl+C
1056
1057 try:
1058 backspace_sequences = [termios.tcgetattr(self._stdin_fd)[6][termios.VERASE]]
1059 except Exception:
1060 # unsupported/not present, use default
1061 backspace_sequences = [b'\x7f', b'\x08']
1062
1063 result_string = b''
1064 while seconds is None or (time.time() - start < seconds):
1065 key_pressed = None
1066 try:
1067 os.set_blocking(self._stdin_fd, False)
1068 while key_pressed is None and (seconds is None or (time.time() - start < seconds)):
1069 key_pressed = self._stdin.read(1)
1070 # throttle to prevent excess CPU consumption
1071 time.sleep(C.DEFAULT_INTERNAL_POLL_INTERVAL)
1072 finally:
1073 os.set_blocking(self._stdin_fd, True)
1074 if key_pressed is None:
1075 key_pressed = b''
1076
1077 if (interrupt_input is None and key_pressed == interrupt) or (interrupt_input is not None and key_pressed.lower() in interrupt_input):
1078 clear_line(self._stdout)
1079 raise AnsiblePromptInterrupt('user interrupt')
1080 if (complete_input is None and key_pressed in (b'\r', b'\n')) or (complete_input is not None and key_pressed.lower() in complete_input):
1081 clear_line(self._stdout)
1082 break
1083 elif key_pressed in backspace_sequences:
1084 clear_line(self._stdout)
1085 result_string = result_string[:-1]
1086 if echo:
1087 self._stdout.write(result_string)
1088 self._stdout.flush()
1089 else:
1090 result_string += key_pressed
1091 return result_string
1092
1093 @property
1094 def _stdin(self) -> t.BinaryIO | None:
1095 if self._final_q:
1096 raise NotImplementedError
1097 try:
1098 return sys.stdin.buffer
1099 except AttributeError:
1100 return None
1101
1102 @property
1103 def _stdin_fd(self) -> int | None:
1104 try:
1105 return self._stdin.fileno()
1106 except (ValueError, AttributeError):
1107 return None
1108
1109 @property
1110 def _stdout(self) -> t.BinaryIO:
1111 if self._final_q:
1112 raise NotImplementedError
1113 return sys.stdout.buffer
1114
1115 @property
1116 def _stdout_fd(self) -> int | None:
1117 try:
1118 return self._stdout.fileno()
1119 except (ValueError, AttributeError):
1120 return None
1121
1122
1123 _display = Display()
1124
1125
1126 def _report_config_warnings(deprecator: _messages.PluginInfo) -> None:
1127 """Called by config to report warnings/deprecations collected during a config parse."""
1128 while config._errors:
1129 msg, exception = config._errors.pop()
1130 _display.error_as_warning(msg=msg, exception=exception)
1131
1132 while config.WARNINGS:
1133 warn = config.WARNINGS.pop()
1134 _display.warning(warn)
1135
1136 while config.DEPRECATED:
1137 # tuple with name and options
1138 dep = config.DEPRECATED.pop(0)
1139 msg = config.get_deprecated_msg_from_config(dep[1]).replace("\t", "")
1140
1141 _display.deprecated( # pylint: disable=ansible-deprecated-unnecessary-collection-name,ansible-invalid-deprecated-version
1142 msg=f"{dep[0]} option. {msg}",
1143 version=dep[1]['version'],
1144 deprecator=deprecator,
1145 )
1146
1147
1148 # emit any warnings or deprecations
1149 # in the event config fails before display is up, we'll lose warnings -- but that's OK, since everything is broken anyway
1150 _report_config_warnings(_deprecator.ANSIBLE_CORE_DEPRECATOR)
1151
1152
1153 def __getattr__(importable_name):
1154 return _no_six.deprecate(importable_name, __name__, "text_type")