1# Copyright: (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
2# Copyright: (c) 2017, Ansible Project
3# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4
5from __future__ import (absolute_import, division, print_function)
6__metaclass__ = type
7
8import os
9import re
10
11from ast import literal_eval
12from jinja2 import Template
13from string import ascii_letters, digits
14
15from ansible.config.manager import ConfigManager, ensure_type, get_ini_config_value
16from ansible.module_utils._text import to_text
17from ansible.module_utils.common.collections import Sequence
18from ansible.module_utils.parsing.convert_bool import boolean, BOOLEANS_TRUE
19from ansible.module_utils.six import string_types
20from ansible.utils.fqcn import add_internal_fqcns
21
22
23def _warning(msg):
24    ''' display is not guaranteed here, nor it being the full class, but try anyways, fallback to sys.stderr.write '''
25    try:
26        from ansible.utils.display import Display
27        Display().warning(msg)
28    except Exception:
29        import sys
30        sys.stderr.write(' [WARNING] %s\n' % (msg))
31
32
33def _deprecated(msg, version='2.8'):
34    ''' display is not guaranteed here, nor it being the full class, but try anyways, fallback to sys.stderr.write '''
35    try:
36        from ansible.utils.display import Display
37        Display().deprecated(msg, version=version)
38    except Exception:
39        import sys
40        sys.stderr.write(' [DEPRECATED] %s, to be removed in %s\n' % (msg, version))
41
42
43def set_constant(name, value, export=vars()):
44    ''' sets constants and returns resolved options dict '''
45    export[name] = value
46
47
48class _DeprecatedSequenceConstant(Sequence):
49    def __init__(self, value, msg, version):
50        self._value = value
51        self._msg = msg
52        self._version = version
53
54    def __len__(self):
55        _deprecated(self._msg, version=self._version)
56        return len(self._value)
57
58    def __getitem__(self, y):
59        _deprecated(self._msg, version=self._version)
60        return self._value[y]
61
62
63# CONSTANTS ### yes, actual ones
64
65# The following are hard-coded action names
66_ACTION_DEBUG = add_internal_fqcns(('debug', ))
67_ACTION_IMPORT_PLAYBOOK = add_internal_fqcns(('import_playbook', ))
68_ACTION_IMPORT_ROLE = add_internal_fqcns(('import_role', ))
69_ACTION_IMPORT_TASKS = add_internal_fqcns(('import_tasks', ))
70_ACTION_INCLUDE = add_internal_fqcns(('include', ))
71_ACTION_INCLUDE_ROLE = add_internal_fqcns(('include_role', ))
72_ACTION_INCLUDE_TASKS = add_internal_fqcns(('include_tasks', ))
73_ACTION_INCLUDE_VARS = add_internal_fqcns(('include_vars', ))
74_ACTION_META = add_internal_fqcns(('meta', ))
75_ACTION_SET_FACT = add_internal_fqcns(('set_fact', ))
76_ACTION_SETUP = add_internal_fqcns(('setup', ))
77_ACTION_HAS_CMD = add_internal_fqcns(('command', 'shell', 'script'))
78_ACTION_ALLOWS_RAW_ARGS = _ACTION_HAS_CMD + add_internal_fqcns(('raw', ))
79_ACTION_ALL_INCLUDES = _ACTION_INCLUDE + _ACTION_INCLUDE_TASKS + _ACTION_INCLUDE_ROLE
80_ACTION_ALL_IMPORT_PLAYBOOKS = _ACTION_INCLUDE + _ACTION_IMPORT_PLAYBOOK
81_ACTION_ALL_INCLUDE_IMPORT_TASKS = _ACTION_INCLUDE + _ACTION_INCLUDE_TASKS + _ACTION_IMPORT_TASKS
82_ACTION_ALL_PROPER_INCLUDE_IMPORT_ROLES = _ACTION_INCLUDE_ROLE + _ACTION_IMPORT_ROLE
83_ACTION_ALL_PROPER_INCLUDE_IMPORT_TASKS = _ACTION_INCLUDE_TASKS + _ACTION_IMPORT_TASKS
84_ACTION_ALL_INCLUDE_ROLE_TASKS = _ACTION_INCLUDE_ROLE + _ACTION_INCLUDE_TASKS
85_ACTION_ALL_INCLUDE_TASKS = _ACTION_INCLUDE + _ACTION_INCLUDE_TASKS
86_ACTION_FACT_GATHERING = _ACTION_SETUP + add_internal_fqcns(('gather_facts', ))
87_ACTION_WITH_CLEAN_FACTS = _ACTION_SET_FACT + _ACTION_INCLUDE_VARS
88
89# http://nezzen.net/2008/06/23/colored-text-in-python-using-ansi-escape-sequences/
90COLOR_CODES = {
91    'black': u'0;30', 'bright gray': u'0;37',
92    'blue': u'0;34', 'white': u'1;37',
93    'green': u'0;32', 'bright blue': u'1;34',
94    'cyan': u'0;36', 'bright green': u'1;32',
95    'red': u'0;31', 'bright cyan': u'1;36',
96    'purple': u'0;35', 'bright red': u'1;31',
97    'yellow': u'0;33', 'bright purple': u'1;35',
98    'dark gray': u'1;30', 'bright yellow': u'1;33',
99    'magenta': u'0;35', 'bright magenta': u'1;35',
100    'normal': u'0',
101}
102REJECT_EXTS = ('.pyc', '.pyo', '.swp', '.bak', '~', '.rpm', '.md', '.txt', '.rst')
103BOOL_TRUE = BOOLEANS_TRUE
104COLLECTION_PTYPE_COMPAT = {'module': 'modules'}
105DEFAULT_BECOME_PASS = None
106DEFAULT_PASSWORD_CHARS = to_text(ascii_letters + digits + ".,:-_", errors='strict')  # characters included in auto-generated passwords
107DEFAULT_REMOTE_PASS = None
108DEFAULT_SUBSET = None
109# FIXME: expand to other plugins, but never doc fragments
110CONFIGURABLE_PLUGINS = ('become', 'cache', 'callback', 'cliconf', 'connection', 'httpapi', 'inventory', 'lookup', 'netconf', 'shell', 'vars')
111# NOTE: always update the docs/docsite/Makefile to match
112DOCUMENTABLE_PLUGINS = CONFIGURABLE_PLUGINS + ('module', 'strategy')
113IGNORE_FILES = ("COPYING", "CONTRIBUTING", "LICENSE", "README", "VERSION", "GUIDELINES")  # ignore during module search
114INTERNAL_RESULT_KEYS = ('add_host', 'add_group')
115LOCALHOST = ('127.0.0.1', 'localhost', '::1')
116MODULE_REQUIRE_ARGS = tuple(add_internal_fqcns(('command', 'win_command', 'ansible.windows.win_command', 'shell', 'win_shell',
117                                                'ansible.windows.win_shell', 'raw', 'script')))
118MODULE_NO_JSON = tuple(add_internal_fqcns(('command', 'win_command', 'ansible.windows.win_command', 'shell', 'win_shell',
119                                           'ansible.windows.win_shell', 'raw')))
120RESTRICTED_RESULT_KEYS = ('ansible_rsync_path', 'ansible_playbook_python', 'ansible_facts')
121TREE_DIR = None
122VAULT_VERSION_MIN = 1.0
123VAULT_VERSION_MAX = 1.0
124
125# This matches a string that cannot be used as a valid python variable name i.e 'not-valid', 'not!valid@either' '1_nor_This'
126INVALID_VARIABLE_NAMES = re.compile(r'^[\d\W]|[^\w]')
127
128
129# FIXME: remove once play_context mangling is removed
130# the magic variable mapping dictionary below is used to translate
131# host/inventory variables to fields in the PlayContext
132# object. The dictionary values are tuples, to account for aliases
133# in variable names.
134
135COMMON_CONNECTION_VARS = frozenset(('ansible_connection', 'ansible_host', 'ansible_user', 'ansible_shell_executable',
136                                    'ansible_port', 'ansible_pipelining', 'ansible_password', 'ansible_timeout',
137                                    'ansible_shell_type', 'ansible_module_compression', 'ansible_private_key_file'))
138
139MAGIC_VARIABLE_MAPPING = dict(
140
141    # base
142    connection=('ansible_connection', ),
143    module_compression=('ansible_module_compression', ),
144    shell=('ansible_shell_type', ),
145    executable=('ansible_shell_executable', ),
146
147    # connection common
148    remote_addr=('ansible_ssh_host', 'ansible_host'),
149    remote_user=('ansible_ssh_user', 'ansible_user'),
150    password=('ansible_ssh_pass', 'ansible_password'),
151    port=('ansible_ssh_port', 'ansible_port'),
152    pipelining=('ansible_ssh_pipelining', 'ansible_pipelining'),
153    timeout=('ansible_ssh_timeout', 'ansible_timeout'),
154    private_key_file=('ansible_ssh_private_key_file', 'ansible_private_key_file'),
155
156    # networking modules
157    network_os=('ansible_network_os', ),
158    connection_user=('ansible_connection_user',),
159
160    # ssh TODO: remove
161    ssh_executable=('ansible_ssh_executable', ),
162    ssh_common_args=('ansible_ssh_common_args', ),
163    sftp_extra_args=('ansible_sftp_extra_args', ),
164    scp_extra_args=('ansible_scp_extra_args', ),
165    ssh_extra_args=('ansible_ssh_extra_args', ),
166    ssh_transfer_method=('ansible_ssh_transfer_method', ),
167
168    # docker TODO: remove
169    docker_extra_args=('ansible_docker_extra_args', ),
170
171    # become
172    become=('ansible_become', ),
173    become_method=('ansible_become_method', ),
174    become_user=('ansible_become_user', ),
175    become_pass=('ansible_become_password', 'ansible_become_pass'),
176    become_exe=('ansible_become_exe', ),
177    become_flags=('ansible_become_flags', ),
178)
179
180# POPULATE SETTINGS FROM CONFIG ###
181config = ConfigManager()
182
183# Generate constants from config
184for setting in config.data.get_settings():
185
186    value = setting.value
187    if setting.origin == 'default' and \
188       isinstance(setting.value, string_types) and \
189       (setting.value.startswith('{{') and setting.value.endswith('}}')):
190        try:
191            t = Template(setting.value)
192            value = t.render(vars())
193            try:
194                value = literal_eval(value)
195            except ValueError:
196                pass  # not a python data structure
197        except Exception:
198            pass  # not templatable
199
200        value = ensure_type(value, setting.type)
201
202    set_constant(setting.name, value)
203
204for warn in config.WARNINGS:
205    _warning(warn)
206