repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
saltstack/salt
salt/utils/decorators/path.py
which_bin
python
def which_bin(exes): ''' Decorator wrapper for salt.utils.path.which_bin ''' def wrapper(function): def wrapped(*args, **kwargs): if salt.utils.path.which_bin(exes) is None: raise CommandNotFoundError( 'None of provided binaries({0}) was not found ' 'in $PATH.'.format( ['\'{0}\''.format(exe) for exe in exes] ) ) return function(*args, **kwargs) return identical_signature_wrapper(function, wrapped) return wrapper
Decorator wrapper for salt.utils.path.which_bin
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/decorators/path.py#L28-L43
null
# -*- coding: utf-8 -*- ''' Decorators for salt.utils.path ''' from __future__ import absolute_import, print_function, unicode_literals # Import Salt libs import salt.utils.path from salt.exceptions import CommandNotFoundError from salt.utils.decorators.signature import identical_signature_wrapper def which(exe): ''' Decorator wrapper for salt.utils.path.which ''' def wrapper(function): def wrapped(*args, **kwargs): if salt.utils.path.which(exe) is None: raise CommandNotFoundError( 'The \'{0}\' binary was not found in $PATH.'.format(exe) ) return function(*args, **kwargs) return identical_signature_wrapper(function, wrapped) return wrapper
saltstack/salt
salt/runners/doc.py
runner
python
def runner(): ''' Return all inline documentation for runner modules CLI Example: .. code-block:: bash salt-run doc.runner ''' client = salt.runner.RunnerClient(__opts__) ret = client.get_docs() return ret
Return all inline documentation for runner modules CLI Example: .. code-block:: bash salt-run doc.runner
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/doc.py#L27-L39
[ "def get_docs(self, arg=None):\n '''\n Return a dictionary of functions and the inline documentation for each\n '''\n if arg:\n if '*' in arg:\n target_mod = arg\n _use_fnmatch = True\n else:\n target_mod = arg + '.' if not arg.endswith('.') else arg\n _use_fnmatch = False\n if _use_fnmatch:\n docs = [(fun, self.functions[fun].__doc__)\n for fun in fnmatch.filter(self.functions, target_mod)]\n else:\n docs = [(fun, self.functions[fun].__doc__)\n for fun in sorted(self.functions)\n if fun == arg or fun.startswith(target_mod)]\n else:\n docs = [(fun, self.functions[fun].__doc__)\n for fun in sorted(self.functions)]\n docs = dict(docs)\n return salt.utils.doc.strip_rst(docs)\n" ]
# -*- coding: utf-8 -*- ''' A runner module to collect and display the inline documentation from the various module types ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import itertools # Import salt libs import salt.client import salt.runner import salt.wheel # Import 3rd-party libs from salt.ext import six from salt.exceptions import SaltClientError def __virtual__(): ''' Always load ''' return True def wheel(): ''' Return all inline documentation for wheel modules CLI Example: .. code-block:: bash salt-run doc.wheel ''' client = salt.wheel.Wheel(__opts__) ret = client.get_docs() return ret def execution(): ''' Collect all the sys.doc output from each minion and return the aggregate CLI Example: .. code-block:: bash salt-run doc.execution ''' client = salt.client.get_local_client(__opts__['conf_file']) docs = {} try: for ret in client.cmd_iter('*', 'sys.doc', timeout=__opts__['timeout']): for v in six.itervalues(ret): docs.update(v) except SaltClientError as exc: print(exc) return [] i = itertools.chain.from_iterable([six.iteritems(docs['ret'])]) ret = dict(list(i)) return ret
saltstack/salt
salt/runners/doc.py
wheel
python
def wheel(): ''' Return all inline documentation for wheel modules CLI Example: .. code-block:: bash salt-run doc.wheel ''' client = salt.wheel.Wheel(__opts__) ret = client.get_docs() return ret
Return all inline documentation for wheel modules CLI Example: .. code-block:: bash salt-run doc.wheel
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/doc.py#L42-L54
[ "def get_docs(self, arg=None):\n '''\n Return a dictionary of functions and the inline documentation for each\n '''\n if arg:\n if '*' in arg:\n target_mod = arg\n _use_fnmatch = True\n else:\n target_mod = arg + '.' if not arg.endswith('.') else arg\n _use_fnmatch = False\n if _use_fnmatch:\n docs = [(fun, self.functions[fun].__doc__)\n for fun in fnmatch.filter(self.functions, target_mod)]\n else:\n docs = [(fun, self.functions[fun].__doc__)\n for fun in sorted(self.functions)\n if fun == arg or fun.startswith(target_mod)]\n else:\n docs = [(fun, self.functions[fun].__doc__)\n for fun in sorted(self.functions)]\n docs = dict(docs)\n return salt.utils.doc.strip_rst(docs)\n" ]
# -*- coding: utf-8 -*- ''' A runner module to collect and display the inline documentation from the various module types ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import itertools # Import salt libs import salt.client import salt.runner import salt.wheel # Import 3rd-party libs from salt.ext import six from salt.exceptions import SaltClientError def __virtual__(): ''' Always load ''' return True def runner(): ''' Return all inline documentation for runner modules CLI Example: .. code-block:: bash salt-run doc.runner ''' client = salt.runner.RunnerClient(__opts__) ret = client.get_docs() return ret def execution(): ''' Collect all the sys.doc output from each minion and return the aggregate CLI Example: .. code-block:: bash salt-run doc.execution ''' client = salt.client.get_local_client(__opts__['conf_file']) docs = {} try: for ret in client.cmd_iter('*', 'sys.doc', timeout=__opts__['timeout']): for v in six.itervalues(ret): docs.update(v) except SaltClientError as exc: print(exc) return [] i = itertools.chain.from_iterable([six.iteritems(docs['ret'])]) ret = dict(list(i)) return ret
saltstack/salt
salt/runners/doc.py
execution
python
def execution(): ''' Collect all the sys.doc output from each minion and return the aggregate CLI Example: .. code-block:: bash salt-run doc.execution ''' client = salt.client.get_local_client(__opts__['conf_file']) docs = {} try: for ret in client.cmd_iter('*', 'sys.doc', timeout=__opts__['timeout']): for v in six.itervalues(ret): docs.update(v) except SaltClientError as exc: print(exc) return [] i = itertools.chain.from_iterable([six.iteritems(docs['ret'])]) ret = dict(list(i)) return ret
Collect all the sys.doc output from each minion and return the aggregate CLI Example: .. code-block:: bash salt-run doc.execution
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/doc.py#L57-L81
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n", "def itervalues(d, **kw):\n return d.itervalues(**kw)\n", "def get_local_client(\n c_path=os.path.join(syspaths.CONFIG_DIR, 'master'),\n mopts=None,\n skip_perm_errors=False,\n io_loop=None,\n auto_reconnect=False):\n '''\n .. versionadded:: 2014.7.0\n\n Read in the config and return the correct LocalClient object based on\n the configured transport\n\n :param IOLoop io_loop: io_loop used for events.\n Pass in an io_loop if you want asynchronous\n operation for obtaining events. Eg use of\n set_event_handler() API. Otherwise, operation\n will be synchronous.\n '''\n if mopts:\n opts = mopts\n else:\n # Late import to prevent circular import\n import salt.config\n opts = salt.config.client_config(c_path)\n\n # TODO: AIO core is separate from transport\n return LocalClient(\n mopts=opts,\n skip_perm_errors=skip_perm_errors,\n io_loop=io_loop,\n auto_reconnect=auto_reconnect)\n", "def cmd_iter(\n self,\n tgt,\n fun,\n arg=(),\n timeout=None,\n tgt_type='glob',\n ret='',\n kwarg=None,\n **kwargs):\n '''\n Yields the individual minion returns as they come in\n\n The function signature is the same as :py:meth:`cmd` with the\n following exceptions.\n\n Normally :py:meth:`cmd_iter` does not yield results for minions that\n are not connected. If you want it to return results for disconnected\n minions set `expect_minions=True` in `kwargs`.\n\n :return: A generator yielding the individual minion returns\n\n .. code-block:: python\n\n >>> ret = local.cmd_iter('*', 'test.ping')\n >>> for i in ret:\n ... print(i)\n {'jerry': {'ret': True}}\n {'dave': {'ret': True}}\n {'stewart': {'ret': True}}\n '''\n was_listening = self.event.cpub\n\n try:\n pub_data = self.run_job(\n tgt,\n fun,\n arg,\n tgt_type,\n ret,\n timeout,\n kwarg=kwarg,\n listen=True,\n **kwargs)\n\n if not pub_data:\n yield pub_data\n else:\n if kwargs.get('yield_pub_data'):\n yield pub_data\n for fn_ret in self.get_iter_returns(pub_data['jid'],\n pub_data['minions'],\n timeout=self._get_timeout(timeout),\n tgt=tgt,\n tgt_type=tgt_type,\n **kwargs):\n if not fn_ret:\n continue\n yield fn_ret\n self._clean_up_subscriptions(pub_data['jid'])\n finally:\n if not was_listening:\n self.event.close_pub()\n" ]
# -*- coding: utf-8 -*- ''' A runner module to collect and display the inline documentation from the various module types ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import itertools # Import salt libs import salt.client import salt.runner import salt.wheel # Import 3rd-party libs from salt.ext import six from salt.exceptions import SaltClientError def __virtual__(): ''' Always load ''' return True def runner(): ''' Return all inline documentation for runner modules CLI Example: .. code-block:: bash salt-run doc.runner ''' client = salt.runner.RunnerClient(__opts__) ret = client.get_docs() return ret def wheel(): ''' Return all inline documentation for wheel modules CLI Example: .. code-block:: bash salt-run doc.wheel ''' client = salt.wheel.Wheel(__opts__) ret = client.get_docs() return ret
saltstack/salt
salt/modules/temp.py
file
python
def file(suffix='', prefix='tmp', parent=None): ''' Create a temporary file CLI Example: .. code-block:: bash salt '*' temp.file salt '*' temp.file prefix='mytemp-' parent='/var/run/' ''' fh_, tmp_ = tempfile.mkstemp(suffix, prefix, parent) os.close(fh_) return tmp_
Create a temporary file CLI Example: .. code-block:: bash salt '*' temp.file salt '*' temp.file prefix='mytemp-' parent='/var/run/'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/temp.py#L33-L46
null
# -*- coding: utf-8 -*- ''' Simple module for creating temporary directories and files This is a thin wrapper around Pythons tempfile module .. versionadded:: 2015.8.0 ''' from __future__ import absolute_import, unicode_literals, print_function import logging import os import tempfile log = logging.getLogger(__name__) def dir(suffix='', prefix='tmp', parent=None): ''' Create a temporary directory CLI Example: .. code-block:: bash salt '*' temp.dir salt '*' temp.dir prefix='mytemp-' parent='/var/run/' ''' return tempfile.mkdtemp(suffix, prefix, parent)
saltstack/salt
salt/runner.py
RunnerClient._reformat_low
python
def _reformat_low(self, low): ''' Format the low data for RunnerClient()'s master_call() function This also normalizes the following low data formats to a single, common low data structure. Old-style low: ``{'fun': 'jobs.lookup_jid', 'jid': '1234'}`` New-style: ``{'fun': 'jobs.lookup_jid', 'kwarg': {'jid': '1234'}}`` CLI-style: ``{'fun': 'jobs.lookup_jid', 'arg': ['jid="1234"']}`` ''' fun = low.pop('fun') verify_fun(self.functions, fun) eauth_creds = dict([(i, low.pop(i)) for i in [ 'username', 'password', 'eauth', 'token', 'client', 'user', 'key', ] if i in low]) # Run name=value args through parse_input. We don't need to run kwargs # through because there is no way to send name=value strings in the low # dict other than by including an `arg` array. _arg, _kwarg = salt.utils.args.parse_input( low.pop('arg', []), condition=False) _kwarg.update(low.pop('kwarg', {})) # If anything hasn't been pop()'ed out of low by this point it must be # an old-style kwarg. _kwarg.update(low) # Finally, mung our kwargs to a format suitable for the byzantine # load_args_and_kwargs so that we can introspect the function being # called and fish for invalid kwargs. munged = [] munged.extend(_arg) munged.append(dict(__kwarg__=True, **_kwarg)) arg, kwarg = salt.minion.load_args_and_kwargs( self.functions[fun], munged, ignore_invalid=True) return dict(fun=fun, kwarg={'kwarg': kwarg, 'arg': arg}, **eauth_creds)
Format the low data for RunnerClient()'s master_call() function This also normalizes the following low data formats to a single, common low data structure. Old-style low: ``{'fun': 'jobs.lookup_jid', 'jid': '1234'}`` New-style: ``{'fun': 'jobs.lookup_jid', 'kwarg': {'jid': '1234'}}`` CLI-style: ``{'fun': 'jobs.lookup_jid', 'arg': ['jid="1234"']}``
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runner.py#L66-L107
[ "def parse_input(args, kwargs=None, condition=True, no_parse=None):\n '''\n Parse out the args and kwargs from a list of input values. Optionally,\n return the args and kwargs without passing them to condition_input().\n\n Don't pull args with key=val apart if it has a newline in it.\n '''\n if no_parse is None:\n no_parse = ()\n if kwargs is None:\n kwargs = {}\n _args = []\n _kwargs = {}\n for arg in args:\n if isinstance(arg, six.string_types):\n arg_name, arg_value = parse_kwarg(arg)\n if arg_name:\n _kwargs[arg_name] = yamlify_arg(arg_value) \\\n if arg_name not in no_parse \\\n else arg_value\n else:\n _args.append(yamlify_arg(arg))\n elif isinstance(arg, dict):\n # Yes, we're popping this key off and adding it back if\n # condition_input is called below, but this is the only way to\n # gracefully handle both CLI and API input.\n if arg.pop('__kwarg__', False) is True:\n _kwargs.update(arg)\n else:\n _args.append(arg)\n else:\n _args.append(arg)\n _kwargs.update(kwargs)\n if condition:\n return condition_input(_args, _kwargs)\n return _args, _kwargs\n", "def load_args_and_kwargs(func, args, data=None, ignore_invalid=False):\n '''\n Detect the args and kwargs that need to be passed to a function call, and\n check them against what was passed.\n '''\n argspec = salt.utils.args.get_function_argspec(func)\n _args = []\n _kwargs = {}\n invalid_kwargs = []\n\n for arg in args:\n if isinstance(arg, dict) and arg.pop('__kwarg__', False) is True:\n # if the arg is a dict with __kwarg__ == True, then its a kwarg\n for key, val in six.iteritems(arg):\n if argspec.keywords or key in argspec.args:\n # Function supports **kwargs or is a positional argument to\n # the function.\n _kwargs[key] = val\n else:\n # **kwargs not in argspec and parsed argument name not in\n # list of positional arguments. This keyword argument is\n # invalid.\n invalid_kwargs.append('{0}={1}'.format(key, val))\n continue\n\n else:\n string_kwarg = salt.utils.args.parse_input([arg], condition=False)[1] # pylint: disable=W0632\n if string_kwarg:\n if argspec.keywords or next(six.iterkeys(string_kwarg)) in argspec.args:\n # Function supports **kwargs or is a positional argument to\n # the function.\n _kwargs.update(string_kwarg)\n else:\n # **kwargs not in argspec and parsed argument name not in\n # list of positional arguments. This keyword argument is\n # invalid.\n for key, val in six.iteritems(string_kwarg):\n invalid_kwargs.append('{0}={1}'.format(key, val))\n else:\n _args.append(arg)\n\n if invalid_kwargs and not ignore_invalid:\n salt.utils.args.invalid_kwargs(invalid_kwargs)\n\n if argspec.keywords and isinstance(data, dict):\n # this function accepts **kwargs, pack in the publish data\n for key, val in six.iteritems(data):\n _kwargs['__pub_{0}'.format(key)] = val\n\n return _args, _kwargs\n", "def verify_fun(lazy_obj, fun):\n '''\n Check that the function passed really exists\n '''\n if not fun:\n raise salt.exceptions.SaltInvocationError(\n 'Must specify a function to run!\\n'\n 'ex: manage.up'\n )\n if fun not in lazy_obj:\n # If the requested function isn't available, lets say why\n raise salt.exceptions.CommandExecutionError(lazy_obj.missing_fun_string(fun))\n" ]
class RunnerClient(mixins.SyncClientMixin, mixins.AsyncClientMixin, object): ''' The interface used by the :command:`salt-run` CLI tool on the Salt Master It executes :ref:`runner modules <all-salt.runners>` which run on the Salt Master. Importing and using ``RunnerClient`` must be done on the same machine as the Salt Master and it must be done using the same user that the Salt Master is running as. Salt's :conf_master:`external_auth` can be used to authenticate calls. The eauth user must be authorized to execute runner modules: (``@runner``). Only the :py:meth:`master_call` below supports eauth. ''' client = 'runner' tag_prefix = 'run' def __init__(self, opts): self.opts = opts self.context = {} @property def functions(self): if not hasattr(self, '_functions'): if not hasattr(self, 'utils'): self.utils = salt.loader.utils(self.opts) # Must be self.functions for mixin to work correctly :-/ try: self._functions = salt.loader.runner( self.opts, utils=self.utils, context=self.context) except AttributeError: # Just in case self.utils is still not present (perhaps due to # problems with the loader), load the runner funcs without them self._functions = salt.loader.runner( self.opts, context=self.context) return self._functions def cmd_async(self, low): ''' Execute a runner function asynchronously; eauth is respected This function requires that :conf_master:`external_auth` is configured and the user is authorized to execute runner functions: (``@runner``). .. code-block:: python runner.eauth_async({ 'fun': 'jobs.list_jobs', 'username': 'saltdev', 'password': 'saltdev', 'eauth': 'pam', }) ''' reformatted_low = self._reformat_low(low) return mixins.AsyncClientMixin.cmd_async(self, reformatted_low) def cmd_sync(self, low, timeout=None, full_return=False): ''' Execute a runner function synchronously; eauth is respected This function requires that :conf_master:`external_auth` is configured and the user is authorized to execute runner functions: (``@runner``). .. code-block:: python runner.eauth_sync({ 'fun': 'jobs.list_jobs', 'username': 'saltdev', 'password': 'saltdev', 'eauth': 'pam', }) ''' reformatted_low = self._reformat_low(low) return mixins.SyncClientMixin.cmd_sync(self, reformatted_low, timeout, full_return) def cmd(self, fun, arg=None, pub_data=None, kwarg=None, print_event=True, full_return=False): ''' Execute a function ''' return super(RunnerClient, self).cmd(fun, arg, pub_data, kwarg, print_event, full_return)
saltstack/salt
salt/runner.py
RunnerClient.cmd_async
python
def cmd_async(self, low): ''' Execute a runner function asynchronously; eauth is respected This function requires that :conf_master:`external_auth` is configured and the user is authorized to execute runner functions: (``@runner``). .. code-block:: python runner.eauth_async({ 'fun': 'jobs.list_jobs', 'username': 'saltdev', 'password': 'saltdev', 'eauth': 'pam', }) ''' reformatted_low = self._reformat_low(low) return mixins.AsyncClientMixin.cmd_async(self, reformatted_low)
Execute a runner function asynchronously; eauth is respected This function requires that :conf_master:`external_auth` is configured and the user is authorized to execute runner functions: (``@runner``). .. code-block:: python runner.eauth_async({ 'fun': 'jobs.list_jobs', 'username': 'saltdev', 'password': 'saltdev', 'eauth': 'pam', })
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runner.py#L109-L127
[ "def cmd_async(self, low):\n '''\n Execute a function asynchronously; eauth is respected\n\n This function requires that :conf_master:`external_auth` is configured\n and the user is authorized\n\n .. code-block:: python\n\n >>> wheel.cmd_async({\n 'fun': 'key.finger',\n 'match': 'jerry',\n 'eauth': 'auto',\n 'username': 'saltdev',\n 'password': 'saltdev',\n })\n {'jid': '20131219224744416681', 'tag': 'salt/wheel/20131219224744416681'}\n '''\n return self.master_call(**low)\n", "def _reformat_low(self, low):\n '''\n Format the low data for RunnerClient()'s master_call() function\n\n This also normalizes the following low data formats to a single, common\n low data structure.\n\n Old-style low: ``{'fun': 'jobs.lookup_jid', 'jid': '1234'}``\n New-style: ``{'fun': 'jobs.lookup_jid', 'kwarg': {'jid': '1234'}}``\n CLI-style: ``{'fun': 'jobs.lookup_jid', 'arg': ['jid=\"1234\"']}``\n '''\n fun = low.pop('fun')\n verify_fun(self.functions, fun)\n\n eauth_creds = dict([(i, low.pop(i)) for i in [\n 'username', 'password', 'eauth', 'token', 'client', 'user', 'key',\n ] if i in low])\n\n # Run name=value args through parse_input. We don't need to run kwargs\n # through because there is no way to send name=value strings in the low\n # dict other than by including an `arg` array.\n _arg, _kwarg = salt.utils.args.parse_input(\n low.pop('arg', []), condition=False)\n _kwarg.update(low.pop('kwarg', {}))\n\n # If anything hasn't been pop()'ed out of low by this point it must be\n # an old-style kwarg.\n _kwarg.update(low)\n\n # Finally, mung our kwargs to a format suitable for the byzantine\n # load_args_and_kwargs so that we can introspect the function being\n # called and fish for invalid kwargs.\n munged = []\n munged.extend(_arg)\n munged.append(dict(__kwarg__=True, **_kwarg))\n arg, kwarg = salt.minion.load_args_and_kwargs(\n self.functions[fun],\n munged,\n ignore_invalid=True)\n\n return dict(fun=fun, kwarg={'kwarg': kwarg, 'arg': arg},\n **eauth_creds)\n" ]
class RunnerClient(mixins.SyncClientMixin, mixins.AsyncClientMixin, object): ''' The interface used by the :command:`salt-run` CLI tool on the Salt Master It executes :ref:`runner modules <all-salt.runners>` which run on the Salt Master. Importing and using ``RunnerClient`` must be done on the same machine as the Salt Master and it must be done using the same user that the Salt Master is running as. Salt's :conf_master:`external_auth` can be used to authenticate calls. The eauth user must be authorized to execute runner modules: (``@runner``). Only the :py:meth:`master_call` below supports eauth. ''' client = 'runner' tag_prefix = 'run' def __init__(self, opts): self.opts = opts self.context = {} @property def functions(self): if not hasattr(self, '_functions'): if not hasattr(self, 'utils'): self.utils = salt.loader.utils(self.opts) # Must be self.functions for mixin to work correctly :-/ try: self._functions = salt.loader.runner( self.opts, utils=self.utils, context=self.context) except AttributeError: # Just in case self.utils is still not present (perhaps due to # problems with the loader), load the runner funcs without them self._functions = salt.loader.runner( self.opts, context=self.context) return self._functions def _reformat_low(self, low): ''' Format the low data for RunnerClient()'s master_call() function This also normalizes the following low data formats to a single, common low data structure. Old-style low: ``{'fun': 'jobs.lookup_jid', 'jid': '1234'}`` New-style: ``{'fun': 'jobs.lookup_jid', 'kwarg': {'jid': '1234'}}`` CLI-style: ``{'fun': 'jobs.lookup_jid', 'arg': ['jid="1234"']}`` ''' fun = low.pop('fun') verify_fun(self.functions, fun) eauth_creds = dict([(i, low.pop(i)) for i in [ 'username', 'password', 'eauth', 'token', 'client', 'user', 'key', ] if i in low]) # Run name=value args through parse_input. We don't need to run kwargs # through because there is no way to send name=value strings in the low # dict other than by including an `arg` array. _arg, _kwarg = salt.utils.args.parse_input( low.pop('arg', []), condition=False) _kwarg.update(low.pop('kwarg', {})) # If anything hasn't been pop()'ed out of low by this point it must be # an old-style kwarg. _kwarg.update(low) # Finally, mung our kwargs to a format suitable for the byzantine # load_args_and_kwargs so that we can introspect the function being # called and fish for invalid kwargs. munged = [] munged.extend(_arg) munged.append(dict(__kwarg__=True, **_kwarg)) arg, kwarg = salt.minion.load_args_and_kwargs( self.functions[fun], munged, ignore_invalid=True) return dict(fun=fun, kwarg={'kwarg': kwarg, 'arg': arg}, **eauth_creds) def cmd_sync(self, low, timeout=None, full_return=False): ''' Execute a runner function synchronously; eauth is respected This function requires that :conf_master:`external_auth` is configured and the user is authorized to execute runner functions: (``@runner``). .. code-block:: python runner.eauth_sync({ 'fun': 'jobs.list_jobs', 'username': 'saltdev', 'password': 'saltdev', 'eauth': 'pam', }) ''' reformatted_low = self._reformat_low(low) return mixins.SyncClientMixin.cmd_sync(self, reformatted_low, timeout, full_return) def cmd(self, fun, arg=None, pub_data=None, kwarg=None, print_event=True, full_return=False): ''' Execute a function ''' return super(RunnerClient, self).cmd(fun, arg, pub_data, kwarg, print_event, full_return)
saltstack/salt
salt/runner.py
RunnerClient.cmd_sync
python
def cmd_sync(self, low, timeout=None, full_return=False): ''' Execute a runner function synchronously; eauth is respected This function requires that :conf_master:`external_auth` is configured and the user is authorized to execute runner functions: (``@runner``). .. code-block:: python runner.eauth_sync({ 'fun': 'jobs.list_jobs', 'username': 'saltdev', 'password': 'saltdev', 'eauth': 'pam', }) ''' reformatted_low = self._reformat_low(low) return mixins.SyncClientMixin.cmd_sync(self, reformatted_low, timeout, full_return)
Execute a runner function synchronously; eauth is respected This function requires that :conf_master:`external_auth` is configured and the user is authorized to execute runner functions: (``@runner``). .. code-block:: python runner.eauth_sync({ 'fun': 'jobs.list_jobs', 'username': 'saltdev', 'password': 'saltdev', 'eauth': 'pam', })
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runner.py#L129-L146
[ "def cmd_sync(self, low, timeout=None, full_return=False):\n '''\n Execute a runner function synchronously; eauth is respected\n\n This function requires that :conf_master:`external_auth` is configured\n and the user is authorized to execute runner functions: (``@runner``).\n\n .. code-block:: python\n\n runner.eauth_sync({\n 'fun': 'jobs.list_jobs',\n 'username': 'saltdev',\n 'password': 'saltdev',\n 'eauth': 'pam',\n })\n '''\n event = salt.utils.event.get_master_event(self.opts, self.opts['sock_dir'], listen=True)\n job = self.master_call(**low)\n ret_tag = salt.utils.event.tagify('ret', base=job['tag'])\n\n if timeout is None:\n timeout = self.opts.get('rest_timeout', 300)\n ret = event.get_event(tag=ret_tag, full=True, wait=timeout, auto_reconnect=True)\n if ret is None:\n raise salt.exceptions.SaltClientTimeout(\n \"RunnerClient job '{0}' timed out\".format(job['jid']),\n jid=job['jid'])\n\n return ret if full_return else ret['data']['return']\n", "def _reformat_low(self, low):\n '''\n Format the low data for RunnerClient()'s master_call() function\n\n This also normalizes the following low data formats to a single, common\n low data structure.\n\n Old-style low: ``{'fun': 'jobs.lookup_jid', 'jid': '1234'}``\n New-style: ``{'fun': 'jobs.lookup_jid', 'kwarg': {'jid': '1234'}}``\n CLI-style: ``{'fun': 'jobs.lookup_jid', 'arg': ['jid=\"1234\"']}``\n '''\n fun = low.pop('fun')\n verify_fun(self.functions, fun)\n\n eauth_creds = dict([(i, low.pop(i)) for i in [\n 'username', 'password', 'eauth', 'token', 'client', 'user', 'key',\n ] if i in low])\n\n # Run name=value args through parse_input. We don't need to run kwargs\n # through because there is no way to send name=value strings in the low\n # dict other than by including an `arg` array.\n _arg, _kwarg = salt.utils.args.parse_input(\n low.pop('arg', []), condition=False)\n _kwarg.update(low.pop('kwarg', {}))\n\n # If anything hasn't been pop()'ed out of low by this point it must be\n # an old-style kwarg.\n _kwarg.update(low)\n\n # Finally, mung our kwargs to a format suitable for the byzantine\n # load_args_and_kwargs so that we can introspect the function being\n # called and fish for invalid kwargs.\n munged = []\n munged.extend(_arg)\n munged.append(dict(__kwarg__=True, **_kwarg))\n arg, kwarg = salt.minion.load_args_and_kwargs(\n self.functions[fun],\n munged,\n ignore_invalid=True)\n\n return dict(fun=fun, kwarg={'kwarg': kwarg, 'arg': arg},\n **eauth_creds)\n" ]
class RunnerClient(mixins.SyncClientMixin, mixins.AsyncClientMixin, object): ''' The interface used by the :command:`salt-run` CLI tool on the Salt Master It executes :ref:`runner modules <all-salt.runners>` which run on the Salt Master. Importing and using ``RunnerClient`` must be done on the same machine as the Salt Master and it must be done using the same user that the Salt Master is running as. Salt's :conf_master:`external_auth` can be used to authenticate calls. The eauth user must be authorized to execute runner modules: (``@runner``). Only the :py:meth:`master_call` below supports eauth. ''' client = 'runner' tag_prefix = 'run' def __init__(self, opts): self.opts = opts self.context = {} @property def functions(self): if not hasattr(self, '_functions'): if not hasattr(self, 'utils'): self.utils = salt.loader.utils(self.opts) # Must be self.functions for mixin to work correctly :-/ try: self._functions = salt.loader.runner( self.opts, utils=self.utils, context=self.context) except AttributeError: # Just in case self.utils is still not present (perhaps due to # problems with the loader), load the runner funcs without them self._functions = salt.loader.runner( self.opts, context=self.context) return self._functions def _reformat_low(self, low): ''' Format the low data for RunnerClient()'s master_call() function This also normalizes the following low data formats to a single, common low data structure. Old-style low: ``{'fun': 'jobs.lookup_jid', 'jid': '1234'}`` New-style: ``{'fun': 'jobs.lookup_jid', 'kwarg': {'jid': '1234'}}`` CLI-style: ``{'fun': 'jobs.lookup_jid', 'arg': ['jid="1234"']}`` ''' fun = low.pop('fun') verify_fun(self.functions, fun) eauth_creds = dict([(i, low.pop(i)) for i in [ 'username', 'password', 'eauth', 'token', 'client', 'user', 'key', ] if i in low]) # Run name=value args through parse_input. We don't need to run kwargs # through because there is no way to send name=value strings in the low # dict other than by including an `arg` array. _arg, _kwarg = salt.utils.args.parse_input( low.pop('arg', []), condition=False) _kwarg.update(low.pop('kwarg', {})) # If anything hasn't been pop()'ed out of low by this point it must be # an old-style kwarg. _kwarg.update(low) # Finally, mung our kwargs to a format suitable for the byzantine # load_args_and_kwargs so that we can introspect the function being # called and fish for invalid kwargs. munged = [] munged.extend(_arg) munged.append(dict(__kwarg__=True, **_kwarg)) arg, kwarg = salt.minion.load_args_and_kwargs( self.functions[fun], munged, ignore_invalid=True) return dict(fun=fun, kwarg={'kwarg': kwarg, 'arg': arg}, **eauth_creds) def cmd_async(self, low): ''' Execute a runner function asynchronously; eauth is respected This function requires that :conf_master:`external_auth` is configured and the user is authorized to execute runner functions: (``@runner``). .. code-block:: python runner.eauth_async({ 'fun': 'jobs.list_jobs', 'username': 'saltdev', 'password': 'saltdev', 'eauth': 'pam', }) ''' reformatted_low = self._reformat_low(low) return mixins.AsyncClientMixin.cmd_async(self, reformatted_low) def cmd(self, fun, arg=None, pub_data=None, kwarg=None, print_event=True, full_return=False): ''' Execute a function ''' return super(RunnerClient, self).cmd(fun, arg, pub_data, kwarg, print_event, full_return)
saltstack/salt
salt/runner.py
Runner.print_docs
python
def print_docs(self): ''' Print out the documentation! ''' arg = self.opts.get('fun', None) docs = super(Runner, self).get_docs(arg) for fun in sorted(docs): display_output('{0}:'.format(fun), 'text', self.opts) print(docs[fun])
Print out the documentation!
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runner.py#L169-L177
[ "def display_output(data, out=None, opts=None, **kwargs):\n '''\n Print the passed data using the desired output\n '''\n if opts is None:\n opts = {}\n display_data = try_printout(data, out, opts, **kwargs)\n\n output_filename = opts.get('output_file', None)\n log.trace('data = %s', data)\n try:\n # output filename can be either '' or None\n if output_filename:\n if not hasattr(output_filename, 'write'):\n ofh = salt.utils.files.fopen(output_filename, 'a') # pylint: disable=resource-leakage\n fh_opened = True\n else:\n # Filehandle/file-like object\n ofh = output_filename\n fh_opened = False\n\n try:\n fdata = display_data\n if isinstance(fdata, six.text_type):\n try:\n fdata = fdata.encode('utf-8')\n except (UnicodeDecodeError, UnicodeEncodeError):\n # try to let the stream write\n # even if we didn't encode it\n pass\n if fdata:\n ofh.write(salt.utils.stringutils.to_str(fdata))\n ofh.write('\\n')\n finally:\n if fh_opened:\n ofh.close()\n return\n if display_data:\n salt.utils.stringutils.print_cli(display_data)\n except IOError as exc:\n # Only raise if it's NOT a broken pipe\n if exc.errno != errno.EPIPE:\n raise exc\n", "def get_docs(self, arg=None):\n '''\n Return a dictionary of functions and the inline documentation for each\n '''\n if arg:\n if '*' in arg:\n target_mod = arg\n _use_fnmatch = True\n else:\n target_mod = arg + '.' if not arg.endswith('.') else arg\n _use_fnmatch = False\n if _use_fnmatch:\n docs = [(fun, self.functions[fun].__doc__)\n for fun in fnmatch.filter(self.functions, target_mod)]\n else:\n docs = [(fun, self.functions[fun].__doc__)\n for fun in sorted(self.functions)\n if fun == arg or fun.startswith(target_mod)]\n else:\n docs = [(fun, self.functions[fun].__doc__)\n for fun in sorted(self.functions)]\n docs = dict(docs)\n return salt.utils.doc.strip_rst(docs)\n" ]
class Runner(RunnerClient): ''' Execute the salt runner interface ''' def __init__(self, opts): super(Runner, self).__init__(opts) self.returners = salt.loader.returners(opts, self.functions) self.outputters = salt.loader.outputters(opts) # TODO: move to mixin whenever we want a salt-wheel cli def run(self): ''' Execute the runner sequence ''' # Print documentation only if self.opts.get('doc', False): self.print_docs() else: return self._run_runner() def _run_runner(self): ''' Actually execute specific runner :return: ''' import salt.minion ret = {} low = {'fun': self.opts['fun']} try: # Allocate a jid async_pub = self._gen_async_pub() self.jid = async_pub['jid'] fun_args = salt.utils.args.parse_input( self.opts['arg'], no_parse=self.opts.get('no_parse', [])) verify_fun(self.functions, low['fun']) args, kwargs = salt.minion.load_args_and_kwargs( self.functions[low['fun']], fun_args) low['arg'] = args low['kwarg'] = kwargs if self.opts.get('eauth'): if 'token' in self.opts: try: with salt.utils.files.fopen(os.path.join(self.opts['cachedir'], '.root_key'), 'r') as fp_: low['key'] = salt.utils.stringutils.to_unicode(fp_.readline()) except IOError: low['token'] = self.opts['token'] # If using eauth and a token hasn't already been loaded into # low, prompt the user to enter auth credentials if 'token' not in low and 'key' not in low and self.opts['eauth']: # This is expensive. Don't do it unless we need to. import salt.auth resolver = salt.auth.Resolver(self.opts) res = resolver.cli(self.opts['eauth']) if self.opts['mktoken'] and res: tok = resolver.token_cli( self.opts['eauth'], res ) if tok: low['token'] = tok.get('token', '') if not res: log.error('Authentication failed') return ret low.update(res) low['eauth'] = self.opts['eauth'] else: user = salt.utils.user.get_specific_user() if low['fun'] in ['state.orchestrate', 'state.orch', 'state.sls']: low['kwarg']['orchestration_jid'] = async_pub['jid'] # Run the runner! if self.opts.get('async', False): if self.opts.get('eauth'): async_pub = self.cmd_async(low) else: async_pub = self.asynchronous(self.opts['fun'], low, user=user, pub=async_pub) # by default: info will be not enough to be printed out ! log.warning( 'Running in asynchronous mode. Results of this execution may ' 'be collected by attaching to the master event bus or ' 'by examing the master job cache, if configured. ' 'This execution is running under tag %s', async_pub['tag'] ) return async_pub['jid'] # return the jid # otherwise run it in the main process if self.opts.get('eauth'): ret = self.cmd_sync(low) if isinstance(ret, dict) and set(ret) == {'data', 'outputter'}: outputter = ret['outputter'] ret = ret['data'] else: outputter = None display_output(ret, outputter, self.opts) else: ret = self._proc_function(self.opts['fun'], low, user, async_pub['tag'], async_pub['jid'], daemonize=False) except salt.exceptions.SaltException as exc: evt = salt.utils.event.get_event('master', opts=self.opts) evt.fire_event({'success': False, 'return': '{0}'.format(exc), 'retcode': 254, 'fun': self.opts['fun'], 'fun_args': fun_args, 'jid': self.jid}, tag='salt/run/{0}/ret'.format(self.jid)) # Attempt to grab documentation if 'fun' in low: ret = self.get_docs('{0}*'.format(low['fun'])) else: ret = None # If we didn't get docs returned then # return the `not availble` message. if not ret: ret = '{0}'.format(exc) if not self.opts.get('quiet', False): display_output(ret, 'nested', self.opts) else: # If we don't have any values in ret by now, that's a problem. # Otherwise, we shouldn't be overwriting the retcode. if not ret: ret = { 'retcode': salt.defaults.exitcodes.EX_SOFTWARE, } log.debug('Runner return: %s', ret) return ret
saltstack/salt
salt/runner.py
Runner.run
python
def run(self): ''' Execute the runner sequence ''' # Print documentation only if self.opts.get('doc', False): self.print_docs() else: return self._run_runner()
Execute the runner sequence
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runner.py#L180-L188
null
class Runner(RunnerClient): ''' Execute the salt runner interface ''' def __init__(self, opts): super(Runner, self).__init__(opts) self.returners = salt.loader.returners(opts, self.functions) self.outputters = salt.loader.outputters(opts) def print_docs(self): ''' Print out the documentation! ''' arg = self.opts.get('fun', None) docs = super(Runner, self).get_docs(arg) for fun in sorted(docs): display_output('{0}:'.format(fun), 'text', self.opts) print(docs[fun]) # TODO: move to mixin whenever we want a salt-wheel cli def _run_runner(self): ''' Actually execute specific runner :return: ''' import salt.minion ret = {} low = {'fun': self.opts['fun']} try: # Allocate a jid async_pub = self._gen_async_pub() self.jid = async_pub['jid'] fun_args = salt.utils.args.parse_input( self.opts['arg'], no_parse=self.opts.get('no_parse', [])) verify_fun(self.functions, low['fun']) args, kwargs = salt.minion.load_args_and_kwargs( self.functions[low['fun']], fun_args) low['arg'] = args low['kwarg'] = kwargs if self.opts.get('eauth'): if 'token' in self.opts: try: with salt.utils.files.fopen(os.path.join(self.opts['cachedir'], '.root_key'), 'r') as fp_: low['key'] = salt.utils.stringutils.to_unicode(fp_.readline()) except IOError: low['token'] = self.opts['token'] # If using eauth and a token hasn't already been loaded into # low, prompt the user to enter auth credentials if 'token' not in low and 'key' not in low and self.opts['eauth']: # This is expensive. Don't do it unless we need to. import salt.auth resolver = salt.auth.Resolver(self.opts) res = resolver.cli(self.opts['eauth']) if self.opts['mktoken'] and res: tok = resolver.token_cli( self.opts['eauth'], res ) if tok: low['token'] = tok.get('token', '') if not res: log.error('Authentication failed') return ret low.update(res) low['eauth'] = self.opts['eauth'] else: user = salt.utils.user.get_specific_user() if low['fun'] in ['state.orchestrate', 'state.orch', 'state.sls']: low['kwarg']['orchestration_jid'] = async_pub['jid'] # Run the runner! if self.opts.get('async', False): if self.opts.get('eauth'): async_pub = self.cmd_async(low) else: async_pub = self.asynchronous(self.opts['fun'], low, user=user, pub=async_pub) # by default: info will be not enough to be printed out ! log.warning( 'Running in asynchronous mode. Results of this execution may ' 'be collected by attaching to the master event bus or ' 'by examing the master job cache, if configured. ' 'This execution is running under tag %s', async_pub['tag'] ) return async_pub['jid'] # return the jid # otherwise run it in the main process if self.opts.get('eauth'): ret = self.cmd_sync(low) if isinstance(ret, dict) and set(ret) == {'data', 'outputter'}: outputter = ret['outputter'] ret = ret['data'] else: outputter = None display_output(ret, outputter, self.opts) else: ret = self._proc_function(self.opts['fun'], low, user, async_pub['tag'], async_pub['jid'], daemonize=False) except salt.exceptions.SaltException as exc: evt = salt.utils.event.get_event('master', opts=self.opts) evt.fire_event({'success': False, 'return': '{0}'.format(exc), 'retcode': 254, 'fun': self.opts['fun'], 'fun_args': fun_args, 'jid': self.jid}, tag='salt/run/{0}/ret'.format(self.jid)) # Attempt to grab documentation if 'fun' in low: ret = self.get_docs('{0}*'.format(low['fun'])) else: ret = None # If we didn't get docs returned then # return the `not availble` message. if not ret: ret = '{0}'.format(exc) if not self.opts.get('quiet', False): display_output(ret, 'nested', self.opts) else: # If we don't have any values in ret by now, that's a problem. # Otherwise, we shouldn't be overwriting the retcode. if not ret: ret = { 'retcode': salt.defaults.exitcodes.EX_SOFTWARE, } log.debug('Runner return: %s', ret) return ret
saltstack/salt
salt/runner.py
Runner._run_runner
python
def _run_runner(self): ''' Actually execute specific runner :return: ''' import salt.minion ret = {} low = {'fun': self.opts['fun']} try: # Allocate a jid async_pub = self._gen_async_pub() self.jid = async_pub['jid'] fun_args = salt.utils.args.parse_input( self.opts['arg'], no_parse=self.opts.get('no_parse', [])) verify_fun(self.functions, low['fun']) args, kwargs = salt.minion.load_args_and_kwargs( self.functions[low['fun']], fun_args) low['arg'] = args low['kwarg'] = kwargs if self.opts.get('eauth'): if 'token' in self.opts: try: with salt.utils.files.fopen(os.path.join(self.opts['cachedir'], '.root_key'), 'r') as fp_: low['key'] = salt.utils.stringutils.to_unicode(fp_.readline()) except IOError: low['token'] = self.opts['token'] # If using eauth and a token hasn't already been loaded into # low, prompt the user to enter auth credentials if 'token' not in low and 'key' not in low and self.opts['eauth']: # This is expensive. Don't do it unless we need to. import salt.auth resolver = salt.auth.Resolver(self.opts) res = resolver.cli(self.opts['eauth']) if self.opts['mktoken'] and res: tok = resolver.token_cli( self.opts['eauth'], res ) if tok: low['token'] = tok.get('token', '') if not res: log.error('Authentication failed') return ret low.update(res) low['eauth'] = self.opts['eauth'] else: user = salt.utils.user.get_specific_user() if low['fun'] in ['state.orchestrate', 'state.orch', 'state.sls']: low['kwarg']['orchestration_jid'] = async_pub['jid'] # Run the runner! if self.opts.get('async', False): if self.opts.get('eauth'): async_pub = self.cmd_async(low) else: async_pub = self.asynchronous(self.opts['fun'], low, user=user, pub=async_pub) # by default: info will be not enough to be printed out ! log.warning( 'Running in asynchronous mode. Results of this execution may ' 'be collected by attaching to the master event bus or ' 'by examing the master job cache, if configured. ' 'This execution is running under tag %s', async_pub['tag'] ) return async_pub['jid'] # return the jid # otherwise run it in the main process if self.opts.get('eauth'): ret = self.cmd_sync(low) if isinstance(ret, dict) and set(ret) == {'data', 'outputter'}: outputter = ret['outputter'] ret = ret['data'] else: outputter = None display_output(ret, outputter, self.opts) else: ret = self._proc_function(self.opts['fun'], low, user, async_pub['tag'], async_pub['jid'], daemonize=False) except salt.exceptions.SaltException as exc: evt = salt.utils.event.get_event('master', opts=self.opts) evt.fire_event({'success': False, 'return': '{0}'.format(exc), 'retcode': 254, 'fun': self.opts['fun'], 'fun_args': fun_args, 'jid': self.jid}, tag='salt/run/{0}/ret'.format(self.jid)) # Attempt to grab documentation if 'fun' in low: ret = self.get_docs('{0}*'.format(low['fun'])) else: ret = None # If we didn't get docs returned then # return the `not availble` message. if not ret: ret = '{0}'.format(exc) if not self.opts.get('quiet', False): display_output(ret, 'nested', self.opts) else: # If we don't have any values in ret by now, that's a problem. # Otherwise, we shouldn't be overwriting the retcode. if not ret: ret = { 'retcode': salt.defaults.exitcodes.EX_SOFTWARE, } log.debug('Runner return: %s', ret) return ret
Actually execute specific runner :return:
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runner.py#L190-L312
null
class Runner(RunnerClient): ''' Execute the salt runner interface ''' def __init__(self, opts): super(Runner, self).__init__(opts) self.returners = salt.loader.returners(opts, self.functions) self.outputters = salt.loader.outputters(opts) def print_docs(self): ''' Print out the documentation! ''' arg = self.opts.get('fun', None) docs = super(Runner, self).get_docs(arg) for fun in sorted(docs): display_output('{0}:'.format(fun), 'text', self.opts) print(docs[fun]) # TODO: move to mixin whenever we want a salt-wheel cli def run(self): ''' Execute the runner sequence ''' # Print documentation only if self.opts.get('doc', False): self.print_docs() else: return self._run_runner()
saltstack/salt
salt/thorium/status.py
reg
python
def reg(name): ''' Activate this register to turn on a minion status tracking register, this register keeps the current status beacon data and the time that each beacon was last checked in. ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} now = time.time() if 'status' not in __reg__: __reg__['status'] = {} __reg__['status']['val'] = {} for event in __events__: if fnmatch.fnmatch(event['tag'], 'salt/beacon/*/status/*'): # Got one! idata = {'recv_time': now} for key in event['data']['data']: if key in ('id', 'recv_time'): continue idata[key] = event['data']['data'][key] __reg__['status']['val'][event['data']['id']] = idata ret['changes'][event['data']['id']] = True return ret
Activate this register to turn on a minion status tracking register, this register keeps the current status beacon data and the time that each beacon was last checked in.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/status.py#L14-L38
null
# -*- coding: utf-8 -*- ''' This thorium state is used to track the status beacon events and keep track of the active status of minions .. versionadded:: 2016.11.0 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import time import fnmatch
saltstack/salt
salt/tops/reclass_adapter.py
top
python
def top(**kwargs): ''' Query |reclass| for the top data (states of the minions). ''' # If reclass is installed, __virtual__ put it onto the search path, so we # don't need to protect against ImportError: # pylint: disable=3rd-party-module-not-gated from reclass.adapters.salt import top as reclass_top from reclass.errors import ReclassException # pylint: enable=3rd-party-module-not-gated try: # Salt's top interface is inconsistent with ext_pillar (see #5786) and # one is expected to extract the arguments to the master_tops plugin # by parsing the configuration file data. I therefore use this adapter # to hide this internality. reclass_opts = __opts__['master_tops']['reclass'] # the source path we used above isn't something reclass needs to care # about, so filter it: filter_out_source_path_option(reclass_opts) # if no inventory_base_uri was specified, initialise it to the first # file_roots of class 'base' (if that exists): set_inventory_base_uri_default(__opts__, kwargs) # Salt expects the top data to be filtered by minion_id, so we better # let it know which minion it is dealing with. Unfortunately, we must # extract these data (see #6930): minion_id = kwargs['opts']['id'] # I purposely do not pass any of __opts__ or __salt__ or __grains__ # to reclass, as I consider those to be Salt-internal and reclass # should not make any assumptions about it. Reclass only needs to know # how it's configured, so: return reclass_top(minion_id, **reclass_opts) except ImportError as e: if 'reclass' in six.text_type(e): raise SaltInvocationError( 'master_tops.reclass: cannot find reclass module ' 'in {0}'.format(sys.path) ) else: raise except TypeError as e: if 'unexpected keyword argument' in six.text_type(e): arg = six.text_type(e).split()[-1] raise SaltInvocationError( 'master_tops.reclass: unexpected option: {0}'.format(arg) ) else: raise except KeyError as e: if 'reclass' in six.text_type(e): raise SaltInvocationError('master_tops.reclass: no configuration ' 'found in master config') else: raise except ReclassException as e: raise SaltInvocationError('master_tops.reclass: {0}'.format(six.text_type(e)))
Query |reclass| for the top data (states of the minions).
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/tops/reclass_adapter.py#L82-L146
[ "def filter_out_source_path_option(opts):\n if 'reclass_source_path' in opts:\n del opts['reclass_source_path']\n", "def set_inventory_base_uri_default(config, opts):\n if 'inventory_base_uri' in opts:\n return\n\n base_roots = config.get('file_roots', {}).get('base', [])\n if base_roots:\n opts['inventory_base_uri'] = base_roots[0]\n" ]
# -*- coding: utf-8 -*- ''' Read tops data from a reclass database .. |reclass| replace:: **reclass** This :ref:`master_tops <master-tops-system>` plugin provides access to the |reclass| database, such that state information (top data) are retrieved from |reclass|. You can find more information about |reclass| at http://reclass.pantsfullofunix.net. To use the plugin, add it to the ``master_tops`` list in the Salt master config and tell |reclass| by way of a few options how and where to find the inventory: .. code-block:: yaml master_tops: reclass: storage_type: yaml_fs inventory_base_uri: /srv/salt This would cause |reclass| to read the inventory from YAML files in ``/srv/salt/nodes`` and ``/srv/salt/classes``. If you are also using |reclass| as ``ext_pillar`` plugin, and you want to avoid having to specify the same information for both, use YAML anchors (take note of the differing data types for ``ext_pillar`` and ``master_tops``): .. code-block:: yaml reclass: &reclass storage_type: yaml_fs inventory_base_uri: /srv/salt reclass_source_path: ~/code/reclass ext_pillar: - reclass: *reclass master_tops: reclass: *reclass If you want to run reclass from source, rather than installing it, you can either let the master know via the ``PYTHONPATH`` environment variable, or by setting the configuration option, like in the example above. ''' from __future__ import absolute_import, print_function, unicode_literals # This file cannot be called reclass.py, because then the module import would # not work. Thanks to the __virtual__ function, however, the plugin still # responds to the name 'reclass'. import sys from salt.utils.reclass import ( prepend_reclass_source_path, filter_out_source_path_option, set_inventory_base_uri_default ) from salt.exceptions import SaltInvocationError from salt.ext import six # Define the module's virtual name __virtualname__ = 'reclass' def __virtual__(retry=False): try: import reclass # pylint: disable=unused-import return __virtualname__ except ImportError: if retry: return False opts = __opts__.get('master_tops', {}).get('reclass', {}) prepend_reclass_source_path(opts) return __virtual__(retry=True)
saltstack/salt
salt/modules/boto_datapipeline.py
create_pipeline
python
def create_pipeline(name, unique_id, description='', region=None, key=None, keyid=None, profile=None): ''' Create a new, empty pipeline. This function is idempotent. CLI example: .. code-block:: bash salt myminion boto_datapipeline.create_pipeline my_name my_unique_id ''' client = _get_client(region, key, keyid, profile) r = {} try: response = client.create_pipeline( name=name, uniqueId=unique_id, description=description, ) r['result'] = response['pipelineId'] except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r
Create a new, empty pipeline. This function is idempotent. CLI example: .. code-block:: bash salt myminion boto_datapipeline.create_pipeline my_name my_unique_id
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_datapipeline.py#L57-L79
[ "def _get_client(region, key, keyid, profile):\n '''\n Get a boto connection to Data Pipeline.\n '''\n session = _get_session(region, key, keyid, profile)\n if not session:\n log.error(\"Failed to get datapipeline client.\")\n return None\n\n return session.client('datapipeline')\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon Data Pipeline .. versionadded:: 2016.3.0 :depends: boto3 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import Salt libs from salt.ext import six import salt.utils.versions log = logging.getLogger(__name__) try: import boto3 import botocore.exceptions boto3.set_stream_logger(level=logging.CRITICAL) logging.getLogger('botocore').setLevel(logging.CRITICAL) HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False def __virtual__(): ''' Only load if boto3 libraries exists. ''' return salt.utils.versions.check_boto_reqs(check_boto=False) def activate_pipeline(pipeline_id, region=None, key=None, keyid=None, profile=None): ''' Start processing pipeline tasks. This function is idempotent. CLI example: .. code-block:: bash salt myminion boto_datapipeline.activate_pipeline my_pipeline_id ''' client = _get_client(region, key, keyid, profile) r = {} try: client.activate_pipeline(pipelineId=pipeline_id) r['result'] = True except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def delete_pipeline(pipeline_id, region=None, key=None, keyid=None, profile=None): ''' Delete a pipeline, its pipeline definition, and its run history. This function is idempotent. CLI example: .. code-block:: bash salt myminion boto_datapipeline.delete_pipeline my_pipeline_id ''' client = _get_client(region, key, keyid, profile) r = {} try: client.delete_pipeline(pipelineId=pipeline_id) r['result'] = True except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def describe_pipelines(pipeline_ids, region=None, key=None, keyid=None, profile=None): ''' Retrieve metadata about one or more pipelines. CLI example: .. code-block:: bash salt myminion boto_datapipeline.describe_pipelines ['my_pipeline_id'] ''' client = _get_client(region, key, keyid, profile) r = {} try: r['result'] = client.describe_pipelines(pipelineIds=pipeline_ids) except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def get_pipeline_definition(pipeline_id, version='latest', region=None, key=None, keyid=None, profile=None): ''' Get the definition of the specified pipeline. CLI example: .. code-block:: bash salt myminion boto_datapipeline.get_pipeline_definition my_pipeline_id ''' client = _get_client(region, key, keyid, profile) r = {} try: r['result'] = client.get_pipeline_definition( pipelineId=pipeline_id, version=version, ) except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def list_pipelines(region=None, key=None, keyid=None, profile=None): ''' Get a list of pipeline ids and names for all pipelines. CLI Example: .. code-block:: bash salt myminion boto_datapipeline.list_pipelines profile=myprofile ''' client = _get_client(region, key, keyid, profile) r = {} try: paginator = client.get_paginator('list_pipelines') pipelines = [] for page in paginator.paginate(): pipelines += page['pipelineIdList'] r['result'] = pipelines except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def pipeline_id_from_name(name, region=None, key=None, keyid=None, profile=None): ''' Get the pipeline id, if it exists, for the given name. CLI example: .. code-block:: bash salt myminion boto_datapipeline.pipeline_id_from_name my_pipeline_name ''' r = {} result_pipelines = list_pipelines() if 'error' in result_pipelines: return result_pipelines for pipeline in result_pipelines['result']: if pipeline['name'] == name: r['result'] = pipeline['id'] return r r['error'] = 'No pipeline found with name={0}'.format(name) return r def put_pipeline_definition(pipeline_id, pipeline_objects, parameter_objects=None, parameter_values=None, region=None, key=None, keyid=None, profile=None): ''' Add tasks, schedules, and preconditions to the specified pipeline. This function is idempotent and will replace an existing definition. CLI example: .. code-block:: bash salt myminion boto_datapipeline.put_pipeline_definition my_pipeline_id my_pipeline_objects ''' parameter_objects = parameter_objects or [] parameter_values = parameter_values or [] client = _get_client(region, key, keyid, profile) r = {} try: response = client.put_pipeline_definition( pipelineId=pipeline_id, pipelineObjects=pipeline_objects, parameterObjects=parameter_objects, parameterValues=parameter_values, ) if response['errored']: r['error'] = response['validationErrors'] else: r['result'] = response except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def _get_client(region, key, keyid, profile): ''' Get a boto connection to Data Pipeline. ''' session = _get_session(region, key, keyid, profile) if not session: log.error("Failed to get datapipeline client.") return None return session.client('datapipeline') def _get_session(region, key, keyid, profile): ''' Get a boto3 session ''' if profile: if isinstance(profile, six.string_types): _profile = __salt__['config.option'](profile) elif isinstance(profile, dict): _profile = profile key = _profile.get('key', None) keyid = _profile.get('keyid', None) region = _profile.get('region', None) if not region and __salt__['config.option']('datapipeline.region'): region = __salt__['config.option']('datapipeline.region') if not region: region = 'us-east-1' return boto3.session.Session( region_name=region, aws_secret_access_key=key, aws_access_key_id=keyid, )
saltstack/salt
salt/modules/boto_datapipeline.py
delete_pipeline
python
def delete_pipeline(pipeline_id, region=None, key=None, keyid=None, profile=None): ''' Delete a pipeline, its pipeline definition, and its run history. This function is idempotent. CLI example: .. code-block:: bash salt myminion boto_datapipeline.delete_pipeline my_pipeline_id ''' client = _get_client(region, key, keyid, profile) r = {} try: client.delete_pipeline(pipelineId=pipeline_id) r['result'] = True except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r
Delete a pipeline, its pipeline definition, and its run history. This function is idempotent. CLI example: .. code-block:: bash salt myminion boto_datapipeline.delete_pipeline my_pipeline_id
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_datapipeline.py#L82-L99
[ "def _get_client(region, key, keyid, profile):\n '''\n Get a boto connection to Data Pipeline.\n '''\n session = _get_session(region, key, keyid, profile)\n if not session:\n log.error(\"Failed to get datapipeline client.\")\n return None\n\n return session.client('datapipeline')\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon Data Pipeline .. versionadded:: 2016.3.0 :depends: boto3 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import Salt libs from salt.ext import six import salt.utils.versions log = logging.getLogger(__name__) try: import boto3 import botocore.exceptions boto3.set_stream_logger(level=logging.CRITICAL) logging.getLogger('botocore').setLevel(logging.CRITICAL) HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False def __virtual__(): ''' Only load if boto3 libraries exists. ''' return salt.utils.versions.check_boto_reqs(check_boto=False) def activate_pipeline(pipeline_id, region=None, key=None, keyid=None, profile=None): ''' Start processing pipeline tasks. This function is idempotent. CLI example: .. code-block:: bash salt myminion boto_datapipeline.activate_pipeline my_pipeline_id ''' client = _get_client(region, key, keyid, profile) r = {} try: client.activate_pipeline(pipelineId=pipeline_id) r['result'] = True except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def create_pipeline(name, unique_id, description='', region=None, key=None, keyid=None, profile=None): ''' Create a new, empty pipeline. This function is idempotent. CLI example: .. code-block:: bash salt myminion boto_datapipeline.create_pipeline my_name my_unique_id ''' client = _get_client(region, key, keyid, profile) r = {} try: response = client.create_pipeline( name=name, uniqueId=unique_id, description=description, ) r['result'] = response['pipelineId'] except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def describe_pipelines(pipeline_ids, region=None, key=None, keyid=None, profile=None): ''' Retrieve metadata about one or more pipelines. CLI example: .. code-block:: bash salt myminion boto_datapipeline.describe_pipelines ['my_pipeline_id'] ''' client = _get_client(region, key, keyid, profile) r = {} try: r['result'] = client.describe_pipelines(pipelineIds=pipeline_ids) except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def get_pipeline_definition(pipeline_id, version='latest', region=None, key=None, keyid=None, profile=None): ''' Get the definition of the specified pipeline. CLI example: .. code-block:: bash salt myminion boto_datapipeline.get_pipeline_definition my_pipeline_id ''' client = _get_client(region, key, keyid, profile) r = {} try: r['result'] = client.get_pipeline_definition( pipelineId=pipeline_id, version=version, ) except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def list_pipelines(region=None, key=None, keyid=None, profile=None): ''' Get a list of pipeline ids and names for all pipelines. CLI Example: .. code-block:: bash salt myminion boto_datapipeline.list_pipelines profile=myprofile ''' client = _get_client(region, key, keyid, profile) r = {} try: paginator = client.get_paginator('list_pipelines') pipelines = [] for page in paginator.paginate(): pipelines += page['pipelineIdList'] r['result'] = pipelines except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def pipeline_id_from_name(name, region=None, key=None, keyid=None, profile=None): ''' Get the pipeline id, if it exists, for the given name. CLI example: .. code-block:: bash salt myminion boto_datapipeline.pipeline_id_from_name my_pipeline_name ''' r = {} result_pipelines = list_pipelines() if 'error' in result_pipelines: return result_pipelines for pipeline in result_pipelines['result']: if pipeline['name'] == name: r['result'] = pipeline['id'] return r r['error'] = 'No pipeline found with name={0}'.format(name) return r def put_pipeline_definition(pipeline_id, pipeline_objects, parameter_objects=None, parameter_values=None, region=None, key=None, keyid=None, profile=None): ''' Add tasks, schedules, and preconditions to the specified pipeline. This function is idempotent and will replace an existing definition. CLI example: .. code-block:: bash salt myminion boto_datapipeline.put_pipeline_definition my_pipeline_id my_pipeline_objects ''' parameter_objects = parameter_objects or [] parameter_values = parameter_values or [] client = _get_client(region, key, keyid, profile) r = {} try: response = client.put_pipeline_definition( pipelineId=pipeline_id, pipelineObjects=pipeline_objects, parameterObjects=parameter_objects, parameterValues=parameter_values, ) if response['errored']: r['error'] = response['validationErrors'] else: r['result'] = response except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def _get_client(region, key, keyid, profile): ''' Get a boto connection to Data Pipeline. ''' session = _get_session(region, key, keyid, profile) if not session: log.error("Failed to get datapipeline client.") return None return session.client('datapipeline') def _get_session(region, key, keyid, profile): ''' Get a boto3 session ''' if profile: if isinstance(profile, six.string_types): _profile = __salt__['config.option'](profile) elif isinstance(profile, dict): _profile = profile key = _profile.get('key', None) keyid = _profile.get('keyid', None) region = _profile.get('region', None) if not region and __salt__['config.option']('datapipeline.region'): region = __salt__['config.option']('datapipeline.region') if not region: region = 'us-east-1' return boto3.session.Session( region_name=region, aws_secret_access_key=key, aws_access_key_id=keyid, )
saltstack/salt
salt/modules/boto_datapipeline.py
describe_pipelines
python
def describe_pipelines(pipeline_ids, region=None, key=None, keyid=None, profile=None): ''' Retrieve metadata about one or more pipelines. CLI example: .. code-block:: bash salt myminion boto_datapipeline.describe_pipelines ['my_pipeline_id'] ''' client = _get_client(region, key, keyid, profile) r = {} try: r['result'] = client.describe_pipelines(pipelineIds=pipeline_ids) except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r
Retrieve metadata about one or more pipelines. CLI example: .. code-block:: bash salt myminion boto_datapipeline.describe_pipelines ['my_pipeline_id']
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_datapipeline.py#L102-L118
[ "def _get_client(region, key, keyid, profile):\n '''\n Get a boto connection to Data Pipeline.\n '''\n session = _get_session(region, key, keyid, profile)\n if not session:\n log.error(\"Failed to get datapipeline client.\")\n return None\n\n return session.client('datapipeline')\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon Data Pipeline .. versionadded:: 2016.3.0 :depends: boto3 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import Salt libs from salt.ext import six import salt.utils.versions log = logging.getLogger(__name__) try: import boto3 import botocore.exceptions boto3.set_stream_logger(level=logging.CRITICAL) logging.getLogger('botocore').setLevel(logging.CRITICAL) HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False def __virtual__(): ''' Only load if boto3 libraries exists. ''' return salt.utils.versions.check_boto_reqs(check_boto=False) def activate_pipeline(pipeline_id, region=None, key=None, keyid=None, profile=None): ''' Start processing pipeline tasks. This function is idempotent. CLI example: .. code-block:: bash salt myminion boto_datapipeline.activate_pipeline my_pipeline_id ''' client = _get_client(region, key, keyid, profile) r = {} try: client.activate_pipeline(pipelineId=pipeline_id) r['result'] = True except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def create_pipeline(name, unique_id, description='', region=None, key=None, keyid=None, profile=None): ''' Create a new, empty pipeline. This function is idempotent. CLI example: .. code-block:: bash salt myminion boto_datapipeline.create_pipeline my_name my_unique_id ''' client = _get_client(region, key, keyid, profile) r = {} try: response = client.create_pipeline( name=name, uniqueId=unique_id, description=description, ) r['result'] = response['pipelineId'] except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def delete_pipeline(pipeline_id, region=None, key=None, keyid=None, profile=None): ''' Delete a pipeline, its pipeline definition, and its run history. This function is idempotent. CLI example: .. code-block:: bash salt myminion boto_datapipeline.delete_pipeline my_pipeline_id ''' client = _get_client(region, key, keyid, profile) r = {} try: client.delete_pipeline(pipelineId=pipeline_id) r['result'] = True except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def get_pipeline_definition(pipeline_id, version='latest', region=None, key=None, keyid=None, profile=None): ''' Get the definition of the specified pipeline. CLI example: .. code-block:: bash salt myminion boto_datapipeline.get_pipeline_definition my_pipeline_id ''' client = _get_client(region, key, keyid, profile) r = {} try: r['result'] = client.get_pipeline_definition( pipelineId=pipeline_id, version=version, ) except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def list_pipelines(region=None, key=None, keyid=None, profile=None): ''' Get a list of pipeline ids and names for all pipelines. CLI Example: .. code-block:: bash salt myminion boto_datapipeline.list_pipelines profile=myprofile ''' client = _get_client(region, key, keyid, profile) r = {} try: paginator = client.get_paginator('list_pipelines') pipelines = [] for page in paginator.paginate(): pipelines += page['pipelineIdList'] r['result'] = pipelines except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def pipeline_id_from_name(name, region=None, key=None, keyid=None, profile=None): ''' Get the pipeline id, if it exists, for the given name. CLI example: .. code-block:: bash salt myminion boto_datapipeline.pipeline_id_from_name my_pipeline_name ''' r = {} result_pipelines = list_pipelines() if 'error' in result_pipelines: return result_pipelines for pipeline in result_pipelines['result']: if pipeline['name'] == name: r['result'] = pipeline['id'] return r r['error'] = 'No pipeline found with name={0}'.format(name) return r def put_pipeline_definition(pipeline_id, pipeline_objects, parameter_objects=None, parameter_values=None, region=None, key=None, keyid=None, profile=None): ''' Add tasks, schedules, and preconditions to the specified pipeline. This function is idempotent and will replace an existing definition. CLI example: .. code-block:: bash salt myminion boto_datapipeline.put_pipeline_definition my_pipeline_id my_pipeline_objects ''' parameter_objects = parameter_objects or [] parameter_values = parameter_values or [] client = _get_client(region, key, keyid, profile) r = {} try: response = client.put_pipeline_definition( pipelineId=pipeline_id, pipelineObjects=pipeline_objects, parameterObjects=parameter_objects, parameterValues=parameter_values, ) if response['errored']: r['error'] = response['validationErrors'] else: r['result'] = response except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def _get_client(region, key, keyid, profile): ''' Get a boto connection to Data Pipeline. ''' session = _get_session(region, key, keyid, profile) if not session: log.error("Failed to get datapipeline client.") return None return session.client('datapipeline') def _get_session(region, key, keyid, profile): ''' Get a boto3 session ''' if profile: if isinstance(profile, six.string_types): _profile = __salt__['config.option'](profile) elif isinstance(profile, dict): _profile = profile key = _profile.get('key', None) keyid = _profile.get('keyid', None) region = _profile.get('region', None) if not region and __salt__['config.option']('datapipeline.region'): region = __salt__['config.option']('datapipeline.region') if not region: region = 'us-east-1' return boto3.session.Session( region_name=region, aws_secret_access_key=key, aws_access_key_id=keyid, )
saltstack/salt
salt/modules/boto_datapipeline.py
list_pipelines
python
def list_pipelines(region=None, key=None, keyid=None, profile=None): ''' Get a list of pipeline ids and names for all pipelines. CLI Example: .. code-block:: bash salt myminion boto_datapipeline.list_pipelines profile=myprofile ''' client = _get_client(region, key, keyid, profile) r = {} try: paginator = client.get_paginator('list_pipelines') pipelines = [] for page in paginator.paginate(): pipelines += page['pipelineIdList'] r['result'] = pipelines except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r
Get a list of pipeline ids and names for all pipelines. CLI Example: .. code-block:: bash salt myminion boto_datapipeline.list_pipelines profile=myprofile
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_datapipeline.py#L144-L164
[ "def _get_client(region, key, keyid, profile):\n '''\n Get a boto connection to Data Pipeline.\n '''\n session = _get_session(region, key, keyid, profile)\n if not session:\n log.error(\"Failed to get datapipeline client.\")\n return None\n\n return session.client('datapipeline')\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon Data Pipeline .. versionadded:: 2016.3.0 :depends: boto3 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import Salt libs from salt.ext import six import salt.utils.versions log = logging.getLogger(__name__) try: import boto3 import botocore.exceptions boto3.set_stream_logger(level=logging.CRITICAL) logging.getLogger('botocore').setLevel(logging.CRITICAL) HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False def __virtual__(): ''' Only load if boto3 libraries exists. ''' return salt.utils.versions.check_boto_reqs(check_boto=False) def activate_pipeline(pipeline_id, region=None, key=None, keyid=None, profile=None): ''' Start processing pipeline tasks. This function is idempotent. CLI example: .. code-block:: bash salt myminion boto_datapipeline.activate_pipeline my_pipeline_id ''' client = _get_client(region, key, keyid, profile) r = {} try: client.activate_pipeline(pipelineId=pipeline_id) r['result'] = True except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def create_pipeline(name, unique_id, description='', region=None, key=None, keyid=None, profile=None): ''' Create a new, empty pipeline. This function is idempotent. CLI example: .. code-block:: bash salt myminion boto_datapipeline.create_pipeline my_name my_unique_id ''' client = _get_client(region, key, keyid, profile) r = {} try: response = client.create_pipeline( name=name, uniqueId=unique_id, description=description, ) r['result'] = response['pipelineId'] except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def delete_pipeline(pipeline_id, region=None, key=None, keyid=None, profile=None): ''' Delete a pipeline, its pipeline definition, and its run history. This function is idempotent. CLI example: .. code-block:: bash salt myminion boto_datapipeline.delete_pipeline my_pipeline_id ''' client = _get_client(region, key, keyid, profile) r = {} try: client.delete_pipeline(pipelineId=pipeline_id) r['result'] = True except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def describe_pipelines(pipeline_ids, region=None, key=None, keyid=None, profile=None): ''' Retrieve metadata about one or more pipelines. CLI example: .. code-block:: bash salt myminion boto_datapipeline.describe_pipelines ['my_pipeline_id'] ''' client = _get_client(region, key, keyid, profile) r = {} try: r['result'] = client.describe_pipelines(pipelineIds=pipeline_ids) except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def get_pipeline_definition(pipeline_id, version='latest', region=None, key=None, keyid=None, profile=None): ''' Get the definition of the specified pipeline. CLI example: .. code-block:: bash salt myminion boto_datapipeline.get_pipeline_definition my_pipeline_id ''' client = _get_client(region, key, keyid, profile) r = {} try: r['result'] = client.get_pipeline_definition( pipelineId=pipeline_id, version=version, ) except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def pipeline_id_from_name(name, region=None, key=None, keyid=None, profile=None): ''' Get the pipeline id, if it exists, for the given name. CLI example: .. code-block:: bash salt myminion boto_datapipeline.pipeline_id_from_name my_pipeline_name ''' r = {} result_pipelines = list_pipelines() if 'error' in result_pipelines: return result_pipelines for pipeline in result_pipelines['result']: if pipeline['name'] == name: r['result'] = pipeline['id'] return r r['error'] = 'No pipeline found with name={0}'.format(name) return r def put_pipeline_definition(pipeline_id, pipeline_objects, parameter_objects=None, parameter_values=None, region=None, key=None, keyid=None, profile=None): ''' Add tasks, schedules, and preconditions to the specified pipeline. This function is idempotent and will replace an existing definition. CLI example: .. code-block:: bash salt myminion boto_datapipeline.put_pipeline_definition my_pipeline_id my_pipeline_objects ''' parameter_objects = parameter_objects or [] parameter_values = parameter_values or [] client = _get_client(region, key, keyid, profile) r = {} try: response = client.put_pipeline_definition( pipelineId=pipeline_id, pipelineObjects=pipeline_objects, parameterObjects=parameter_objects, parameterValues=parameter_values, ) if response['errored']: r['error'] = response['validationErrors'] else: r['result'] = response except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def _get_client(region, key, keyid, profile): ''' Get a boto connection to Data Pipeline. ''' session = _get_session(region, key, keyid, profile) if not session: log.error("Failed to get datapipeline client.") return None return session.client('datapipeline') def _get_session(region, key, keyid, profile): ''' Get a boto3 session ''' if profile: if isinstance(profile, six.string_types): _profile = __salt__['config.option'](profile) elif isinstance(profile, dict): _profile = profile key = _profile.get('key', None) keyid = _profile.get('keyid', None) region = _profile.get('region', None) if not region and __salt__['config.option']('datapipeline.region'): region = __salt__['config.option']('datapipeline.region') if not region: region = 'us-east-1' return boto3.session.Session( region_name=region, aws_secret_access_key=key, aws_access_key_id=keyid, )
saltstack/salt
salt/modules/boto_datapipeline.py
pipeline_id_from_name
python
def pipeline_id_from_name(name, region=None, key=None, keyid=None, profile=None): ''' Get the pipeline id, if it exists, for the given name. CLI example: .. code-block:: bash salt myminion boto_datapipeline.pipeline_id_from_name my_pipeline_name ''' r = {} result_pipelines = list_pipelines() if 'error' in result_pipelines: return result_pipelines for pipeline in result_pipelines['result']: if pipeline['name'] == name: r['result'] = pipeline['id'] return r r['error'] = 'No pipeline found with name={0}'.format(name) return r
Get the pipeline id, if it exists, for the given name. CLI example: .. code-block:: bash salt myminion boto_datapipeline.pipeline_id_from_name my_pipeline_name
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_datapipeline.py#L167-L187
[ "def list_pipelines(region=None, key=None, keyid=None, profile=None):\n '''\n Get a list of pipeline ids and names for all pipelines.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_datapipeline.list_pipelines profile=myprofile\n '''\n client = _get_client(region, key, keyid, profile)\n r = {}\n try:\n paginator = client.get_paginator('list_pipelines')\n pipelines = []\n for page in paginator.paginate():\n pipelines += page['pipelineIdList']\n r['result'] = pipelines\n except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:\n r['error'] = six.text_type(e)\n return r\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon Data Pipeline .. versionadded:: 2016.3.0 :depends: boto3 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import Salt libs from salt.ext import six import salt.utils.versions log = logging.getLogger(__name__) try: import boto3 import botocore.exceptions boto3.set_stream_logger(level=logging.CRITICAL) logging.getLogger('botocore').setLevel(logging.CRITICAL) HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False def __virtual__(): ''' Only load if boto3 libraries exists. ''' return salt.utils.versions.check_boto_reqs(check_boto=False) def activate_pipeline(pipeline_id, region=None, key=None, keyid=None, profile=None): ''' Start processing pipeline tasks. This function is idempotent. CLI example: .. code-block:: bash salt myminion boto_datapipeline.activate_pipeline my_pipeline_id ''' client = _get_client(region, key, keyid, profile) r = {} try: client.activate_pipeline(pipelineId=pipeline_id) r['result'] = True except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def create_pipeline(name, unique_id, description='', region=None, key=None, keyid=None, profile=None): ''' Create a new, empty pipeline. This function is idempotent. CLI example: .. code-block:: bash salt myminion boto_datapipeline.create_pipeline my_name my_unique_id ''' client = _get_client(region, key, keyid, profile) r = {} try: response = client.create_pipeline( name=name, uniqueId=unique_id, description=description, ) r['result'] = response['pipelineId'] except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def delete_pipeline(pipeline_id, region=None, key=None, keyid=None, profile=None): ''' Delete a pipeline, its pipeline definition, and its run history. This function is idempotent. CLI example: .. code-block:: bash salt myminion boto_datapipeline.delete_pipeline my_pipeline_id ''' client = _get_client(region, key, keyid, profile) r = {} try: client.delete_pipeline(pipelineId=pipeline_id) r['result'] = True except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def describe_pipelines(pipeline_ids, region=None, key=None, keyid=None, profile=None): ''' Retrieve metadata about one or more pipelines. CLI example: .. code-block:: bash salt myminion boto_datapipeline.describe_pipelines ['my_pipeline_id'] ''' client = _get_client(region, key, keyid, profile) r = {} try: r['result'] = client.describe_pipelines(pipelineIds=pipeline_ids) except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def get_pipeline_definition(pipeline_id, version='latest', region=None, key=None, keyid=None, profile=None): ''' Get the definition of the specified pipeline. CLI example: .. code-block:: bash salt myminion boto_datapipeline.get_pipeline_definition my_pipeline_id ''' client = _get_client(region, key, keyid, profile) r = {} try: r['result'] = client.get_pipeline_definition( pipelineId=pipeline_id, version=version, ) except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def list_pipelines(region=None, key=None, keyid=None, profile=None): ''' Get a list of pipeline ids and names for all pipelines. CLI Example: .. code-block:: bash salt myminion boto_datapipeline.list_pipelines profile=myprofile ''' client = _get_client(region, key, keyid, profile) r = {} try: paginator = client.get_paginator('list_pipelines') pipelines = [] for page in paginator.paginate(): pipelines += page['pipelineIdList'] r['result'] = pipelines except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def put_pipeline_definition(pipeline_id, pipeline_objects, parameter_objects=None, parameter_values=None, region=None, key=None, keyid=None, profile=None): ''' Add tasks, schedules, and preconditions to the specified pipeline. This function is idempotent and will replace an existing definition. CLI example: .. code-block:: bash salt myminion boto_datapipeline.put_pipeline_definition my_pipeline_id my_pipeline_objects ''' parameter_objects = parameter_objects or [] parameter_values = parameter_values or [] client = _get_client(region, key, keyid, profile) r = {} try: response = client.put_pipeline_definition( pipelineId=pipeline_id, pipelineObjects=pipeline_objects, parameterObjects=parameter_objects, parameterValues=parameter_values, ) if response['errored']: r['error'] = response['validationErrors'] else: r['result'] = response except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def _get_client(region, key, keyid, profile): ''' Get a boto connection to Data Pipeline. ''' session = _get_session(region, key, keyid, profile) if not session: log.error("Failed to get datapipeline client.") return None return session.client('datapipeline') def _get_session(region, key, keyid, profile): ''' Get a boto3 session ''' if profile: if isinstance(profile, six.string_types): _profile = __salt__['config.option'](profile) elif isinstance(profile, dict): _profile = profile key = _profile.get('key', None) keyid = _profile.get('keyid', None) region = _profile.get('region', None) if not region and __salt__['config.option']('datapipeline.region'): region = __salt__['config.option']('datapipeline.region') if not region: region = 'us-east-1' return boto3.session.Session( region_name=region, aws_secret_access_key=key, aws_access_key_id=keyid, )
saltstack/salt
salt/modules/boto_datapipeline.py
put_pipeline_definition
python
def put_pipeline_definition(pipeline_id, pipeline_objects, parameter_objects=None, parameter_values=None, region=None, key=None, keyid=None, profile=None): ''' Add tasks, schedules, and preconditions to the specified pipeline. This function is idempotent and will replace an existing definition. CLI example: .. code-block:: bash salt myminion boto_datapipeline.put_pipeline_definition my_pipeline_id my_pipeline_objects ''' parameter_objects = parameter_objects or [] parameter_values = parameter_values or [] client = _get_client(region, key, keyid, profile) r = {} try: response = client.put_pipeline_definition( pipelineId=pipeline_id, pipelineObjects=pipeline_objects, parameterObjects=parameter_objects, parameterValues=parameter_values, ) if response['errored']: r['error'] = response['validationErrors'] else: r['result'] = response except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r
Add tasks, schedules, and preconditions to the specified pipeline. This function is idempotent and will replace an existing definition. CLI example: .. code-block:: bash salt myminion boto_datapipeline.put_pipeline_definition my_pipeline_id my_pipeline_objects
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_datapipeline.py#L190-L219
[ "def _get_client(region, key, keyid, profile):\n '''\n Get a boto connection to Data Pipeline.\n '''\n session = _get_session(region, key, keyid, profile)\n if not session:\n log.error(\"Failed to get datapipeline client.\")\n return None\n\n return session.client('datapipeline')\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon Data Pipeline .. versionadded:: 2016.3.0 :depends: boto3 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import Salt libs from salt.ext import six import salt.utils.versions log = logging.getLogger(__name__) try: import boto3 import botocore.exceptions boto3.set_stream_logger(level=logging.CRITICAL) logging.getLogger('botocore').setLevel(logging.CRITICAL) HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False def __virtual__(): ''' Only load if boto3 libraries exists. ''' return salt.utils.versions.check_boto_reqs(check_boto=False) def activate_pipeline(pipeline_id, region=None, key=None, keyid=None, profile=None): ''' Start processing pipeline tasks. This function is idempotent. CLI example: .. code-block:: bash salt myminion boto_datapipeline.activate_pipeline my_pipeline_id ''' client = _get_client(region, key, keyid, profile) r = {} try: client.activate_pipeline(pipelineId=pipeline_id) r['result'] = True except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def create_pipeline(name, unique_id, description='', region=None, key=None, keyid=None, profile=None): ''' Create a new, empty pipeline. This function is idempotent. CLI example: .. code-block:: bash salt myminion boto_datapipeline.create_pipeline my_name my_unique_id ''' client = _get_client(region, key, keyid, profile) r = {} try: response = client.create_pipeline( name=name, uniqueId=unique_id, description=description, ) r['result'] = response['pipelineId'] except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def delete_pipeline(pipeline_id, region=None, key=None, keyid=None, profile=None): ''' Delete a pipeline, its pipeline definition, and its run history. This function is idempotent. CLI example: .. code-block:: bash salt myminion boto_datapipeline.delete_pipeline my_pipeline_id ''' client = _get_client(region, key, keyid, profile) r = {} try: client.delete_pipeline(pipelineId=pipeline_id) r['result'] = True except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def describe_pipelines(pipeline_ids, region=None, key=None, keyid=None, profile=None): ''' Retrieve metadata about one or more pipelines. CLI example: .. code-block:: bash salt myminion boto_datapipeline.describe_pipelines ['my_pipeline_id'] ''' client = _get_client(region, key, keyid, profile) r = {} try: r['result'] = client.describe_pipelines(pipelineIds=pipeline_ids) except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def get_pipeline_definition(pipeline_id, version='latest', region=None, key=None, keyid=None, profile=None): ''' Get the definition of the specified pipeline. CLI example: .. code-block:: bash salt myminion boto_datapipeline.get_pipeline_definition my_pipeline_id ''' client = _get_client(region, key, keyid, profile) r = {} try: r['result'] = client.get_pipeline_definition( pipelineId=pipeline_id, version=version, ) except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def list_pipelines(region=None, key=None, keyid=None, profile=None): ''' Get a list of pipeline ids and names for all pipelines. CLI Example: .. code-block:: bash salt myminion boto_datapipeline.list_pipelines profile=myprofile ''' client = _get_client(region, key, keyid, profile) r = {} try: paginator = client.get_paginator('list_pipelines') pipelines = [] for page in paginator.paginate(): pipelines += page['pipelineIdList'] r['result'] = pipelines except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def pipeline_id_from_name(name, region=None, key=None, keyid=None, profile=None): ''' Get the pipeline id, if it exists, for the given name. CLI example: .. code-block:: bash salt myminion boto_datapipeline.pipeline_id_from_name my_pipeline_name ''' r = {} result_pipelines = list_pipelines() if 'error' in result_pipelines: return result_pipelines for pipeline in result_pipelines['result']: if pipeline['name'] == name: r['result'] = pipeline['id'] return r r['error'] = 'No pipeline found with name={0}'.format(name) return r def _get_client(region, key, keyid, profile): ''' Get a boto connection to Data Pipeline. ''' session = _get_session(region, key, keyid, profile) if not session: log.error("Failed to get datapipeline client.") return None return session.client('datapipeline') def _get_session(region, key, keyid, profile): ''' Get a boto3 session ''' if profile: if isinstance(profile, six.string_types): _profile = __salt__['config.option'](profile) elif isinstance(profile, dict): _profile = profile key = _profile.get('key', None) keyid = _profile.get('keyid', None) region = _profile.get('region', None) if not region and __salt__['config.option']('datapipeline.region'): region = __salt__['config.option']('datapipeline.region') if not region: region = 'us-east-1' return boto3.session.Session( region_name=region, aws_secret_access_key=key, aws_access_key_id=keyid, )
saltstack/salt
salt/modules/boto_datapipeline.py
_get_client
python
def _get_client(region, key, keyid, profile): ''' Get a boto connection to Data Pipeline. ''' session = _get_session(region, key, keyid, profile) if not session: log.error("Failed to get datapipeline client.") return None return session.client('datapipeline')
Get a boto connection to Data Pipeline.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_datapipeline.py#L222-L231
[ "def _get_session(region, key, keyid, profile):\n '''\n Get a boto3 session\n '''\n if profile:\n if isinstance(profile, six.string_types):\n _profile = __salt__['config.option'](profile)\n elif isinstance(profile, dict):\n _profile = profile\n key = _profile.get('key', None)\n keyid = _profile.get('keyid', None)\n region = _profile.get('region', None)\n\n if not region and __salt__['config.option']('datapipeline.region'):\n region = __salt__['config.option']('datapipeline.region')\n\n if not region:\n region = 'us-east-1'\n\n return boto3.session.Session(\n region_name=region,\n aws_secret_access_key=key,\n aws_access_key_id=keyid,\n )\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon Data Pipeline .. versionadded:: 2016.3.0 :depends: boto3 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import Salt libs from salt.ext import six import salt.utils.versions log = logging.getLogger(__name__) try: import boto3 import botocore.exceptions boto3.set_stream_logger(level=logging.CRITICAL) logging.getLogger('botocore').setLevel(logging.CRITICAL) HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False def __virtual__(): ''' Only load if boto3 libraries exists. ''' return salt.utils.versions.check_boto_reqs(check_boto=False) def activate_pipeline(pipeline_id, region=None, key=None, keyid=None, profile=None): ''' Start processing pipeline tasks. This function is idempotent. CLI example: .. code-block:: bash salt myminion boto_datapipeline.activate_pipeline my_pipeline_id ''' client = _get_client(region, key, keyid, profile) r = {} try: client.activate_pipeline(pipelineId=pipeline_id) r['result'] = True except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def create_pipeline(name, unique_id, description='', region=None, key=None, keyid=None, profile=None): ''' Create a new, empty pipeline. This function is idempotent. CLI example: .. code-block:: bash salt myminion boto_datapipeline.create_pipeline my_name my_unique_id ''' client = _get_client(region, key, keyid, profile) r = {} try: response = client.create_pipeline( name=name, uniqueId=unique_id, description=description, ) r['result'] = response['pipelineId'] except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def delete_pipeline(pipeline_id, region=None, key=None, keyid=None, profile=None): ''' Delete a pipeline, its pipeline definition, and its run history. This function is idempotent. CLI example: .. code-block:: bash salt myminion boto_datapipeline.delete_pipeline my_pipeline_id ''' client = _get_client(region, key, keyid, profile) r = {} try: client.delete_pipeline(pipelineId=pipeline_id) r['result'] = True except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def describe_pipelines(pipeline_ids, region=None, key=None, keyid=None, profile=None): ''' Retrieve metadata about one or more pipelines. CLI example: .. code-block:: bash salt myminion boto_datapipeline.describe_pipelines ['my_pipeline_id'] ''' client = _get_client(region, key, keyid, profile) r = {} try: r['result'] = client.describe_pipelines(pipelineIds=pipeline_ids) except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def get_pipeline_definition(pipeline_id, version='latest', region=None, key=None, keyid=None, profile=None): ''' Get the definition of the specified pipeline. CLI example: .. code-block:: bash salt myminion boto_datapipeline.get_pipeline_definition my_pipeline_id ''' client = _get_client(region, key, keyid, profile) r = {} try: r['result'] = client.get_pipeline_definition( pipelineId=pipeline_id, version=version, ) except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def list_pipelines(region=None, key=None, keyid=None, profile=None): ''' Get a list of pipeline ids and names for all pipelines. CLI Example: .. code-block:: bash salt myminion boto_datapipeline.list_pipelines profile=myprofile ''' client = _get_client(region, key, keyid, profile) r = {} try: paginator = client.get_paginator('list_pipelines') pipelines = [] for page in paginator.paginate(): pipelines += page['pipelineIdList'] r['result'] = pipelines except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def pipeline_id_from_name(name, region=None, key=None, keyid=None, profile=None): ''' Get the pipeline id, if it exists, for the given name. CLI example: .. code-block:: bash salt myminion boto_datapipeline.pipeline_id_from_name my_pipeline_name ''' r = {} result_pipelines = list_pipelines() if 'error' in result_pipelines: return result_pipelines for pipeline in result_pipelines['result']: if pipeline['name'] == name: r['result'] = pipeline['id'] return r r['error'] = 'No pipeline found with name={0}'.format(name) return r def put_pipeline_definition(pipeline_id, pipeline_objects, parameter_objects=None, parameter_values=None, region=None, key=None, keyid=None, profile=None): ''' Add tasks, schedules, and preconditions to the specified pipeline. This function is idempotent and will replace an existing definition. CLI example: .. code-block:: bash salt myminion boto_datapipeline.put_pipeline_definition my_pipeline_id my_pipeline_objects ''' parameter_objects = parameter_objects or [] parameter_values = parameter_values or [] client = _get_client(region, key, keyid, profile) r = {} try: response = client.put_pipeline_definition( pipelineId=pipeline_id, pipelineObjects=pipeline_objects, parameterObjects=parameter_objects, parameterValues=parameter_values, ) if response['errored']: r['error'] = response['validationErrors'] else: r['result'] = response except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def _get_session(region, key, keyid, profile): ''' Get a boto3 session ''' if profile: if isinstance(profile, six.string_types): _profile = __salt__['config.option'](profile) elif isinstance(profile, dict): _profile = profile key = _profile.get('key', None) keyid = _profile.get('keyid', None) region = _profile.get('region', None) if not region and __salt__['config.option']('datapipeline.region'): region = __salt__['config.option']('datapipeline.region') if not region: region = 'us-east-1' return boto3.session.Session( region_name=region, aws_secret_access_key=key, aws_access_key_id=keyid, )
saltstack/salt
salt/modules/boto_datapipeline.py
_get_session
python
def _get_session(region, key, keyid, profile): ''' Get a boto3 session ''' if profile: if isinstance(profile, six.string_types): _profile = __salt__['config.option'](profile) elif isinstance(profile, dict): _profile = profile key = _profile.get('key', None) keyid = _profile.get('keyid', None) region = _profile.get('region', None) if not region and __salt__['config.option']('datapipeline.region'): region = __salt__['config.option']('datapipeline.region') if not region: region = 'us-east-1' return boto3.session.Session( region_name=region, aws_secret_access_key=key, aws_access_key_id=keyid, )
Get a boto3 session
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_datapipeline.py#L234-L257
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon Data Pipeline .. versionadded:: 2016.3.0 :depends: boto3 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import Salt libs from salt.ext import six import salt.utils.versions log = logging.getLogger(__name__) try: import boto3 import botocore.exceptions boto3.set_stream_logger(level=logging.CRITICAL) logging.getLogger('botocore').setLevel(logging.CRITICAL) HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False def __virtual__(): ''' Only load if boto3 libraries exists. ''' return salt.utils.versions.check_boto_reqs(check_boto=False) def activate_pipeline(pipeline_id, region=None, key=None, keyid=None, profile=None): ''' Start processing pipeline tasks. This function is idempotent. CLI example: .. code-block:: bash salt myminion boto_datapipeline.activate_pipeline my_pipeline_id ''' client = _get_client(region, key, keyid, profile) r = {} try: client.activate_pipeline(pipelineId=pipeline_id) r['result'] = True except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def create_pipeline(name, unique_id, description='', region=None, key=None, keyid=None, profile=None): ''' Create a new, empty pipeline. This function is idempotent. CLI example: .. code-block:: bash salt myminion boto_datapipeline.create_pipeline my_name my_unique_id ''' client = _get_client(region, key, keyid, profile) r = {} try: response = client.create_pipeline( name=name, uniqueId=unique_id, description=description, ) r['result'] = response['pipelineId'] except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def delete_pipeline(pipeline_id, region=None, key=None, keyid=None, profile=None): ''' Delete a pipeline, its pipeline definition, and its run history. This function is idempotent. CLI example: .. code-block:: bash salt myminion boto_datapipeline.delete_pipeline my_pipeline_id ''' client = _get_client(region, key, keyid, profile) r = {} try: client.delete_pipeline(pipelineId=pipeline_id) r['result'] = True except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def describe_pipelines(pipeline_ids, region=None, key=None, keyid=None, profile=None): ''' Retrieve metadata about one or more pipelines. CLI example: .. code-block:: bash salt myminion boto_datapipeline.describe_pipelines ['my_pipeline_id'] ''' client = _get_client(region, key, keyid, profile) r = {} try: r['result'] = client.describe_pipelines(pipelineIds=pipeline_ids) except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def get_pipeline_definition(pipeline_id, version='latest', region=None, key=None, keyid=None, profile=None): ''' Get the definition of the specified pipeline. CLI example: .. code-block:: bash salt myminion boto_datapipeline.get_pipeline_definition my_pipeline_id ''' client = _get_client(region, key, keyid, profile) r = {} try: r['result'] = client.get_pipeline_definition( pipelineId=pipeline_id, version=version, ) except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def list_pipelines(region=None, key=None, keyid=None, profile=None): ''' Get a list of pipeline ids and names for all pipelines. CLI Example: .. code-block:: bash salt myminion boto_datapipeline.list_pipelines profile=myprofile ''' client = _get_client(region, key, keyid, profile) r = {} try: paginator = client.get_paginator('list_pipelines') pipelines = [] for page in paginator.paginate(): pipelines += page['pipelineIdList'] r['result'] = pipelines except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def pipeline_id_from_name(name, region=None, key=None, keyid=None, profile=None): ''' Get the pipeline id, if it exists, for the given name. CLI example: .. code-block:: bash salt myminion boto_datapipeline.pipeline_id_from_name my_pipeline_name ''' r = {} result_pipelines = list_pipelines() if 'error' in result_pipelines: return result_pipelines for pipeline in result_pipelines['result']: if pipeline['name'] == name: r['result'] = pipeline['id'] return r r['error'] = 'No pipeline found with name={0}'.format(name) return r def put_pipeline_definition(pipeline_id, pipeline_objects, parameter_objects=None, parameter_values=None, region=None, key=None, keyid=None, profile=None): ''' Add tasks, schedules, and preconditions to the specified pipeline. This function is idempotent and will replace an existing definition. CLI example: .. code-block:: bash salt myminion boto_datapipeline.put_pipeline_definition my_pipeline_id my_pipeline_objects ''' parameter_objects = parameter_objects or [] parameter_values = parameter_values or [] client = _get_client(region, key, keyid, profile) r = {} try: response = client.put_pipeline_definition( pipelineId=pipeline_id, pipelineObjects=pipeline_objects, parameterObjects=parameter_objects, parameterValues=parameter_values, ) if response['errored']: r['error'] = response['validationErrors'] else: r['result'] = response except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r['error'] = six.text_type(e) return r def _get_client(region, key, keyid, profile): ''' Get a boto connection to Data Pipeline. ''' session = _get_session(region, key, keyid, profile) if not session: log.error("Failed to get datapipeline client.") return None return session.client('datapipeline')
saltstack/salt
salt/modules/qemu_img.py
make_image
python
def make_image(location, size, fmt): ''' Create a blank virtual machine image file of the specified size in megabytes. The image can be created in any format supported by qemu CLI Example: .. code-block:: bash salt '*' qemu_img.make_image /tmp/image.qcow 2048 qcow2 salt '*' qemu_img.make_image /tmp/image.raw 10240 raw ''' if not os.path.isabs(location): return '' if not os.path.isdir(os.path.dirname(location)): return '' if not __salt__['cmd.retcode']( 'qemu-img create -f {0} {1} {2}M'.format( fmt, location, size), python_shell=False): return location return ''
Create a blank virtual machine image file of the specified size in megabytes. The image can be created in any format supported by qemu CLI Example: .. code-block:: bash salt '*' qemu_img.make_image /tmp/image.qcow 2048 qcow2 salt '*' qemu_img.make_image /tmp/image.raw 10240 raw
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/qemu_img.py#L28-L51
null
# -*- coding: utf-8 -*- ''' Qemu-img Command Wrapper ======================== The qemu img command is wrapped for specific functions :depends: qemu-img ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import os # Import salt libs import salt.utils.path def __virtual__(): ''' Only load if qemu-img is installed ''' if salt.utils.path.which('qemu-img'): return 'qemu_img' return (False, 'The qemu_img execution module cannot be loaded: the qemu-img binary is not in the path.') def convert(orig, dest, fmt): ''' Convert an existing disk image to another format using qemu-img CLI Example: .. code-block:: bash salt '*' qemu_img.convert /path/to/original.img /path/to/new.img qcow2 ''' cmd = ('qemu-img', 'convert', '-O', fmt, orig, dest) ret = __salt__['cmd.run_all'](cmd, python_shell=False) if ret['retcode'] == 0: return True else: return ret['stderr']
saltstack/salt
salt/modules/qemu_img.py
convert
python
def convert(orig, dest, fmt): ''' Convert an existing disk image to another format using qemu-img CLI Example: .. code-block:: bash salt '*' qemu_img.convert /path/to/original.img /path/to/new.img qcow2 ''' cmd = ('qemu-img', 'convert', '-O', fmt, orig, dest) ret = __salt__['cmd.run_all'](cmd, python_shell=False) if ret['retcode'] == 0: return True else: return ret['stderr']
Convert an existing disk image to another format using qemu-img CLI Example: .. code-block:: bash salt '*' qemu_img.convert /path/to/original.img /path/to/new.img qcow2
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/qemu_img.py#L54-L69
null
# -*- coding: utf-8 -*- ''' Qemu-img Command Wrapper ======================== The qemu img command is wrapped for specific functions :depends: qemu-img ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import os # Import salt libs import salt.utils.path def __virtual__(): ''' Only load if qemu-img is installed ''' if salt.utils.path.which('qemu-img'): return 'qemu_img' return (False, 'The qemu_img execution module cannot be loaded: the qemu-img binary is not in the path.') def make_image(location, size, fmt): ''' Create a blank virtual machine image file of the specified size in megabytes. The image can be created in any format supported by qemu CLI Example: .. code-block:: bash salt '*' qemu_img.make_image /tmp/image.qcow 2048 qcow2 salt '*' qemu_img.make_image /tmp/image.raw 10240 raw ''' if not os.path.isabs(location): return '' if not os.path.isdir(os.path.dirname(location)): return '' if not __salt__['cmd.retcode']( 'qemu-img create -f {0} {1} {2}M'.format( fmt, location, size), python_shell=False): return location return ''
saltstack/salt
salt/modules/win_network.py
ping
python
def ping(host, timeout=False, return_boolean=False): ''' Performs a ping to a host CLI Example: .. code-block:: bash salt '*' network.ping archlinux.org .. versionadded:: 2016.11.0 Return a True or False instead of ping output. .. code-block:: bash salt '*' network.ping archlinux.org return_boolean=True Set the time to wait for a response in seconds. .. code-block:: bash salt '*' network.ping archlinux.org timeout=3 ''' if timeout: # Windows ping differs by having timeout be for individual echo requests.' # Divide timeout by tries to mimic BSD behaviour. timeout = int(timeout) * 1000 // 4 cmd = ['ping', '-n', '4', '-w', six.text_type(timeout), salt.utils.network.sanitize_host(host)] else: cmd = ['ping', '-n', '4', salt.utils.network.sanitize_host(host)] if return_boolean: ret = __salt__['cmd.run_all'](cmd, python_shell=False) if ret['retcode'] != 0: return False else: return True else: return __salt__['cmd.run'](cmd, python_shell=False)
Performs a ping to a host CLI Example: .. code-block:: bash salt '*' network.ping archlinux.org .. versionadded:: 2016.11.0 Return a True or False instead of ping output. .. code-block:: bash salt '*' network.ping archlinux.org return_boolean=True Set the time to wait for a response in seconds. .. code-block:: bash salt '*' network.ping archlinux.org timeout=3
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_network.py#L69-L107
[ "def sanitize_host(host):\n '''\n Sanitize host string.\n https://tools.ietf.org/html/rfc1123#section-2.1\n '''\n RFC952_characters = ascii_letters + digits + \".-\"\n return \"\".join([c for c in host[0:255] if c in RFC952_characters])\n" ]
# -*- coding: utf-8 -*- ''' Module for gathering and managing network information ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import re import hashlib import datetime import socket # Import Salt libs import salt.utils.network import salt.utils.platform import salt.utils.validate.net from salt.modules.network import (wol, get_hostname, interface, interface_ip, subnets6, ip_in_subnet, convert_cidr, calc_net, get_fqdn, ifacestartswith, iphexval) from salt.utils.functools import namespaced_function as _namespaced_function try: import salt.utils.winapi HAS_DEPENDENCIES = True except ImportError: HAS_DEPENDENCIES = False # Import 3rd party libraries import salt.ext.six as six # pylint: disable=W0611 try: import wmi # pylint: disable=W0611 except ImportError: HAS_DEPENDENCIES = False from salt._compat import ipaddress # Define the module's virtual name __virtualname__ = 'network' def __virtual__(): ''' Only works on Windows systems ''' if not salt.utils.platform.is_windows(): return False, "Module win_network: Only available on Windows" if not HAS_DEPENDENCIES: return False, "Module win_network: Missing dependencies" global wol, get_hostname, interface, interface_ip, subnets6, ip_in_subnet global convert_cidr, calc_net, get_fqdn, ifacestartswith, iphexval wol = _namespaced_function(wol, globals()) get_hostname = _namespaced_function(get_hostname, globals()) interface = _namespaced_function(interface, globals()) interface_ip = _namespaced_function(interface_ip, globals()) subnets6 = _namespaced_function(subnets6, globals()) ip_in_subnet = _namespaced_function(ip_in_subnet, globals()) convert_cidr = _namespaced_function(convert_cidr, globals()) calc_net = _namespaced_function(calc_net, globals()) get_fqdn = _namespaced_function(get_fqdn, globals()) ifacestartswith = _namespaced_function(ifacestartswith, globals()) iphexval = _namespaced_function(iphexval, globals()) return __virtualname__ def netstat(): ''' Return information on open ports and states CLI Example: .. code-block:: bash salt '*' network.netstat ''' ret = [] cmd = ['netstat', '-nao'] lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines() for line in lines: comps = line.split() if line.startswith(' TCP'): ret.append({ 'local-address': comps[1], 'proto': comps[0], 'remote-address': comps[2], 'state': comps[3], 'program': comps[4]}) if line.startswith(' UDP'): ret.append({ 'local-address': comps[1], 'proto': comps[0], 'remote-address': comps[2], 'state': None, 'program': comps[3]}) return ret def traceroute(host): ''' Performs a traceroute to a 3rd party host CLI Example: .. code-block:: bash salt '*' network.traceroute archlinux.org ''' ret = [] cmd = ['tracert', salt.utils.network.sanitize_host(host)] lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines() for line in lines: if ' ' not in line: continue if line.startswith('Trac'): continue if line.startswith('over'): continue comps = line.split() complength = len(comps) # This method still needs to better catch rows of other lengths # For example if some of the ms returns are '*' if complength == 9: result = { 'count': comps[0], 'hostname': comps[7], 'ip': comps[8], 'ms1': comps[1], 'ms2': comps[3], 'ms3': comps[5]} ret.append(result) elif complength == 8: result = { 'count': comps[0], 'hostname': None, 'ip': comps[7], 'ms1': comps[1], 'ms2': comps[3], 'ms3': comps[5]} ret.append(result) else: result = { 'count': comps[0], 'hostname': None, 'ip': None, 'ms1': None, 'ms2': None, 'ms3': None} ret.append(result) return ret def nslookup(host): ''' Query DNS for information about a domain or ip address CLI Example: .. code-block:: bash salt '*' network.nslookup archlinux.org ''' ret = [] addresses = [] cmd = ['nslookup', salt.utils.network.sanitize_host(host)] lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines() for line in lines: if addresses: # We're in the last block listing addresses addresses.append(line.strip()) continue if line.startswith('Non-authoritative'): continue if 'Addresses' in line: comps = line.split(":", 1) addresses.append(comps[1].strip()) continue if ":" in line: comps = line.split(":", 1) ret.append({comps[0].strip(): comps[1].strip()}) if addresses: ret.append({'Addresses': addresses}) return ret def get_route(ip): ''' Return routing information for given destination ip .. versionadded:: 2016.11.5 CLI Example:: salt '*' network.get_route 10.10.10.10 ''' cmd = 'Find-NetRoute -RemoteIPAddress {0}'.format(ip) out = __salt__['cmd.run'](cmd, shell='powershell', python_shell=True) regexp = re.compile( r"^IPAddress\s+:\s(?P<source>[\d\.:]+)?.*" r"^InterfaceAlias\s+:\s(?P<interface>[\w\.\:\-\ ]+)?.*" r"^NextHop\s+:\s(?P<gateway>[\d\.:]+)", flags=re.MULTILINE | re.DOTALL ) m = regexp.search(out) ret = { 'destination': ip, 'gateway': m.group('gateway'), 'interface': m.group('interface'), 'source': m.group('source') } return ret def dig(host): ''' Performs a DNS lookup with dig Note: dig must be installed on the Windows minion CLI Example: .. code-block:: bash salt '*' network.dig archlinux.org ''' cmd = ['dig', salt.utils.network.sanitize_host(host)] return __salt__['cmd.run'](cmd, python_shell=False) def interfaces_names(): ''' Return a list of all the interfaces names CLI Example: .. code-block:: bash salt '*' network.interfaces_names ''' ret = [] with salt.utils.winapi.Com(): c = wmi.WMI() for iface in c.Win32_NetworkAdapter(NetEnabled=True): ret.append(iface.NetConnectionID) return ret def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion CLI Example: .. code-block:: bash salt '*' network.interfaces ''' return salt.utils.network.win_interfaces() def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface CLI Example: .. code-block:: bash salt '*' network.hw_addr 'Wireless Connection #1' ''' return salt.utils.network.hw_addr(iface) # Alias hwaddr to preserve backward compat hwaddr = salt.utils.functools.alias_function(hw_addr, 'hwaddr') def subnets(): ''' Returns a list of subnets to which the host belongs CLI Example: .. code-block:: bash salt '*' network.subnets ''' return salt.utils.network.subnets() def in_subnet(cidr): ''' Returns True if host is within specified subnet, otherwise False CLI Example: .. code-block:: bash salt '*' network.in_subnet 10.0.0.0/16 ''' return salt.utils.network.in_subnet(cidr) def ip_addrs(interface=None, include_loopback=False, cidr=None, type=None): ''' Returns a list of IPv4 addresses assigned to the host. interface Only IP addresses from that interface will be returned. include_loopback : False Include loopback 127.0.0.1 IPv4 address. cidr Describes subnet using CIDR notation and only IPv4 addresses that belong to this subnet will be returned. .. versionchanged:: 2019.2.0 type If option set to 'public' then only public addresses will be returned. Ditto for 'private'. .. versionchanged:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' network.ip_addrs salt '*' network.ip_addrs cidr=10.0.0.0/8 salt '*' network.ip_addrs cidr=192.168.0.0/16 type=private ''' addrs = salt.utils.network.ip_addrs(interface=interface, include_loopback=include_loopback) if cidr: return [i for i in addrs if salt.utils.network.in_subnet(cidr, [i])] else: if type == 'public': return [i for i in addrs if not is_private(i)] elif type == 'private': return [i for i in addrs if is_private(i)] else: return addrs ipaddrs = salt.utils.functools.alias_function(ip_addrs, 'ipaddrs') def ip_addrs6(interface=None, include_loopback=False, cidr=None): ''' Returns a list of IPv6 addresses assigned to the host. interface Only IP addresses from that interface will be returned. include_loopback : False Include loopback ::1 IPv6 address. cidr Describes subnet using CIDR notation and only IPv6 addresses that belong to this subnet will be returned. .. versionchanged:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' network.ip_addrs6 salt '*' network.ip_addrs6 cidr=2000::/3 ''' addrs = salt.utils.network.ip_addrs6(interface=interface, include_loopback=include_loopback) if cidr: return [i for i in addrs if salt.utils.network.in_subnet(cidr, [i])] else: return addrs ipaddrs6 = salt.utils.functools.alias_function(ip_addrs6, 'ipaddrs6') def connect(host, port=None, **kwargs): ''' Test connectivity to a host using a particular port from the minion. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' network.connect archlinux.org 80 salt '*' network.connect archlinux.org 80 timeout=3 salt '*' network.connect archlinux.org 80 timeout=3 family=ipv4 salt '*' network.connect google-public-dns-a.google.com port=53 proto=udp timeout=3 ''' ret = {'result': None, 'comment': ''} if not host: ret['result'] = False ret['comment'] = 'Required argument, host, is missing.' return ret if not port: ret['result'] = False ret['comment'] = 'Required argument, port, is missing.' return ret proto = kwargs.get('proto', 'tcp') timeout = kwargs.get('timeout', 5) family = kwargs.get('family', None) if salt.utils.validate.net.ipv4_addr(host) or salt.utils.validate.net.ipv6_addr(host): address = host else: address = '{0}'.format(salt.utils.network.sanitize_host(host)) try: if proto == 'udp': __proto = socket.SOL_UDP else: __proto = socket.SOL_TCP proto = 'tcp' if family: if family == 'ipv4': __family = socket.AF_INET elif family == 'ipv6': __family = socket.AF_INET6 else: __family = 0 else: __family = 0 (family, socktype, _proto, garbage, _address) = socket.getaddrinfo(address, port, __family, 0, __proto)[0] skt = socket.socket(family, socktype, _proto) skt.settimeout(timeout) if proto == 'udp': # Generate a random string of a # decent size to test UDP connection md5h = hashlib.md5() md5h.update(datetime.datetime.now().strftime('%s')) msg = md5h.hexdigest() skt.sendto(msg, _address) recv, svr = skt.recvfrom(255) skt.close() else: skt.connect(_address) skt.shutdown(2) except Exception as exc: ret['result'] = False ret['comment'] = 'Unable to connect to {0} ({1}) on {2} port {3}'\ .format(host, _address[0], proto, port) return ret ret['result'] = True ret['comment'] = 'Successfully connected to {0} ({1}) on {2} port {3}'\ .format(host, _address[0], proto, port) return ret def is_private(ip_addr): ''' Check if the given IP address is a private address .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' network.is_private 10.0.0.3 ''' return ipaddress.ip_address(ip_addr).is_private
saltstack/salt
salt/modules/win_network.py
netstat
python
def netstat(): ''' Return information on open ports and states CLI Example: .. code-block:: bash salt '*' network.netstat ''' ret = [] cmd = ['netstat', '-nao'] lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines() for line in lines: comps = line.split() if line.startswith(' TCP'): ret.append({ 'local-address': comps[1], 'proto': comps[0], 'remote-address': comps[2], 'state': comps[3], 'program': comps[4]}) if line.startswith(' UDP'): ret.append({ 'local-address': comps[1], 'proto': comps[0], 'remote-address': comps[2], 'state': None, 'program': comps[3]}) return ret
Return information on open ports and states CLI Example: .. code-block:: bash salt '*' network.netstat
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_network.py#L110-L139
null
# -*- coding: utf-8 -*- ''' Module for gathering and managing network information ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import re import hashlib import datetime import socket # Import Salt libs import salt.utils.network import salt.utils.platform import salt.utils.validate.net from salt.modules.network import (wol, get_hostname, interface, interface_ip, subnets6, ip_in_subnet, convert_cidr, calc_net, get_fqdn, ifacestartswith, iphexval) from salt.utils.functools import namespaced_function as _namespaced_function try: import salt.utils.winapi HAS_DEPENDENCIES = True except ImportError: HAS_DEPENDENCIES = False # Import 3rd party libraries import salt.ext.six as six # pylint: disable=W0611 try: import wmi # pylint: disable=W0611 except ImportError: HAS_DEPENDENCIES = False from salt._compat import ipaddress # Define the module's virtual name __virtualname__ = 'network' def __virtual__(): ''' Only works on Windows systems ''' if not salt.utils.platform.is_windows(): return False, "Module win_network: Only available on Windows" if not HAS_DEPENDENCIES: return False, "Module win_network: Missing dependencies" global wol, get_hostname, interface, interface_ip, subnets6, ip_in_subnet global convert_cidr, calc_net, get_fqdn, ifacestartswith, iphexval wol = _namespaced_function(wol, globals()) get_hostname = _namespaced_function(get_hostname, globals()) interface = _namespaced_function(interface, globals()) interface_ip = _namespaced_function(interface_ip, globals()) subnets6 = _namespaced_function(subnets6, globals()) ip_in_subnet = _namespaced_function(ip_in_subnet, globals()) convert_cidr = _namespaced_function(convert_cidr, globals()) calc_net = _namespaced_function(calc_net, globals()) get_fqdn = _namespaced_function(get_fqdn, globals()) ifacestartswith = _namespaced_function(ifacestartswith, globals()) iphexval = _namespaced_function(iphexval, globals()) return __virtualname__ def ping(host, timeout=False, return_boolean=False): ''' Performs a ping to a host CLI Example: .. code-block:: bash salt '*' network.ping archlinux.org .. versionadded:: 2016.11.0 Return a True or False instead of ping output. .. code-block:: bash salt '*' network.ping archlinux.org return_boolean=True Set the time to wait for a response in seconds. .. code-block:: bash salt '*' network.ping archlinux.org timeout=3 ''' if timeout: # Windows ping differs by having timeout be for individual echo requests.' # Divide timeout by tries to mimic BSD behaviour. timeout = int(timeout) * 1000 // 4 cmd = ['ping', '-n', '4', '-w', six.text_type(timeout), salt.utils.network.sanitize_host(host)] else: cmd = ['ping', '-n', '4', salt.utils.network.sanitize_host(host)] if return_boolean: ret = __salt__['cmd.run_all'](cmd, python_shell=False) if ret['retcode'] != 0: return False else: return True else: return __salt__['cmd.run'](cmd, python_shell=False) def traceroute(host): ''' Performs a traceroute to a 3rd party host CLI Example: .. code-block:: bash salt '*' network.traceroute archlinux.org ''' ret = [] cmd = ['tracert', salt.utils.network.sanitize_host(host)] lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines() for line in lines: if ' ' not in line: continue if line.startswith('Trac'): continue if line.startswith('over'): continue comps = line.split() complength = len(comps) # This method still needs to better catch rows of other lengths # For example if some of the ms returns are '*' if complength == 9: result = { 'count': comps[0], 'hostname': comps[7], 'ip': comps[8], 'ms1': comps[1], 'ms2': comps[3], 'ms3': comps[5]} ret.append(result) elif complength == 8: result = { 'count': comps[0], 'hostname': None, 'ip': comps[7], 'ms1': comps[1], 'ms2': comps[3], 'ms3': comps[5]} ret.append(result) else: result = { 'count': comps[0], 'hostname': None, 'ip': None, 'ms1': None, 'ms2': None, 'ms3': None} ret.append(result) return ret def nslookup(host): ''' Query DNS for information about a domain or ip address CLI Example: .. code-block:: bash salt '*' network.nslookup archlinux.org ''' ret = [] addresses = [] cmd = ['nslookup', salt.utils.network.sanitize_host(host)] lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines() for line in lines: if addresses: # We're in the last block listing addresses addresses.append(line.strip()) continue if line.startswith('Non-authoritative'): continue if 'Addresses' in line: comps = line.split(":", 1) addresses.append(comps[1].strip()) continue if ":" in line: comps = line.split(":", 1) ret.append({comps[0].strip(): comps[1].strip()}) if addresses: ret.append({'Addresses': addresses}) return ret def get_route(ip): ''' Return routing information for given destination ip .. versionadded:: 2016.11.5 CLI Example:: salt '*' network.get_route 10.10.10.10 ''' cmd = 'Find-NetRoute -RemoteIPAddress {0}'.format(ip) out = __salt__['cmd.run'](cmd, shell='powershell', python_shell=True) regexp = re.compile( r"^IPAddress\s+:\s(?P<source>[\d\.:]+)?.*" r"^InterfaceAlias\s+:\s(?P<interface>[\w\.\:\-\ ]+)?.*" r"^NextHop\s+:\s(?P<gateway>[\d\.:]+)", flags=re.MULTILINE | re.DOTALL ) m = regexp.search(out) ret = { 'destination': ip, 'gateway': m.group('gateway'), 'interface': m.group('interface'), 'source': m.group('source') } return ret def dig(host): ''' Performs a DNS lookup with dig Note: dig must be installed on the Windows minion CLI Example: .. code-block:: bash salt '*' network.dig archlinux.org ''' cmd = ['dig', salt.utils.network.sanitize_host(host)] return __salt__['cmd.run'](cmd, python_shell=False) def interfaces_names(): ''' Return a list of all the interfaces names CLI Example: .. code-block:: bash salt '*' network.interfaces_names ''' ret = [] with salt.utils.winapi.Com(): c = wmi.WMI() for iface in c.Win32_NetworkAdapter(NetEnabled=True): ret.append(iface.NetConnectionID) return ret def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion CLI Example: .. code-block:: bash salt '*' network.interfaces ''' return salt.utils.network.win_interfaces() def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface CLI Example: .. code-block:: bash salt '*' network.hw_addr 'Wireless Connection #1' ''' return salt.utils.network.hw_addr(iface) # Alias hwaddr to preserve backward compat hwaddr = salt.utils.functools.alias_function(hw_addr, 'hwaddr') def subnets(): ''' Returns a list of subnets to which the host belongs CLI Example: .. code-block:: bash salt '*' network.subnets ''' return salt.utils.network.subnets() def in_subnet(cidr): ''' Returns True if host is within specified subnet, otherwise False CLI Example: .. code-block:: bash salt '*' network.in_subnet 10.0.0.0/16 ''' return salt.utils.network.in_subnet(cidr) def ip_addrs(interface=None, include_loopback=False, cidr=None, type=None): ''' Returns a list of IPv4 addresses assigned to the host. interface Only IP addresses from that interface will be returned. include_loopback : False Include loopback 127.0.0.1 IPv4 address. cidr Describes subnet using CIDR notation and only IPv4 addresses that belong to this subnet will be returned. .. versionchanged:: 2019.2.0 type If option set to 'public' then only public addresses will be returned. Ditto for 'private'. .. versionchanged:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' network.ip_addrs salt '*' network.ip_addrs cidr=10.0.0.0/8 salt '*' network.ip_addrs cidr=192.168.0.0/16 type=private ''' addrs = salt.utils.network.ip_addrs(interface=interface, include_loopback=include_loopback) if cidr: return [i for i in addrs if salt.utils.network.in_subnet(cidr, [i])] else: if type == 'public': return [i for i in addrs if not is_private(i)] elif type == 'private': return [i for i in addrs if is_private(i)] else: return addrs ipaddrs = salt.utils.functools.alias_function(ip_addrs, 'ipaddrs') def ip_addrs6(interface=None, include_loopback=False, cidr=None): ''' Returns a list of IPv6 addresses assigned to the host. interface Only IP addresses from that interface will be returned. include_loopback : False Include loopback ::1 IPv6 address. cidr Describes subnet using CIDR notation and only IPv6 addresses that belong to this subnet will be returned. .. versionchanged:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' network.ip_addrs6 salt '*' network.ip_addrs6 cidr=2000::/3 ''' addrs = salt.utils.network.ip_addrs6(interface=interface, include_loopback=include_loopback) if cidr: return [i for i in addrs if salt.utils.network.in_subnet(cidr, [i])] else: return addrs ipaddrs6 = salt.utils.functools.alias_function(ip_addrs6, 'ipaddrs6') def connect(host, port=None, **kwargs): ''' Test connectivity to a host using a particular port from the minion. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' network.connect archlinux.org 80 salt '*' network.connect archlinux.org 80 timeout=3 salt '*' network.connect archlinux.org 80 timeout=3 family=ipv4 salt '*' network.connect google-public-dns-a.google.com port=53 proto=udp timeout=3 ''' ret = {'result': None, 'comment': ''} if not host: ret['result'] = False ret['comment'] = 'Required argument, host, is missing.' return ret if not port: ret['result'] = False ret['comment'] = 'Required argument, port, is missing.' return ret proto = kwargs.get('proto', 'tcp') timeout = kwargs.get('timeout', 5) family = kwargs.get('family', None) if salt.utils.validate.net.ipv4_addr(host) or salt.utils.validate.net.ipv6_addr(host): address = host else: address = '{0}'.format(salt.utils.network.sanitize_host(host)) try: if proto == 'udp': __proto = socket.SOL_UDP else: __proto = socket.SOL_TCP proto = 'tcp' if family: if family == 'ipv4': __family = socket.AF_INET elif family == 'ipv6': __family = socket.AF_INET6 else: __family = 0 else: __family = 0 (family, socktype, _proto, garbage, _address) = socket.getaddrinfo(address, port, __family, 0, __proto)[0] skt = socket.socket(family, socktype, _proto) skt.settimeout(timeout) if proto == 'udp': # Generate a random string of a # decent size to test UDP connection md5h = hashlib.md5() md5h.update(datetime.datetime.now().strftime('%s')) msg = md5h.hexdigest() skt.sendto(msg, _address) recv, svr = skt.recvfrom(255) skt.close() else: skt.connect(_address) skt.shutdown(2) except Exception as exc: ret['result'] = False ret['comment'] = 'Unable to connect to {0} ({1}) on {2} port {3}'\ .format(host, _address[0], proto, port) return ret ret['result'] = True ret['comment'] = 'Successfully connected to {0} ({1}) on {2} port {3}'\ .format(host, _address[0], proto, port) return ret def is_private(ip_addr): ''' Check if the given IP address is a private address .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' network.is_private 10.0.0.3 ''' return ipaddress.ip_address(ip_addr).is_private
saltstack/salt
salt/modules/win_network.py
traceroute
python
def traceroute(host): ''' Performs a traceroute to a 3rd party host CLI Example: .. code-block:: bash salt '*' network.traceroute archlinux.org ''' ret = [] cmd = ['tracert', salt.utils.network.sanitize_host(host)] lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines() for line in lines: if ' ' not in line: continue if line.startswith('Trac'): continue if line.startswith('over'): continue comps = line.split() complength = len(comps) # This method still needs to better catch rows of other lengths # For example if some of the ms returns are '*' if complength == 9: result = { 'count': comps[0], 'hostname': comps[7], 'ip': comps[8], 'ms1': comps[1], 'ms2': comps[3], 'ms3': comps[5]} ret.append(result) elif complength == 8: result = { 'count': comps[0], 'hostname': None, 'ip': comps[7], 'ms1': comps[1], 'ms2': comps[3], 'ms3': comps[5]} ret.append(result) else: result = { 'count': comps[0], 'hostname': None, 'ip': None, 'ms1': None, 'ms2': None, 'ms3': None} ret.append(result) return ret
Performs a traceroute to a 3rd party host CLI Example: .. code-block:: bash salt '*' network.traceroute archlinux.org
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_network.py#L142-L193
[ "def sanitize_host(host):\n '''\n Sanitize host string.\n https://tools.ietf.org/html/rfc1123#section-2.1\n '''\n RFC952_characters = ascii_letters + digits + \".-\"\n return \"\".join([c for c in host[0:255] if c in RFC952_characters])\n" ]
# -*- coding: utf-8 -*- ''' Module for gathering and managing network information ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import re import hashlib import datetime import socket # Import Salt libs import salt.utils.network import salt.utils.platform import salt.utils.validate.net from salt.modules.network import (wol, get_hostname, interface, interface_ip, subnets6, ip_in_subnet, convert_cidr, calc_net, get_fqdn, ifacestartswith, iphexval) from salt.utils.functools import namespaced_function as _namespaced_function try: import salt.utils.winapi HAS_DEPENDENCIES = True except ImportError: HAS_DEPENDENCIES = False # Import 3rd party libraries import salt.ext.six as six # pylint: disable=W0611 try: import wmi # pylint: disable=W0611 except ImportError: HAS_DEPENDENCIES = False from salt._compat import ipaddress # Define the module's virtual name __virtualname__ = 'network' def __virtual__(): ''' Only works on Windows systems ''' if not salt.utils.platform.is_windows(): return False, "Module win_network: Only available on Windows" if not HAS_DEPENDENCIES: return False, "Module win_network: Missing dependencies" global wol, get_hostname, interface, interface_ip, subnets6, ip_in_subnet global convert_cidr, calc_net, get_fqdn, ifacestartswith, iphexval wol = _namespaced_function(wol, globals()) get_hostname = _namespaced_function(get_hostname, globals()) interface = _namespaced_function(interface, globals()) interface_ip = _namespaced_function(interface_ip, globals()) subnets6 = _namespaced_function(subnets6, globals()) ip_in_subnet = _namespaced_function(ip_in_subnet, globals()) convert_cidr = _namespaced_function(convert_cidr, globals()) calc_net = _namespaced_function(calc_net, globals()) get_fqdn = _namespaced_function(get_fqdn, globals()) ifacestartswith = _namespaced_function(ifacestartswith, globals()) iphexval = _namespaced_function(iphexval, globals()) return __virtualname__ def ping(host, timeout=False, return_boolean=False): ''' Performs a ping to a host CLI Example: .. code-block:: bash salt '*' network.ping archlinux.org .. versionadded:: 2016.11.0 Return a True or False instead of ping output. .. code-block:: bash salt '*' network.ping archlinux.org return_boolean=True Set the time to wait for a response in seconds. .. code-block:: bash salt '*' network.ping archlinux.org timeout=3 ''' if timeout: # Windows ping differs by having timeout be for individual echo requests.' # Divide timeout by tries to mimic BSD behaviour. timeout = int(timeout) * 1000 // 4 cmd = ['ping', '-n', '4', '-w', six.text_type(timeout), salt.utils.network.sanitize_host(host)] else: cmd = ['ping', '-n', '4', salt.utils.network.sanitize_host(host)] if return_boolean: ret = __salt__['cmd.run_all'](cmd, python_shell=False) if ret['retcode'] != 0: return False else: return True else: return __salt__['cmd.run'](cmd, python_shell=False) def netstat(): ''' Return information on open ports and states CLI Example: .. code-block:: bash salt '*' network.netstat ''' ret = [] cmd = ['netstat', '-nao'] lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines() for line in lines: comps = line.split() if line.startswith(' TCP'): ret.append({ 'local-address': comps[1], 'proto': comps[0], 'remote-address': comps[2], 'state': comps[3], 'program': comps[4]}) if line.startswith(' UDP'): ret.append({ 'local-address': comps[1], 'proto': comps[0], 'remote-address': comps[2], 'state': None, 'program': comps[3]}) return ret def nslookup(host): ''' Query DNS for information about a domain or ip address CLI Example: .. code-block:: bash salt '*' network.nslookup archlinux.org ''' ret = [] addresses = [] cmd = ['nslookup', salt.utils.network.sanitize_host(host)] lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines() for line in lines: if addresses: # We're in the last block listing addresses addresses.append(line.strip()) continue if line.startswith('Non-authoritative'): continue if 'Addresses' in line: comps = line.split(":", 1) addresses.append(comps[1].strip()) continue if ":" in line: comps = line.split(":", 1) ret.append({comps[0].strip(): comps[1].strip()}) if addresses: ret.append({'Addresses': addresses}) return ret def get_route(ip): ''' Return routing information for given destination ip .. versionadded:: 2016.11.5 CLI Example:: salt '*' network.get_route 10.10.10.10 ''' cmd = 'Find-NetRoute -RemoteIPAddress {0}'.format(ip) out = __salt__['cmd.run'](cmd, shell='powershell', python_shell=True) regexp = re.compile( r"^IPAddress\s+:\s(?P<source>[\d\.:]+)?.*" r"^InterfaceAlias\s+:\s(?P<interface>[\w\.\:\-\ ]+)?.*" r"^NextHop\s+:\s(?P<gateway>[\d\.:]+)", flags=re.MULTILINE | re.DOTALL ) m = regexp.search(out) ret = { 'destination': ip, 'gateway': m.group('gateway'), 'interface': m.group('interface'), 'source': m.group('source') } return ret def dig(host): ''' Performs a DNS lookup with dig Note: dig must be installed on the Windows minion CLI Example: .. code-block:: bash salt '*' network.dig archlinux.org ''' cmd = ['dig', salt.utils.network.sanitize_host(host)] return __salt__['cmd.run'](cmd, python_shell=False) def interfaces_names(): ''' Return a list of all the interfaces names CLI Example: .. code-block:: bash salt '*' network.interfaces_names ''' ret = [] with salt.utils.winapi.Com(): c = wmi.WMI() for iface in c.Win32_NetworkAdapter(NetEnabled=True): ret.append(iface.NetConnectionID) return ret def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion CLI Example: .. code-block:: bash salt '*' network.interfaces ''' return salt.utils.network.win_interfaces() def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface CLI Example: .. code-block:: bash salt '*' network.hw_addr 'Wireless Connection #1' ''' return salt.utils.network.hw_addr(iface) # Alias hwaddr to preserve backward compat hwaddr = salt.utils.functools.alias_function(hw_addr, 'hwaddr') def subnets(): ''' Returns a list of subnets to which the host belongs CLI Example: .. code-block:: bash salt '*' network.subnets ''' return salt.utils.network.subnets() def in_subnet(cidr): ''' Returns True if host is within specified subnet, otherwise False CLI Example: .. code-block:: bash salt '*' network.in_subnet 10.0.0.0/16 ''' return salt.utils.network.in_subnet(cidr) def ip_addrs(interface=None, include_loopback=False, cidr=None, type=None): ''' Returns a list of IPv4 addresses assigned to the host. interface Only IP addresses from that interface will be returned. include_loopback : False Include loopback 127.0.0.1 IPv4 address. cidr Describes subnet using CIDR notation and only IPv4 addresses that belong to this subnet will be returned. .. versionchanged:: 2019.2.0 type If option set to 'public' then only public addresses will be returned. Ditto for 'private'. .. versionchanged:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' network.ip_addrs salt '*' network.ip_addrs cidr=10.0.0.0/8 salt '*' network.ip_addrs cidr=192.168.0.0/16 type=private ''' addrs = salt.utils.network.ip_addrs(interface=interface, include_loopback=include_loopback) if cidr: return [i for i in addrs if salt.utils.network.in_subnet(cidr, [i])] else: if type == 'public': return [i for i in addrs if not is_private(i)] elif type == 'private': return [i for i in addrs if is_private(i)] else: return addrs ipaddrs = salt.utils.functools.alias_function(ip_addrs, 'ipaddrs') def ip_addrs6(interface=None, include_loopback=False, cidr=None): ''' Returns a list of IPv6 addresses assigned to the host. interface Only IP addresses from that interface will be returned. include_loopback : False Include loopback ::1 IPv6 address. cidr Describes subnet using CIDR notation and only IPv6 addresses that belong to this subnet will be returned. .. versionchanged:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' network.ip_addrs6 salt '*' network.ip_addrs6 cidr=2000::/3 ''' addrs = salt.utils.network.ip_addrs6(interface=interface, include_loopback=include_loopback) if cidr: return [i for i in addrs if salt.utils.network.in_subnet(cidr, [i])] else: return addrs ipaddrs6 = salt.utils.functools.alias_function(ip_addrs6, 'ipaddrs6') def connect(host, port=None, **kwargs): ''' Test connectivity to a host using a particular port from the minion. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' network.connect archlinux.org 80 salt '*' network.connect archlinux.org 80 timeout=3 salt '*' network.connect archlinux.org 80 timeout=3 family=ipv4 salt '*' network.connect google-public-dns-a.google.com port=53 proto=udp timeout=3 ''' ret = {'result': None, 'comment': ''} if not host: ret['result'] = False ret['comment'] = 'Required argument, host, is missing.' return ret if not port: ret['result'] = False ret['comment'] = 'Required argument, port, is missing.' return ret proto = kwargs.get('proto', 'tcp') timeout = kwargs.get('timeout', 5) family = kwargs.get('family', None) if salt.utils.validate.net.ipv4_addr(host) or salt.utils.validate.net.ipv6_addr(host): address = host else: address = '{0}'.format(salt.utils.network.sanitize_host(host)) try: if proto == 'udp': __proto = socket.SOL_UDP else: __proto = socket.SOL_TCP proto = 'tcp' if family: if family == 'ipv4': __family = socket.AF_INET elif family == 'ipv6': __family = socket.AF_INET6 else: __family = 0 else: __family = 0 (family, socktype, _proto, garbage, _address) = socket.getaddrinfo(address, port, __family, 0, __proto)[0] skt = socket.socket(family, socktype, _proto) skt.settimeout(timeout) if proto == 'udp': # Generate a random string of a # decent size to test UDP connection md5h = hashlib.md5() md5h.update(datetime.datetime.now().strftime('%s')) msg = md5h.hexdigest() skt.sendto(msg, _address) recv, svr = skt.recvfrom(255) skt.close() else: skt.connect(_address) skt.shutdown(2) except Exception as exc: ret['result'] = False ret['comment'] = 'Unable to connect to {0} ({1}) on {2} port {3}'\ .format(host, _address[0], proto, port) return ret ret['result'] = True ret['comment'] = 'Successfully connected to {0} ({1}) on {2} port {3}'\ .format(host, _address[0], proto, port) return ret def is_private(ip_addr): ''' Check if the given IP address is a private address .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' network.is_private 10.0.0.3 ''' return ipaddress.ip_address(ip_addr).is_private
saltstack/salt
salt/modules/win_network.py
nslookup
python
def nslookup(host): ''' Query DNS for information about a domain or ip address CLI Example: .. code-block:: bash salt '*' network.nslookup archlinux.org ''' ret = [] addresses = [] cmd = ['nslookup', salt.utils.network.sanitize_host(host)] lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines() for line in lines: if addresses: # We're in the last block listing addresses addresses.append(line.strip()) continue if line.startswith('Non-authoritative'): continue if 'Addresses' in line: comps = line.split(":", 1) addresses.append(comps[1].strip()) continue if ":" in line: comps = line.split(":", 1) ret.append({comps[0].strip(): comps[1].strip()}) if addresses: ret.append({'Addresses': addresses}) return ret
Query DNS for information about a domain or ip address CLI Example: .. code-block:: bash salt '*' network.nslookup archlinux.org
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_network.py#L196-L226
[ "def sanitize_host(host):\n '''\n Sanitize host string.\n https://tools.ietf.org/html/rfc1123#section-2.1\n '''\n RFC952_characters = ascii_letters + digits + \".-\"\n return \"\".join([c for c in host[0:255] if c in RFC952_characters])\n" ]
# -*- coding: utf-8 -*- ''' Module for gathering and managing network information ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import re import hashlib import datetime import socket # Import Salt libs import salt.utils.network import salt.utils.platform import salt.utils.validate.net from salt.modules.network import (wol, get_hostname, interface, interface_ip, subnets6, ip_in_subnet, convert_cidr, calc_net, get_fqdn, ifacestartswith, iphexval) from salt.utils.functools import namespaced_function as _namespaced_function try: import salt.utils.winapi HAS_DEPENDENCIES = True except ImportError: HAS_DEPENDENCIES = False # Import 3rd party libraries import salt.ext.six as six # pylint: disable=W0611 try: import wmi # pylint: disable=W0611 except ImportError: HAS_DEPENDENCIES = False from salt._compat import ipaddress # Define the module's virtual name __virtualname__ = 'network' def __virtual__(): ''' Only works on Windows systems ''' if not salt.utils.platform.is_windows(): return False, "Module win_network: Only available on Windows" if not HAS_DEPENDENCIES: return False, "Module win_network: Missing dependencies" global wol, get_hostname, interface, interface_ip, subnets6, ip_in_subnet global convert_cidr, calc_net, get_fqdn, ifacestartswith, iphexval wol = _namespaced_function(wol, globals()) get_hostname = _namespaced_function(get_hostname, globals()) interface = _namespaced_function(interface, globals()) interface_ip = _namespaced_function(interface_ip, globals()) subnets6 = _namespaced_function(subnets6, globals()) ip_in_subnet = _namespaced_function(ip_in_subnet, globals()) convert_cidr = _namespaced_function(convert_cidr, globals()) calc_net = _namespaced_function(calc_net, globals()) get_fqdn = _namespaced_function(get_fqdn, globals()) ifacestartswith = _namespaced_function(ifacestartswith, globals()) iphexval = _namespaced_function(iphexval, globals()) return __virtualname__ def ping(host, timeout=False, return_boolean=False): ''' Performs a ping to a host CLI Example: .. code-block:: bash salt '*' network.ping archlinux.org .. versionadded:: 2016.11.0 Return a True or False instead of ping output. .. code-block:: bash salt '*' network.ping archlinux.org return_boolean=True Set the time to wait for a response in seconds. .. code-block:: bash salt '*' network.ping archlinux.org timeout=3 ''' if timeout: # Windows ping differs by having timeout be for individual echo requests.' # Divide timeout by tries to mimic BSD behaviour. timeout = int(timeout) * 1000 // 4 cmd = ['ping', '-n', '4', '-w', six.text_type(timeout), salt.utils.network.sanitize_host(host)] else: cmd = ['ping', '-n', '4', salt.utils.network.sanitize_host(host)] if return_boolean: ret = __salt__['cmd.run_all'](cmd, python_shell=False) if ret['retcode'] != 0: return False else: return True else: return __salt__['cmd.run'](cmd, python_shell=False) def netstat(): ''' Return information on open ports and states CLI Example: .. code-block:: bash salt '*' network.netstat ''' ret = [] cmd = ['netstat', '-nao'] lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines() for line in lines: comps = line.split() if line.startswith(' TCP'): ret.append({ 'local-address': comps[1], 'proto': comps[0], 'remote-address': comps[2], 'state': comps[3], 'program': comps[4]}) if line.startswith(' UDP'): ret.append({ 'local-address': comps[1], 'proto': comps[0], 'remote-address': comps[2], 'state': None, 'program': comps[3]}) return ret def traceroute(host): ''' Performs a traceroute to a 3rd party host CLI Example: .. code-block:: bash salt '*' network.traceroute archlinux.org ''' ret = [] cmd = ['tracert', salt.utils.network.sanitize_host(host)] lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines() for line in lines: if ' ' not in line: continue if line.startswith('Trac'): continue if line.startswith('over'): continue comps = line.split() complength = len(comps) # This method still needs to better catch rows of other lengths # For example if some of the ms returns are '*' if complength == 9: result = { 'count': comps[0], 'hostname': comps[7], 'ip': comps[8], 'ms1': comps[1], 'ms2': comps[3], 'ms3': comps[5]} ret.append(result) elif complength == 8: result = { 'count': comps[0], 'hostname': None, 'ip': comps[7], 'ms1': comps[1], 'ms2': comps[3], 'ms3': comps[5]} ret.append(result) else: result = { 'count': comps[0], 'hostname': None, 'ip': None, 'ms1': None, 'ms2': None, 'ms3': None} ret.append(result) return ret def get_route(ip): ''' Return routing information for given destination ip .. versionadded:: 2016.11.5 CLI Example:: salt '*' network.get_route 10.10.10.10 ''' cmd = 'Find-NetRoute -RemoteIPAddress {0}'.format(ip) out = __salt__['cmd.run'](cmd, shell='powershell', python_shell=True) regexp = re.compile( r"^IPAddress\s+:\s(?P<source>[\d\.:]+)?.*" r"^InterfaceAlias\s+:\s(?P<interface>[\w\.\:\-\ ]+)?.*" r"^NextHop\s+:\s(?P<gateway>[\d\.:]+)", flags=re.MULTILINE | re.DOTALL ) m = regexp.search(out) ret = { 'destination': ip, 'gateway': m.group('gateway'), 'interface': m.group('interface'), 'source': m.group('source') } return ret def dig(host): ''' Performs a DNS lookup with dig Note: dig must be installed on the Windows minion CLI Example: .. code-block:: bash salt '*' network.dig archlinux.org ''' cmd = ['dig', salt.utils.network.sanitize_host(host)] return __salt__['cmd.run'](cmd, python_shell=False) def interfaces_names(): ''' Return a list of all the interfaces names CLI Example: .. code-block:: bash salt '*' network.interfaces_names ''' ret = [] with salt.utils.winapi.Com(): c = wmi.WMI() for iface in c.Win32_NetworkAdapter(NetEnabled=True): ret.append(iface.NetConnectionID) return ret def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion CLI Example: .. code-block:: bash salt '*' network.interfaces ''' return salt.utils.network.win_interfaces() def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface CLI Example: .. code-block:: bash salt '*' network.hw_addr 'Wireless Connection #1' ''' return salt.utils.network.hw_addr(iface) # Alias hwaddr to preserve backward compat hwaddr = salt.utils.functools.alias_function(hw_addr, 'hwaddr') def subnets(): ''' Returns a list of subnets to which the host belongs CLI Example: .. code-block:: bash salt '*' network.subnets ''' return salt.utils.network.subnets() def in_subnet(cidr): ''' Returns True if host is within specified subnet, otherwise False CLI Example: .. code-block:: bash salt '*' network.in_subnet 10.0.0.0/16 ''' return salt.utils.network.in_subnet(cidr) def ip_addrs(interface=None, include_loopback=False, cidr=None, type=None): ''' Returns a list of IPv4 addresses assigned to the host. interface Only IP addresses from that interface will be returned. include_loopback : False Include loopback 127.0.0.1 IPv4 address. cidr Describes subnet using CIDR notation and only IPv4 addresses that belong to this subnet will be returned. .. versionchanged:: 2019.2.0 type If option set to 'public' then only public addresses will be returned. Ditto for 'private'. .. versionchanged:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' network.ip_addrs salt '*' network.ip_addrs cidr=10.0.0.0/8 salt '*' network.ip_addrs cidr=192.168.0.0/16 type=private ''' addrs = salt.utils.network.ip_addrs(interface=interface, include_loopback=include_loopback) if cidr: return [i for i in addrs if salt.utils.network.in_subnet(cidr, [i])] else: if type == 'public': return [i for i in addrs if not is_private(i)] elif type == 'private': return [i for i in addrs if is_private(i)] else: return addrs ipaddrs = salt.utils.functools.alias_function(ip_addrs, 'ipaddrs') def ip_addrs6(interface=None, include_loopback=False, cidr=None): ''' Returns a list of IPv6 addresses assigned to the host. interface Only IP addresses from that interface will be returned. include_loopback : False Include loopback ::1 IPv6 address. cidr Describes subnet using CIDR notation and only IPv6 addresses that belong to this subnet will be returned. .. versionchanged:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' network.ip_addrs6 salt '*' network.ip_addrs6 cidr=2000::/3 ''' addrs = salt.utils.network.ip_addrs6(interface=interface, include_loopback=include_loopback) if cidr: return [i for i in addrs if salt.utils.network.in_subnet(cidr, [i])] else: return addrs ipaddrs6 = salt.utils.functools.alias_function(ip_addrs6, 'ipaddrs6') def connect(host, port=None, **kwargs): ''' Test connectivity to a host using a particular port from the minion. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' network.connect archlinux.org 80 salt '*' network.connect archlinux.org 80 timeout=3 salt '*' network.connect archlinux.org 80 timeout=3 family=ipv4 salt '*' network.connect google-public-dns-a.google.com port=53 proto=udp timeout=3 ''' ret = {'result': None, 'comment': ''} if not host: ret['result'] = False ret['comment'] = 'Required argument, host, is missing.' return ret if not port: ret['result'] = False ret['comment'] = 'Required argument, port, is missing.' return ret proto = kwargs.get('proto', 'tcp') timeout = kwargs.get('timeout', 5) family = kwargs.get('family', None) if salt.utils.validate.net.ipv4_addr(host) or salt.utils.validate.net.ipv6_addr(host): address = host else: address = '{0}'.format(salt.utils.network.sanitize_host(host)) try: if proto == 'udp': __proto = socket.SOL_UDP else: __proto = socket.SOL_TCP proto = 'tcp' if family: if family == 'ipv4': __family = socket.AF_INET elif family == 'ipv6': __family = socket.AF_INET6 else: __family = 0 else: __family = 0 (family, socktype, _proto, garbage, _address) = socket.getaddrinfo(address, port, __family, 0, __proto)[0] skt = socket.socket(family, socktype, _proto) skt.settimeout(timeout) if proto == 'udp': # Generate a random string of a # decent size to test UDP connection md5h = hashlib.md5() md5h.update(datetime.datetime.now().strftime('%s')) msg = md5h.hexdigest() skt.sendto(msg, _address) recv, svr = skt.recvfrom(255) skt.close() else: skt.connect(_address) skt.shutdown(2) except Exception as exc: ret['result'] = False ret['comment'] = 'Unable to connect to {0} ({1}) on {2} port {3}'\ .format(host, _address[0], proto, port) return ret ret['result'] = True ret['comment'] = 'Successfully connected to {0} ({1}) on {2} port {3}'\ .format(host, _address[0], proto, port) return ret def is_private(ip_addr): ''' Check if the given IP address is a private address .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' network.is_private 10.0.0.3 ''' return ipaddress.ip_address(ip_addr).is_private
saltstack/salt
salt/modules/win_network.py
get_route
python
def get_route(ip): ''' Return routing information for given destination ip .. versionadded:: 2016.11.5 CLI Example:: salt '*' network.get_route 10.10.10.10 ''' cmd = 'Find-NetRoute -RemoteIPAddress {0}'.format(ip) out = __salt__['cmd.run'](cmd, shell='powershell', python_shell=True) regexp = re.compile( r"^IPAddress\s+:\s(?P<source>[\d\.:]+)?.*" r"^InterfaceAlias\s+:\s(?P<interface>[\w\.\:\-\ ]+)?.*" r"^NextHop\s+:\s(?P<gateway>[\d\.:]+)", flags=re.MULTILINE | re.DOTALL ) m = regexp.search(out) ret = { 'destination': ip, 'gateway': m.group('gateway'), 'interface': m.group('interface'), 'source': m.group('source') } return ret
Return routing information for given destination ip .. versionadded:: 2016.11.5 CLI Example:: salt '*' network.get_route 10.10.10.10
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_network.py#L229-L255
null
# -*- coding: utf-8 -*- ''' Module for gathering and managing network information ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import re import hashlib import datetime import socket # Import Salt libs import salt.utils.network import salt.utils.platform import salt.utils.validate.net from salt.modules.network import (wol, get_hostname, interface, interface_ip, subnets6, ip_in_subnet, convert_cidr, calc_net, get_fqdn, ifacestartswith, iphexval) from salt.utils.functools import namespaced_function as _namespaced_function try: import salt.utils.winapi HAS_DEPENDENCIES = True except ImportError: HAS_DEPENDENCIES = False # Import 3rd party libraries import salt.ext.six as six # pylint: disable=W0611 try: import wmi # pylint: disable=W0611 except ImportError: HAS_DEPENDENCIES = False from salt._compat import ipaddress # Define the module's virtual name __virtualname__ = 'network' def __virtual__(): ''' Only works on Windows systems ''' if not salt.utils.platform.is_windows(): return False, "Module win_network: Only available on Windows" if not HAS_DEPENDENCIES: return False, "Module win_network: Missing dependencies" global wol, get_hostname, interface, interface_ip, subnets6, ip_in_subnet global convert_cidr, calc_net, get_fqdn, ifacestartswith, iphexval wol = _namespaced_function(wol, globals()) get_hostname = _namespaced_function(get_hostname, globals()) interface = _namespaced_function(interface, globals()) interface_ip = _namespaced_function(interface_ip, globals()) subnets6 = _namespaced_function(subnets6, globals()) ip_in_subnet = _namespaced_function(ip_in_subnet, globals()) convert_cidr = _namespaced_function(convert_cidr, globals()) calc_net = _namespaced_function(calc_net, globals()) get_fqdn = _namespaced_function(get_fqdn, globals()) ifacestartswith = _namespaced_function(ifacestartswith, globals()) iphexval = _namespaced_function(iphexval, globals()) return __virtualname__ def ping(host, timeout=False, return_boolean=False): ''' Performs a ping to a host CLI Example: .. code-block:: bash salt '*' network.ping archlinux.org .. versionadded:: 2016.11.0 Return a True or False instead of ping output. .. code-block:: bash salt '*' network.ping archlinux.org return_boolean=True Set the time to wait for a response in seconds. .. code-block:: bash salt '*' network.ping archlinux.org timeout=3 ''' if timeout: # Windows ping differs by having timeout be for individual echo requests.' # Divide timeout by tries to mimic BSD behaviour. timeout = int(timeout) * 1000 // 4 cmd = ['ping', '-n', '4', '-w', six.text_type(timeout), salt.utils.network.sanitize_host(host)] else: cmd = ['ping', '-n', '4', salt.utils.network.sanitize_host(host)] if return_boolean: ret = __salt__['cmd.run_all'](cmd, python_shell=False) if ret['retcode'] != 0: return False else: return True else: return __salt__['cmd.run'](cmd, python_shell=False) def netstat(): ''' Return information on open ports and states CLI Example: .. code-block:: bash salt '*' network.netstat ''' ret = [] cmd = ['netstat', '-nao'] lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines() for line in lines: comps = line.split() if line.startswith(' TCP'): ret.append({ 'local-address': comps[1], 'proto': comps[0], 'remote-address': comps[2], 'state': comps[3], 'program': comps[4]}) if line.startswith(' UDP'): ret.append({ 'local-address': comps[1], 'proto': comps[0], 'remote-address': comps[2], 'state': None, 'program': comps[3]}) return ret def traceroute(host): ''' Performs a traceroute to a 3rd party host CLI Example: .. code-block:: bash salt '*' network.traceroute archlinux.org ''' ret = [] cmd = ['tracert', salt.utils.network.sanitize_host(host)] lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines() for line in lines: if ' ' not in line: continue if line.startswith('Trac'): continue if line.startswith('over'): continue comps = line.split() complength = len(comps) # This method still needs to better catch rows of other lengths # For example if some of the ms returns are '*' if complength == 9: result = { 'count': comps[0], 'hostname': comps[7], 'ip': comps[8], 'ms1': comps[1], 'ms2': comps[3], 'ms3': comps[5]} ret.append(result) elif complength == 8: result = { 'count': comps[0], 'hostname': None, 'ip': comps[7], 'ms1': comps[1], 'ms2': comps[3], 'ms3': comps[5]} ret.append(result) else: result = { 'count': comps[0], 'hostname': None, 'ip': None, 'ms1': None, 'ms2': None, 'ms3': None} ret.append(result) return ret def nslookup(host): ''' Query DNS for information about a domain or ip address CLI Example: .. code-block:: bash salt '*' network.nslookup archlinux.org ''' ret = [] addresses = [] cmd = ['nslookup', salt.utils.network.sanitize_host(host)] lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines() for line in lines: if addresses: # We're in the last block listing addresses addresses.append(line.strip()) continue if line.startswith('Non-authoritative'): continue if 'Addresses' in line: comps = line.split(":", 1) addresses.append(comps[1].strip()) continue if ":" in line: comps = line.split(":", 1) ret.append({comps[0].strip(): comps[1].strip()}) if addresses: ret.append({'Addresses': addresses}) return ret def dig(host): ''' Performs a DNS lookup with dig Note: dig must be installed on the Windows minion CLI Example: .. code-block:: bash salt '*' network.dig archlinux.org ''' cmd = ['dig', salt.utils.network.sanitize_host(host)] return __salt__['cmd.run'](cmd, python_shell=False) def interfaces_names(): ''' Return a list of all the interfaces names CLI Example: .. code-block:: bash salt '*' network.interfaces_names ''' ret = [] with salt.utils.winapi.Com(): c = wmi.WMI() for iface in c.Win32_NetworkAdapter(NetEnabled=True): ret.append(iface.NetConnectionID) return ret def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion CLI Example: .. code-block:: bash salt '*' network.interfaces ''' return salt.utils.network.win_interfaces() def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface CLI Example: .. code-block:: bash salt '*' network.hw_addr 'Wireless Connection #1' ''' return salt.utils.network.hw_addr(iface) # Alias hwaddr to preserve backward compat hwaddr = salt.utils.functools.alias_function(hw_addr, 'hwaddr') def subnets(): ''' Returns a list of subnets to which the host belongs CLI Example: .. code-block:: bash salt '*' network.subnets ''' return salt.utils.network.subnets() def in_subnet(cidr): ''' Returns True if host is within specified subnet, otherwise False CLI Example: .. code-block:: bash salt '*' network.in_subnet 10.0.0.0/16 ''' return salt.utils.network.in_subnet(cidr) def ip_addrs(interface=None, include_loopback=False, cidr=None, type=None): ''' Returns a list of IPv4 addresses assigned to the host. interface Only IP addresses from that interface will be returned. include_loopback : False Include loopback 127.0.0.1 IPv4 address. cidr Describes subnet using CIDR notation and only IPv4 addresses that belong to this subnet will be returned. .. versionchanged:: 2019.2.0 type If option set to 'public' then only public addresses will be returned. Ditto for 'private'. .. versionchanged:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' network.ip_addrs salt '*' network.ip_addrs cidr=10.0.0.0/8 salt '*' network.ip_addrs cidr=192.168.0.0/16 type=private ''' addrs = salt.utils.network.ip_addrs(interface=interface, include_loopback=include_loopback) if cidr: return [i for i in addrs if salt.utils.network.in_subnet(cidr, [i])] else: if type == 'public': return [i for i in addrs if not is_private(i)] elif type == 'private': return [i for i in addrs if is_private(i)] else: return addrs ipaddrs = salt.utils.functools.alias_function(ip_addrs, 'ipaddrs') def ip_addrs6(interface=None, include_loopback=False, cidr=None): ''' Returns a list of IPv6 addresses assigned to the host. interface Only IP addresses from that interface will be returned. include_loopback : False Include loopback ::1 IPv6 address. cidr Describes subnet using CIDR notation and only IPv6 addresses that belong to this subnet will be returned. .. versionchanged:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' network.ip_addrs6 salt '*' network.ip_addrs6 cidr=2000::/3 ''' addrs = salt.utils.network.ip_addrs6(interface=interface, include_loopback=include_loopback) if cidr: return [i for i in addrs if salt.utils.network.in_subnet(cidr, [i])] else: return addrs ipaddrs6 = salt.utils.functools.alias_function(ip_addrs6, 'ipaddrs6') def connect(host, port=None, **kwargs): ''' Test connectivity to a host using a particular port from the minion. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' network.connect archlinux.org 80 salt '*' network.connect archlinux.org 80 timeout=3 salt '*' network.connect archlinux.org 80 timeout=3 family=ipv4 salt '*' network.connect google-public-dns-a.google.com port=53 proto=udp timeout=3 ''' ret = {'result': None, 'comment': ''} if not host: ret['result'] = False ret['comment'] = 'Required argument, host, is missing.' return ret if not port: ret['result'] = False ret['comment'] = 'Required argument, port, is missing.' return ret proto = kwargs.get('proto', 'tcp') timeout = kwargs.get('timeout', 5) family = kwargs.get('family', None) if salt.utils.validate.net.ipv4_addr(host) or salt.utils.validate.net.ipv6_addr(host): address = host else: address = '{0}'.format(salt.utils.network.sanitize_host(host)) try: if proto == 'udp': __proto = socket.SOL_UDP else: __proto = socket.SOL_TCP proto = 'tcp' if family: if family == 'ipv4': __family = socket.AF_INET elif family == 'ipv6': __family = socket.AF_INET6 else: __family = 0 else: __family = 0 (family, socktype, _proto, garbage, _address) = socket.getaddrinfo(address, port, __family, 0, __proto)[0] skt = socket.socket(family, socktype, _proto) skt.settimeout(timeout) if proto == 'udp': # Generate a random string of a # decent size to test UDP connection md5h = hashlib.md5() md5h.update(datetime.datetime.now().strftime('%s')) msg = md5h.hexdigest() skt.sendto(msg, _address) recv, svr = skt.recvfrom(255) skt.close() else: skt.connect(_address) skt.shutdown(2) except Exception as exc: ret['result'] = False ret['comment'] = 'Unable to connect to {0} ({1}) on {2} port {3}'\ .format(host, _address[0], proto, port) return ret ret['result'] = True ret['comment'] = 'Successfully connected to {0} ({1}) on {2} port {3}'\ .format(host, _address[0], proto, port) return ret def is_private(ip_addr): ''' Check if the given IP address is a private address .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' network.is_private 10.0.0.3 ''' return ipaddress.ip_address(ip_addr).is_private
saltstack/salt
salt/modules/win_network.py
dig
python
def dig(host): ''' Performs a DNS lookup with dig Note: dig must be installed on the Windows minion CLI Example: .. code-block:: bash salt '*' network.dig archlinux.org ''' cmd = ['dig', salt.utils.network.sanitize_host(host)] return __salt__['cmd.run'](cmd, python_shell=False)
Performs a DNS lookup with dig Note: dig must be installed on the Windows minion CLI Example: .. code-block:: bash salt '*' network.dig archlinux.org
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_network.py#L258-L271
[ "def sanitize_host(host):\n '''\n Sanitize host string.\n https://tools.ietf.org/html/rfc1123#section-2.1\n '''\n RFC952_characters = ascii_letters + digits + \".-\"\n return \"\".join([c for c in host[0:255] if c in RFC952_characters])\n" ]
# -*- coding: utf-8 -*- ''' Module for gathering and managing network information ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import re import hashlib import datetime import socket # Import Salt libs import salt.utils.network import salt.utils.platform import salt.utils.validate.net from salt.modules.network import (wol, get_hostname, interface, interface_ip, subnets6, ip_in_subnet, convert_cidr, calc_net, get_fqdn, ifacestartswith, iphexval) from salt.utils.functools import namespaced_function as _namespaced_function try: import salt.utils.winapi HAS_DEPENDENCIES = True except ImportError: HAS_DEPENDENCIES = False # Import 3rd party libraries import salt.ext.six as six # pylint: disable=W0611 try: import wmi # pylint: disable=W0611 except ImportError: HAS_DEPENDENCIES = False from salt._compat import ipaddress # Define the module's virtual name __virtualname__ = 'network' def __virtual__(): ''' Only works on Windows systems ''' if not salt.utils.platform.is_windows(): return False, "Module win_network: Only available on Windows" if not HAS_DEPENDENCIES: return False, "Module win_network: Missing dependencies" global wol, get_hostname, interface, interface_ip, subnets6, ip_in_subnet global convert_cidr, calc_net, get_fqdn, ifacestartswith, iphexval wol = _namespaced_function(wol, globals()) get_hostname = _namespaced_function(get_hostname, globals()) interface = _namespaced_function(interface, globals()) interface_ip = _namespaced_function(interface_ip, globals()) subnets6 = _namespaced_function(subnets6, globals()) ip_in_subnet = _namespaced_function(ip_in_subnet, globals()) convert_cidr = _namespaced_function(convert_cidr, globals()) calc_net = _namespaced_function(calc_net, globals()) get_fqdn = _namespaced_function(get_fqdn, globals()) ifacestartswith = _namespaced_function(ifacestartswith, globals()) iphexval = _namespaced_function(iphexval, globals()) return __virtualname__ def ping(host, timeout=False, return_boolean=False): ''' Performs a ping to a host CLI Example: .. code-block:: bash salt '*' network.ping archlinux.org .. versionadded:: 2016.11.0 Return a True or False instead of ping output. .. code-block:: bash salt '*' network.ping archlinux.org return_boolean=True Set the time to wait for a response in seconds. .. code-block:: bash salt '*' network.ping archlinux.org timeout=3 ''' if timeout: # Windows ping differs by having timeout be for individual echo requests.' # Divide timeout by tries to mimic BSD behaviour. timeout = int(timeout) * 1000 // 4 cmd = ['ping', '-n', '4', '-w', six.text_type(timeout), salt.utils.network.sanitize_host(host)] else: cmd = ['ping', '-n', '4', salt.utils.network.sanitize_host(host)] if return_boolean: ret = __salt__['cmd.run_all'](cmd, python_shell=False) if ret['retcode'] != 0: return False else: return True else: return __salt__['cmd.run'](cmd, python_shell=False) def netstat(): ''' Return information on open ports and states CLI Example: .. code-block:: bash salt '*' network.netstat ''' ret = [] cmd = ['netstat', '-nao'] lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines() for line in lines: comps = line.split() if line.startswith(' TCP'): ret.append({ 'local-address': comps[1], 'proto': comps[0], 'remote-address': comps[2], 'state': comps[3], 'program': comps[4]}) if line.startswith(' UDP'): ret.append({ 'local-address': comps[1], 'proto': comps[0], 'remote-address': comps[2], 'state': None, 'program': comps[3]}) return ret def traceroute(host): ''' Performs a traceroute to a 3rd party host CLI Example: .. code-block:: bash salt '*' network.traceroute archlinux.org ''' ret = [] cmd = ['tracert', salt.utils.network.sanitize_host(host)] lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines() for line in lines: if ' ' not in line: continue if line.startswith('Trac'): continue if line.startswith('over'): continue comps = line.split() complength = len(comps) # This method still needs to better catch rows of other lengths # For example if some of the ms returns are '*' if complength == 9: result = { 'count': comps[0], 'hostname': comps[7], 'ip': comps[8], 'ms1': comps[1], 'ms2': comps[3], 'ms3': comps[5]} ret.append(result) elif complength == 8: result = { 'count': comps[0], 'hostname': None, 'ip': comps[7], 'ms1': comps[1], 'ms2': comps[3], 'ms3': comps[5]} ret.append(result) else: result = { 'count': comps[0], 'hostname': None, 'ip': None, 'ms1': None, 'ms2': None, 'ms3': None} ret.append(result) return ret def nslookup(host): ''' Query DNS for information about a domain or ip address CLI Example: .. code-block:: bash salt '*' network.nslookup archlinux.org ''' ret = [] addresses = [] cmd = ['nslookup', salt.utils.network.sanitize_host(host)] lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines() for line in lines: if addresses: # We're in the last block listing addresses addresses.append(line.strip()) continue if line.startswith('Non-authoritative'): continue if 'Addresses' in line: comps = line.split(":", 1) addresses.append(comps[1].strip()) continue if ":" in line: comps = line.split(":", 1) ret.append({comps[0].strip(): comps[1].strip()}) if addresses: ret.append({'Addresses': addresses}) return ret def get_route(ip): ''' Return routing information for given destination ip .. versionadded:: 2016.11.5 CLI Example:: salt '*' network.get_route 10.10.10.10 ''' cmd = 'Find-NetRoute -RemoteIPAddress {0}'.format(ip) out = __salt__['cmd.run'](cmd, shell='powershell', python_shell=True) regexp = re.compile( r"^IPAddress\s+:\s(?P<source>[\d\.:]+)?.*" r"^InterfaceAlias\s+:\s(?P<interface>[\w\.\:\-\ ]+)?.*" r"^NextHop\s+:\s(?P<gateway>[\d\.:]+)", flags=re.MULTILINE | re.DOTALL ) m = regexp.search(out) ret = { 'destination': ip, 'gateway': m.group('gateway'), 'interface': m.group('interface'), 'source': m.group('source') } return ret def interfaces_names(): ''' Return a list of all the interfaces names CLI Example: .. code-block:: bash salt '*' network.interfaces_names ''' ret = [] with salt.utils.winapi.Com(): c = wmi.WMI() for iface in c.Win32_NetworkAdapter(NetEnabled=True): ret.append(iface.NetConnectionID) return ret def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion CLI Example: .. code-block:: bash salt '*' network.interfaces ''' return salt.utils.network.win_interfaces() def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface CLI Example: .. code-block:: bash salt '*' network.hw_addr 'Wireless Connection #1' ''' return salt.utils.network.hw_addr(iface) # Alias hwaddr to preserve backward compat hwaddr = salt.utils.functools.alias_function(hw_addr, 'hwaddr') def subnets(): ''' Returns a list of subnets to which the host belongs CLI Example: .. code-block:: bash salt '*' network.subnets ''' return salt.utils.network.subnets() def in_subnet(cidr): ''' Returns True if host is within specified subnet, otherwise False CLI Example: .. code-block:: bash salt '*' network.in_subnet 10.0.0.0/16 ''' return salt.utils.network.in_subnet(cidr) def ip_addrs(interface=None, include_loopback=False, cidr=None, type=None): ''' Returns a list of IPv4 addresses assigned to the host. interface Only IP addresses from that interface will be returned. include_loopback : False Include loopback 127.0.0.1 IPv4 address. cidr Describes subnet using CIDR notation and only IPv4 addresses that belong to this subnet will be returned. .. versionchanged:: 2019.2.0 type If option set to 'public' then only public addresses will be returned. Ditto for 'private'. .. versionchanged:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' network.ip_addrs salt '*' network.ip_addrs cidr=10.0.0.0/8 salt '*' network.ip_addrs cidr=192.168.0.0/16 type=private ''' addrs = salt.utils.network.ip_addrs(interface=interface, include_loopback=include_loopback) if cidr: return [i for i in addrs if salt.utils.network.in_subnet(cidr, [i])] else: if type == 'public': return [i for i in addrs if not is_private(i)] elif type == 'private': return [i for i in addrs if is_private(i)] else: return addrs ipaddrs = salt.utils.functools.alias_function(ip_addrs, 'ipaddrs') def ip_addrs6(interface=None, include_loopback=False, cidr=None): ''' Returns a list of IPv6 addresses assigned to the host. interface Only IP addresses from that interface will be returned. include_loopback : False Include loopback ::1 IPv6 address. cidr Describes subnet using CIDR notation and only IPv6 addresses that belong to this subnet will be returned. .. versionchanged:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' network.ip_addrs6 salt '*' network.ip_addrs6 cidr=2000::/3 ''' addrs = salt.utils.network.ip_addrs6(interface=interface, include_loopback=include_loopback) if cidr: return [i for i in addrs if salt.utils.network.in_subnet(cidr, [i])] else: return addrs ipaddrs6 = salt.utils.functools.alias_function(ip_addrs6, 'ipaddrs6') def connect(host, port=None, **kwargs): ''' Test connectivity to a host using a particular port from the minion. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' network.connect archlinux.org 80 salt '*' network.connect archlinux.org 80 timeout=3 salt '*' network.connect archlinux.org 80 timeout=3 family=ipv4 salt '*' network.connect google-public-dns-a.google.com port=53 proto=udp timeout=3 ''' ret = {'result': None, 'comment': ''} if not host: ret['result'] = False ret['comment'] = 'Required argument, host, is missing.' return ret if not port: ret['result'] = False ret['comment'] = 'Required argument, port, is missing.' return ret proto = kwargs.get('proto', 'tcp') timeout = kwargs.get('timeout', 5) family = kwargs.get('family', None) if salt.utils.validate.net.ipv4_addr(host) or salt.utils.validate.net.ipv6_addr(host): address = host else: address = '{0}'.format(salt.utils.network.sanitize_host(host)) try: if proto == 'udp': __proto = socket.SOL_UDP else: __proto = socket.SOL_TCP proto = 'tcp' if family: if family == 'ipv4': __family = socket.AF_INET elif family == 'ipv6': __family = socket.AF_INET6 else: __family = 0 else: __family = 0 (family, socktype, _proto, garbage, _address) = socket.getaddrinfo(address, port, __family, 0, __proto)[0] skt = socket.socket(family, socktype, _proto) skt.settimeout(timeout) if proto == 'udp': # Generate a random string of a # decent size to test UDP connection md5h = hashlib.md5() md5h.update(datetime.datetime.now().strftime('%s')) msg = md5h.hexdigest() skt.sendto(msg, _address) recv, svr = skt.recvfrom(255) skt.close() else: skt.connect(_address) skt.shutdown(2) except Exception as exc: ret['result'] = False ret['comment'] = 'Unable to connect to {0} ({1}) on {2} port {3}'\ .format(host, _address[0], proto, port) return ret ret['result'] = True ret['comment'] = 'Successfully connected to {0} ({1}) on {2} port {3}'\ .format(host, _address[0], proto, port) return ret def is_private(ip_addr): ''' Check if the given IP address is a private address .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' network.is_private 10.0.0.3 ''' return ipaddress.ip_address(ip_addr).is_private
saltstack/salt
salt/modules/win_network.py
interfaces_names
python
def interfaces_names(): ''' Return a list of all the interfaces names CLI Example: .. code-block:: bash salt '*' network.interfaces_names ''' ret = [] with salt.utils.winapi.Com(): c = wmi.WMI() for iface in c.Win32_NetworkAdapter(NetEnabled=True): ret.append(iface.NetConnectionID) return ret
Return a list of all the interfaces names CLI Example: .. code-block:: bash salt '*' network.interfaces_names
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_network.py#L274-L290
null
# -*- coding: utf-8 -*- ''' Module for gathering and managing network information ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import re import hashlib import datetime import socket # Import Salt libs import salt.utils.network import salt.utils.platform import salt.utils.validate.net from salt.modules.network import (wol, get_hostname, interface, interface_ip, subnets6, ip_in_subnet, convert_cidr, calc_net, get_fqdn, ifacestartswith, iphexval) from salt.utils.functools import namespaced_function as _namespaced_function try: import salt.utils.winapi HAS_DEPENDENCIES = True except ImportError: HAS_DEPENDENCIES = False # Import 3rd party libraries import salt.ext.six as six # pylint: disable=W0611 try: import wmi # pylint: disable=W0611 except ImportError: HAS_DEPENDENCIES = False from salt._compat import ipaddress # Define the module's virtual name __virtualname__ = 'network' def __virtual__(): ''' Only works on Windows systems ''' if not salt.utils.platform.is_windows(): return False, "Module win_network: Only available on Windows" if not HAS_DEPENDENCIES: return False, "Module win_network: Missing dependencies" global wol, get_hostname, interface, interface_ip, subnets6, ip_in_subnet global convert_cidr, calc_net, get_fqdn, ifacestartswith, iphexval wol = _namespaced_function(wol, globals()) get_hostname = _namespaced_function(get_hostname, globals()) interface = _namespaced_function(interface, globals()) interface_ip = _namespaced_function(interface_ip, globals()) subnets6 = _namespaced_function(subnets6, globals()) ip_in_subnet = _namespaced_function(ip_in_subnet, globals()) convert_cidr = _namespaced_function(convert_cidr, globals()) calc_net = _namespaced_function(calc_net, globals()) get_fqdn = _namespaced_function(get_fqdn, globals()) ifacestartswith = _namespaced_function(ifacestartswith, globals()) iphexval = _namespaced_function(iphexval, globals()) return __virtualname__ def ping(host, timeout=False, return_boolean=False): ''' Performs a ping to a host CLI Example: .. code-block:: bash salt '*' network.ping archlinux.org .. versionadded:: 2016.11.0 Return a True or False instead of ping output. .. code-block:: bash salt '*' network.ping archlinux.org return_boolean=True Set the time to wait for a response in seconds. .. code-block:: bash salt '*' network.ping archlinux.org timeout=3 ''' if timeout: # Windows ping differs by having timeout be for individual echo requests.' # Divide timeout by tries to mimic BSD behaviour. timeout = int(timeout) * 1000 // 4 cmd = ['ping', '-n', '4', '-w', six.text_type(timeout), salt.utils.network.sanitize_host(host)] else: cmd = ['ping', '-n', '4', salt.utils.network.sanitize_host(host)] if return_boolean: ret = __salt__['cmd.run_all'](cmd, python_shell=False) if ret['retcode'] != 0: return False else: return True else: return __salt__['cmd.run'](cmd, python_shell=False) def netstat(): ''' Return information on open ports and states CLI Example: .. code-block:: bash salt '*' network.netstat ''' ret = [] cmd = ['netstat', '-nao'] lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines() for line in lines: comps = line.split() if line.startswith(' TCP'): ret.append({ 'local-address': comps[1], 'proto': comps[0], 'remote-address': comps[2], 'state': comps[3], 'program': comps[4]}) if line.startswith(' UDP'): ret.append({ 'local-address': comps[1], 'proto': comps[0], 'remote-address': comps[2], 'state': None, 'program': comps[3]}) return ret def traceroute(host): ''' Performs a traceroute to a 3rd party host CLI Example: .. code-block:: bash salt '*' network.traceroute archlinux.org ''' ret = [] cmd = ['tracert', salt.utils.network.sanitize_host(host)] lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines() for line in lines: if ' ' not in line: continue if line.startswith('Trac'): continue if line.startswith('over'): continue comps = line.split() complength = len(comps) # This method still needs to better catch rows of other lengths # For example if some of the ms returns are '*' if complength == 9: result = { 'count': comps[0], 'hostname': comps[7], 'ip': comps[8], 'ms1': comps[1], 'ms2': comps[3], 'ms3': comps[5]} ret.append(result) elif complength == 8: result = { 'count': comps[0], 'hostname': None, 'ip': comps[7], 'ms1': comps[1], 'ms2': comps[3], 'ms3': comps[5]} ret.append(result) else: result = { 'count': comps[0], 'hostname': None, 'ip': None, 'ms1': None, 'ms2': None, 'ms3': None} ret.append(result) return ret def nslookup(host): ''' Query DNS for information about a domain or ip address CLI Example: .. code-block:: bash salt '*' network.nslookup archlinux.org ''' ret = [] addresses = [] cmd = ['nslookup', salt.utils.network.sanitize_host(host)] lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines() for line in lines: if addresses: # We're in the last block listing addresses addresses.append(line.strip()) continue if line.startswith('Non-authoritative'): continue if 'Addresses' in line: comps = line.split(":", 1) addresses.append(comps[1].strip()) continue if ":" in line: comps = line.split(":", 1) ret.append({comps[0].strip(): comps[1].strip()}) if addresses: ret.append({'Addresses': addresses}) return ret def get_route(ip): ''' Return routing information for given destination ip .. versionadded:: 2016.11.5 CLI Example:: salt '*' network.get_route 10.10.10.10 ''' cmd = 'Find-NetRoute -RemoteIPAddress {0}'.format(ip) out = __salt__['cmd.run'](cmd, shell='powershell', python_shell=True) regexp = re.compile( r"^IPAddress\s+:\s(?P<source>[\d\.:]+)?.*" r"^InterfaceAlias\s+:\s(?P<interface>[\w\.\:\-\ ]+)?.*" r"^NextHop\s+:\s(?P<gateway>[\d\.:]+)", flags=re.MULTILINE | re.DOTALL ) m = regexp.search(out) ret = { 'destination': ip, 'gateway': m.group('gateway'), 'interface': m.group('interface'), 'source': m.group('source') } return ret def dig(host): ''' Performs a DNS lookup with dig Note: dig must be installed on the Windows minion CLI Example: .. code-block:: bash salt '*' network.dig archlinux.org ''' cmd = ['dig', salt.utils.network.sanitize_host(host)] return __salt__['cmd.run'](cmd, python_shell=False) def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion CLI Example: .. code-block:: bash salt '*' network.interfaces ''' return salt.utils.network.win_interfaces() def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface CLI Example: .. code-block:: bash salt '*' network.hw_addr 'Wireless Connection #1' ''' return salt.utils.network.hw_addr(iface) # Alias hwaddr to preserve backward compat hwaddr = salt.utils.functools.alias_function(hw_addr, 'hwaddr') def subnets(): ''' Returns a list of subnets to which the host belongs CLI Example: .. code-block:: bash salt '*' network.subnets ''' return salt.utils.network.subnets() def in_subnet(cidr): ''' Returns True if host is within specified subnet, otherwise False CLI Example: .. code-block:: bash salt '*' network.in_subnet 10.0.0.0/16 ''' return salt.utils.network.in_subnet(cidr) def ip_addrs(interface=None, include_loopback=False, cidr=None, type=None): ''' Returns a list of IPv4 addresses assigned to the host. interface Only IP addresses from that interface will be returned. include_loopback : False Include loopback 127.0.0.1 IPv4 address. cidr Describes subnet using CIDR notation and only IPv4 addresses that belong to this subnet will be returned. .. versionchanged:: 2019.2.0 type If option set to 'public' then only public addresses will be returned. Ditto for 'private'. .. versionchanged:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' network.ip_addrs salt '*' network.ip_addrs cidr=10.0.0.0/8 salt '*' network.ip_addrs cidr=192.168.0.0/16 type=private ''' addrs = salt.utils.network.ip_addrs(interface=interface, include_loopback=include_loopback) if cidr: return [i for i in addrs if salt.utils.network.in_subnet(cidr, [i])] else: if type == 'public': return [i for i in addrs if not is_private(i)] elif type == 'private': return [i for i in addrs if is_private(i)] else: return addrs ipaddrs = salt.utils.functools.alias_function(ip_addrs, 'ipaddrs') def ip_addrs6(interface=None, include_loopback=False, cidr=None): ''' Returns a list of IPv6 addresses assigned to the host. interface Only IP addresses from that interface will be returned. include_loopback : False Include loopback ::1 IPv6 address. cidr Describes subnet using CIDR notation and only IPv6 addresses that belong to this subnet will be returned. .. versionchanged:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' network.ip_addrs6 salt '*' network.ip_addrs6 cidr=2000::/3 ''' addrs = salt.utils.network.ip_addrs6(interface=interface, include_loopback=include_loopback) if cidr: return [i for i in addrs if salt.utils.network.in_subnet(cidr, [i])] else: return addrs ipaddrs6 = salt.utils.functools.alias_function(ip_addrs6, 'ipaddrs6') def connect(host, port=None, **kwargs): ''' Test connectivity to a host using a particular port from the minion. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' network.connect archlinux.org 80 salt '*' network.connect archlinux.org 80 timeout=3 salt '*' network.connect archlinux.org 80 timeout=3 family=ipv4 salt '*' network.connect google-public-dns-a.google.com port=53 proto=udp timeout=3 ''' ret = {'result': None, 'comment': ''} if not host: ret['result'] = False ret['comment'] = 'Required argument, host, is missing.' return ret if not port: ret['result'] = False ret['comment'] = 'Required argument, port, is missing.' return ret proto = kwargs.get('proto', 'tcp') timeout = kwargs.get('timeout', 5) family = kwargs.get('family', None) if salt.utils.validate.net.ipv4_addr(host) or salt.utils.validate.net.ipv6_addr(host): address = host else: address = '{0}'.format(salt.utils.network.sanitize_host(host)) try: if proto == 'udp': __proto = socket.SOL_UDP else: __proto = socket.SOL_TCP proto = 'tcp' if family: if family == 'ipv4': __family = socket.AF_INET elif family == 'ipv6': __family = socket.AF_INET6 else: __family = 0 else: __family = 0 (family, socktype, _proto, garbage, _address) = socket.getaddrinfo(address, port, __family, 0, __proto)[0] skt = socket.socket(family, socktype, _proto) skt.settimeout(timeout) if proto == 'udp': # Generate a random string of a # decent size to test UDP connection md5h = hashlib.md5() md5h.update(datetime.datetime.now().strftime('%s')) msg = md5h.hexdigest() skt.sendto(msg, _address) recv, svr = skt.recvfrom(255) skt.close() else: skt.connect(_address) skt.shutdown(2) except Exception as exc: ret['result'] = False ret['comment'] = 'Unable to connect to {0} ({1}) on {2} port {3}'\ .format(host, _address[0], proto, port) return ret ret['result'] = True ret['comment'] = 'Successfully connected to {0} ({1}) on {2} port {3}'\ .format(host, _address[0], proto, port) return ret def is_private(ip_addr): ''' Check if the given IP address is a private address .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' network.is_private 10.0.0.3 ''' return ipaddress.ip_address(ip_addr).is_private
saltstack/salt
salt/modules/win_network.py
ip_addrs
python
def ip_addrs(interface=None, include_loopback=False, cidr=None, type=None): ''' Returns a list of IPv4 addresses assigned to the host. interface Only IP addresses from that interface will be returned. include_loopback : False Include loopback 127.0.0.1 IPv4 address. cidr Describes subnet using CIDR notation and only IPv4 addresses that belong to this subnet will be returned. .. versionchanged:: 2019.2.0 type If option set to 'public' then only public addresses will be returned. Ditto for 'private'. .. versionchanged:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' network.ip_addrs salt '*' network.ip_addrs cidr=10.0.0.0/8 salt '*' network.ip_addrs cidr=192.168.0.0/16 type=private ''' addrs = salt.utils.network.ip_addrs(interface=interface, include_loopback=include_loopback) if cidr: return [i for i in addrs if salt.utils.network.in_subnet(cidr, [i])] else: if type == 'public': return [i for i in addrs if not is_private(i)] elif type == 'private': return [i for i in addrs if is_private(i)] else: return addrs
Returns a list of IPv4 addresses assigned to the host. interface Only IP addresses from that interface will be returned. include_loopback : False Include loopback 127.0.0.1 IPv4 address. cidr Describes subnet using CIDR notation and only IPv4 addresses that belong to this subnet will be returned. .. versionchanged:: 2019.2.0 type If option set to 'public' then only public addresses will be returned. Ditto for 'private'. .. versionchanged:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' network.ip_addrs salt '*' network.ip_addrs cidr=10.0.0.0/8 salt '*' network.ip_addrs cidr=192.168.0.0/16 type=private
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_network.py#L349-L389
[ "def ip_addrs(interface=None, include_loopback=False, interface_data=None):\n '''\n Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is\n ignored, unless 'include_loopback=True' is indicated. If 'interface' is\n provided, then only IP addresses from that interface will be returned.\n '''\n return _ip_addrs(interface, include_loopback, interface_data, 'inet')\n" ]
# -*- coding: utf-8 -*- ''' Module for gathering and managing network information ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import re import hashlib import datetime import socket # Import Salt libs import salt.utils.network import salt.utils.platform import salt.utils.validate.net from salt.modules.network import (wol, get_hostname, interface, interface_ip, subnets6, ip_in_subnet, convert_cidr, calc_net, get_fqdn, ifacestartswith, iphexval) from salt.utils.functools import namespaced_function as _namespaced_function try: import salt.utils.winapi HAS_DEPENDENCIES = True except ImportError: HAS_DEPENDENCIES = False # Import 3rd party libraries import salt.ext.six as six # pylint: disable=W0611 try: import wmi # pylint: disable=W0611 except ImportError: HAS_DEPENDENCIES = False from salt._compat import ipaddress # Define the module's virtual name __virtualname__ = 'network' def __virtual__(): ''' Only works on Windows systems ''' if not salt.utils.platform.is_windows(): return False, "Module win_network: Only available on Windows" if not HAS_DEPENDENCIES: return False, "Module win_network: Missing dependencies" global wol, get_hostname, interface, interface_ip, subnets6, ip_in_subnet global convert_cidr, calc_net, get_fqdn, ifacestartswith, iphexval wol = _namespaced_function(wol, globals()) get_hostname = _namespaced_function(get_hostname, globals()) interface = _namespaced_function(interface, globals()) interface_ip = _namespaced_function(interface_ip, globals()) subnets6 = _namespaced_function(subnets6, globals()) ip_in_subnet = _namespaced_function(ip_in_subnet, globals()) convert_cidr = _namespaced_function(convert_cidr, globals()) calc_net = _namespaced_function(calc_net, globals()) get_fqdn = _namespaced_function(get_fqdn, globals()) ifacestartswith = _namespaced_function(ifacestartswith, globals()) iphexval = _namespaced_function(iphexval, globals()) return __virtualname__ def ping(host, timeout=False, return_boolean=False): ''' Performs a ping to a host CLI Example: .. code-block:: bash salt '*' network.ping archlinux.org .. versionadded:: 2016.11.0 Return a True or False instead of ping output. .. code-block:: bash salt '*' network.ping archlinux.org return_boolean=True Set the time to wait for a response in seconds. .. code-block:: bash salt '*' network.ping archlinux.org timeout=3 ''' if timeout: # Windows ping differs by having timeout be for individual echo requests.' # Divide timeout by tries to mimic BSD behaviour. timeout = int(timeout) * 1000 // 4 cmd = ['ping', '-n', '4', '-w', six.text_type(timeout), salt.utils.network.sanitize_host(host)] else: cmd = ['ping', '-n', '4', salt.utils.network.sanitize_host(host)] if return_boolean: ret = __salt__['cmd.run_all'](cmd, python_shell=False) if ret['retcode'] != 0: return False else: return True else: return __salt__['cmd.run'](cmd, python_shell=False) def netstat(): ''' Return information on open ports and states CLI Example: .. code-block:: bash salt '*' network.netstat ''' ret = [] cmd = ['netstat', '-nao'] lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines() for line in lines: comps = line.split() if line.startswith(' TCP'): ret.append({ 'local-address': comps[1], 'proto': comps[0], 'remote-address': comps[2], 'state': comps[3], 'program': comps[4]}) if line.startswith(' UDP'): ret.append({ 'local-address': comps[1], 'proto': comps[0], 'remote-address': comps[2], 'state': None, 'program': comps[3]}) return ret def traceroute(host): ''' Performs a traceroute to a 3rd party host CLI Example: .. code-block:: bash salt '*' network.traceroute archlinux.org ''' ret = [] cmd = ['tracert', salt.utils.network.sanitize_host(host)] lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines() for line in lines: if ' ' not in line: continue if line.startswith('Trac'): continue if line.startswith('over'): continue comps = line.split() complength = len(comps) # This method still needs to better catch rows of other lengths # For example if some of the ms returns are '*' if complength == 9: result = { 'count': comps[0], 'hostname': comps[7], 'ip': comps[8], 'ms1': comps[1], 'ms2': comps[3], 'ms3': comps[5]} ret.append(result) elif complength == 8: result = { 'count': comps[0], 'hostname': None, 'ip': comps[7], 'ms1': comps[1], 'ms2': comps[3], 'ms3': comps[5]} ret.append(result) else: result = { 'count': comps[0], 'hostname': None, 'ip': None, 'ms1': None, 'ms2': None, 'ms3': None} ret.append(result) return ret def nslookup(host): ''' Query DNS for information about a domain or ip address CLI Example: .. code-block:: bash salt '*' network.nslookup archlinux.org ''' ret = [] addresses = [] cmd = ['nslookup', salt.utils.network.sanitize_host(host)] lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines() for line in lines: if addresses: # We're in the last block listing addresses addresses.append(line.strip()) continue if line.startswith('Non-authoritative'): continue if 'Addresses' in line: comps = line.split(":", 1) addresses.append(comps[1].strip()) continue if ":" in line: comps = line.split(":", 1) ret.append({comps[0].strip(): comps[1].strip()}) if addresses: ret.append({'Addresses': addresses}) return ret def get_route(ip): ''' Return routing information for given destination ip .. versionadded:: 2016.11.5 CLI Example:: salt '*' network.get_route 10.10.10.10 ''' cmd = 'Find-NetRoute -RemoteIPAddress {0}'.format(ip) out = __salt__['cmd.run'](cmd, shell='powershell', python_shell=True) regexp = re.compile( r"^IPAddress\s+:\s(?P<source>[\d\.:]+)?.*" r"^InterfaceAlias\s+:\s(?P<interface>[\w\.\:\-\ ]+)?.*" r"^NextHop\s+:\s(?P<gateway>[\d\.:]+)", flags=re.MULTILINE | re.DOTALL ) m = regexp.search(out) ret = { 'destination': ip, 'gateway': m.group('gateway'), 'interface': m.group('interface'), 'source': m.group('source') } return ret def dig(host): ''' Performs a DNS lookup with dig Note: dig must be installed on the Windows minion CLI Example: .. code-block:: bash salt '*' network.dig archlinux.org ''' cmd = ['dig', salt.utils.network.sanitize_host(host)] return __salt__['cmd.run'](cmd, python_shell=False) def interfaces_names(): ''' Return a list of all the interfaces names CLI Example: .. code-block:: bash salt '*' network.interfaces_names ''' ret = [] with salt.utils.winapi.Com(): c = wmi.WMI() for iface in c.Win32_NetworkAdapter(NetEnabled=True): ret.append(iface.NetConnectionID) return ret def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion CLI Example: .. code-block:: bash salt '*' network.interfaces ''' return salt.utils.network.win_interfaces() def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface CLI Example: .. code-block:: bash salt '*' network.hw_addr 'Wireless Connection #1' ''' return salt.utils.network.hw_addr(iface) # Alias hwaddr to preserve backward compat hwaddr = salt.utils.functools.alias_function(hw_addr, 'hwaddr') def subnets(): ''' Returns a list of subnets to which the host belongs CLI Example: .. code-block:: bash salt '*' network.subnets ''' return salt.utils.network.subnets() def in_subnet(cidr): ''' Returns True if host is within specified subnet, otherwise False CLI Example: .. code-block:: bash salt '*' network.in_subnet 10.0.0.0/16 ''' return salt.utils.network.in_subnet(cidr) ipaddrs = salt.utils.functools.alias_function(ip_addrs, 'ipaddrs') def ip_addrs6(interface=None, include_loopback=False, cidr=None): ''' Returns a list of IPv6 addresses assigned to the host. interface Only IP addresses from that interface will be returned. include_loopback : False Include loopback ::1 IPv6 address. cidr Describes subnet using CIDR notation and only IPv6 addresses that belong to this subnet will be returned. .. versionchanged:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' network.ip_addrs6 salt '*' network.ip_addrs6 cidr=2000::/3 ''' addrs = salt.utils.network.ip_addrs6(interface=interface, include_loopback=include_loopback) if cidr: return [i for i in addrs if salt.utils.network.in_subnet(cidr, [i])] else: return addrs ipaddrs6 = salt.utils.functools.alias_function(ip_addrs6, 'ipaddrs6') def connect(host, port=None, **kwargs): ''' Test connectivity to a host using a particular port from the minion. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' network.connect archlinux.org 80 salt '*' network.connect archlinux.org 80 timeout=3 salt '*' network.connect archlinux.org 80 timeout=3 family=ipv4 salt '*' network.connect google-public-dns-a.google.com port=53 proto=udp timeout=3 ''' ret = {'result': None, 'comment': ''} if not host: ret['result'] = False ret['comment'] = 'Required argument, host, is missing.' return ret if not port: ret['result'] = False ret['comment'] = 'Required argument, port, is missing.' return ret proto = kwargs.get('proto', 'tcp') timeout = kwargs.get('timeout', 5) family = kwargs.get('family', None) if salt.utils.validate.net.ipv4_addr(host) or salt.utils.validate.net.ipv6_addr(host): address = host else: address = '{0}'.format(salt.utils.network.sanitize_host(host)) try: if proto == 'udp': __proto = socket.SOL_UDP else: __proto = socket.SOL_TCP proto = 'tcp' if family: if family == 'ipv4': __family = socket.AF_INET elif family == 'ipv6': __family = socket.AF_INET6 else: __family = 0 else: __family = 0 (family, socktype, _proto, garbage, _address) = socket.getaddrinfo(address, port, __family, 0, __proto)[0] skt = socket.socket(family, socktype, _proto) skt.settimeout(timeout) if proto == 'udp': # Generate a random string of a # decent size to test UDP connection md5h = hashlib.md5() md5h.update(datetime.datetime.now().strftime('%s')) msg = md5h.hexdigest() skt.sendto(msg, _address) recv, svr = skt.recvfrom(255) skt.close() else: skt.connect(_address) skt.shutdown(2) except Exception as exc: ret['result'] = False ret['comment'] = 'Unable to connect to {0} ({1}) on {2} port {3}'\ .format(host, _address[0], proto, port) return ret ret['result'] = True ret['comment'] = 'Successfully connected to {0} ({1}) on {2} port {3}'\ .format(host, _address[0], proto, port) return ret def is_private(ip_addr): ''' Check if the given IP address is a private address .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' network.is_private 10.0.0.3 ''' return ipaddress.ip_address(ip_addr).is_private
saltstack/salt
salt/modules/win_network.py
ip_addrs6
python
def ip_addrs6(interface=None, include_loopback=False, cidr=None): ''' Returns a list of IPv6 addresses assigned to the host. interface Only IP addresses from that interface will be returned. include_loopback : False Include loopback ::1 IPv6 address. cidr Describes subnet using CIDR notation and only IPv6 addresses that belong to this subnet will be returned. .. versionchanged:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' network.ip_addrs6 salt '*' network.ip_addrs6 cidr=2000::/3 ''' addrs = salt.utils.network.ip_addrs6(interface=interface, include_loopback=include_loopback) if cidr: return [i for i in addrs if salt.utils.network.in_subnet(cidr, [i])] else: return addrs
Returns a list of IPv6 addresses assigned to the host. interface Only IP addresses from that interface will be returned. include_loopback : False Include loopback ::1 IPv6 address. cidr Describes subnet using CIDR notation and only IPv6 addresses that belong to this subnet will be returned. .. versionchanged:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' network.ip_addrs6 salt '*' network.ip_addrs6 cidr=2000::/3
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_network.py#L395-L423
[ "def ip_addrs6(interface=None, include_loopback=False, interface_data=None):\n '''\n Returns a list of IPv6 addresses assigned to the host. ::1 is ignored,\n unless 'include_loopback=True' is indicated. If 'interface' is provided,\n then only IP addresses from that interface will be returned.\n '''\n return _ip_addrs(interface, include_loopback, interface_data, 'inet6')\n" ]
# -*- coding: utf-8 -*- ''' Module for gathering and managing network information ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import re import hashlib import datetime import socket # Import Salt libs import salt.utils.network import salt.utils.platform import salt.utils.validate.net from salt.modules.network import (wol, get_hostname, interface, interface_ip, subnets6, ip_in_subnet, convert_cidr, calc_net, get_fqdn, ifacestartswith, iphexval) from salt.utils.functools import namespaced_function as _namespaced_function try: import salt.utils.winapi HAS_DEPENDENCIES = True except ImportError: HAS_DEPENDENCIES = False # Import 3rd party libraries import salt.ext.six as six # pylint: disable=W0611 try: import wmi # pylint: disable=W0611 except ImportError: HAS_DEPENDENCIES = False from salt._compat import ipaddress # Define the module's virtual name __virtualname__ = 'network' def __virtual__(): ''' Only works on Windows systems ''' if not salt.utils.platform.is_windows(): return False, "Module win_network: Only available on Windows" if not HAS_DEPENDENCIES: return False, "Module win_network: Missing dependencies" global wol, get_hostname, interface, interface_ip, subnets6, ip_in_subnet global convert_cidr, calc_net, get_fqdn, ifacestartswith, iphexval wol = _namespaced_function(wol, globals()) get_hostname = _namespaced_function(get_hostname, globals()) interface = _namespaced_function(interface, globals()) interface_ip = _namespaced_function(interface_ip, globals()) subnets6 = _namespaced_function(subnets6, globals()) ip_in_subnet = _namespaced_function(ip_in_subnet, globals()) convert_cidr = _namespaced_function(convert_cidr, globals()) calc_net = _namespaced_function(calc_net, globals()) get_fqdn = _namespaced_function(get_fqdn, globals()) ifacestartswith = _namespaced_function(ifacestartswith, globals()) iphexval = _namespaced_function(iphexval, globals()) return __virtualname__ def ping(host, timeout=False, return_boolean=False): ''' Performs a ping to a host CLI Example: .. code-block:: bash salt '*' network.ping archlinux.org .. versionadded:: 2016.11.0 Return a True or False instead of ping output. .. code-block:: bash salt '*' network.ping archlinux.org return_boolean=True Set the time to wait for a response in seconds. .. code-block:: bash salt '*' network.ping archlinux.org timeout=3 ''' if timeout: # Windows ping differs by having timeout be for individual echo requests.' # Divide timeout by tries to mimic BSD behaviour. timeout = int(timeout) * 1000 // 4 cmd = ['ping', '-n', '4', '-w', six.text_type(timeout), salt.utils.network.sanitize_host(host)] else: cmd = ['ping', '-n', '4', salt.utils.network.sanitize_host(host)] if return_boolean: ret = __salt__['cmd.run_all'](cmd, python_shell=False) if ret['retcode'] != 0: return False else: return True else: return __salt__['cmd.run'](cmd, python_shell=False) def netstat(): ''' Return information on open ports and states CLI Example: .. code-block:: bash salt '*' network.netstat ''' ret = [] cmd = ['netstat', '-nao'] lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines() for line in lines: comps = line.split() if line.startswith(' TCP'): ret.append({ 'local-address': comps[1], 'proto': comps[0], 'remote-address': comps[2], 'state': comps[3], 'program': comps[4]}) if line.startswith(' UDP'): ret.append({ 'local-address': comps[1], 'proto': comps[0], 'remote-address': comps[2], 'state': None, 'program': comps[3]}) return ret def traceroute(host): ''' Performs a traceroute to a 3rd party host CLI Example: .. code-block:: bash salt '*' network.traceroute archlinux.org ''' ret = [] cmd = ['tracert', salt.utils.network.sanitize_host(host)] lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines() for line in lines: if ' ' not in line: continue if line.startswith('Trac'): continue if line.startswith('over'): continue comps = line.split() complength = len(comps) # This method still needs to better catch rows of other lengths # For example if some of the ms returns are '*' if complength == 9: result = { 'count': comps[0], 'hostname': comps[7], 'ip': comps[8], 'ms1': comps[1], 'ms2': comps[3], 'ms3': comps[5]} ret.append(result) elif complength == 8: result = { 'count': comps[0], 'hostname': None, 'ip': comps[7], 'ms1': comps[1], 'ms2': comps[3], 'ms3': comps[5]} ret.append(result) else: result = { 'count': comps[0], 'hostname': None, 'ip': None, 'ms1': None, 'ms2': None, 'ms3': None} ret.append(result) return ret def nslookup(host): ''' Query DNS for information about a domain or ip address CLI Example: .. code-block:: bash salt '*' network.nslookup archlinux.org ''' ret = [] addresses = [] cmd = ['nslookup', salt.utils.network.sanitize_host(host)] lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines() for line in lines: if addresses: # We're in the last block listing addresses addresses.append(line.strip()) continue if line.startswith('Non-authoritative'): continue if 'Addresses' in line: comps = line.split(":", 1) addresses.append(comps[1].strip()) continue if ":" in line: comps = line.split(":", 1) ret.append({comps[0].strip(): comps[1].strip()}) if addresses: ret.append({'Addresses': addresses}) return ret def get_route(ip): ''' Return routing information for given destination ip .. versionadded:: 2016.11.5 CLI Example:: salt '*' network.get_route 10.10.10.10 ''' cmd = 'Find-NetRoute -RemoteIPAddress {0}'.format(ip) out = __salt__['cmd.run'](cmd, shell='powershell', python_shell=True) regexp = re.compile( r"^IPAddress\s+:\s(?P<source>[\d\.:]+)?.*" r"^InterfaceAlias\s+:\s(?P<interface>[\w\.\:\-\ ]+)?.*" r"^NextHop\s+:\s(?P<gateway>[\d\.:]+)", flags=re.MULTILINE | re.DOTALL ) m = regexp.search(out) ret = { 'destination': ip, 'gateway': m.group('gateway'), 'interface': m.group('interface'), 'source': m.group('source') } return ret def dig(host): ''' Performs a DNS lookup with dig Note: dig must be installed on the Windows minion CLI Example: .. code-block:: bash salt '*' network.dig archlinux.org ''' cmd = ['dig', salt.utils.network.sanitize_host(host)] return __salt__['cmd.run'](cmd, python_shell=False) def interfaces_names(): ''' Return a list of all the interfaces names CLI Example: .. code-block:: bash salt '*' network.interfaces_names ''' ret = [] with salt.utils.winapi.Com(): c = wmi.WMI() for iface in c.Win32_NetworkAdapter(NetEnabled=True): ret.append(iface.NetConnectionID) return ret def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion CLI Example: .. code-block:: bash salt '*' network.interfaces ''' return salt.utils.network.win_interfaces() def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface CLI Example: .. code-block:: bash salt '*' network.hw_addr 'Wireless Connection #1' ''' return salt.utils.network.hw_addr(iface) # Alias hwaddr to preserve backward compat hwaddr = salt.utils.functools.alias_function(hw_addr, 'hwaddr') def subnets(): ''' Returns a list of subnets to which the host belongs CLI Example: .. code-block:: bash salt '*' network.subnets ''' return salt.utils.network.subnets() def in_subnet(cidr): ''' Returns True if host is within specified subnet, otherwise False CLI Example: .. code-block:: bash salt '*' network.in_subnet 10.0.0.0/16 ''' return salt.utils.network.in_subnet(cidr) def ip_addrs(interface=None, include_loopback=False, cidr=None, type=None): ''' Returns a list of IPv4 addresses assigned to the host. interface Only IP addresses from that interface will be returned. include_loopback : False Include loopback 127.0.0.1 IPv4 address. cidr Describes subnet using CIDR notation and only IPv4 addresses that belong to this subnet will be returned. .. versionchanged:: 2019.2.0 type If option set to 'public' then only public addresses will be returned. Ditto for 'private'. .. versionchanged:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' network.ip_addrs salt '*' network.ip_addrs cidr=10.0.0.0/8 salt '*' network.ip_addrs cidr=192.168.0.0/16 type=private ''' addrs = salt.utils.network.ip_addrs(interface=interface, include_loopback=include_loopback) if cidr: return [i for i in addrs if salt.utils.network.in_subnet(cidr, [i])] else: if type == 'public': return [i for i in addrs if not is_private(i)] elif type == 'private': return [i for i in addrs if is_private(i)] else: return addrs ipaddrs = salt.utils.functools.alias_function(ip_addrs, 'ipaddrs') ipaddrs6 = salt.utils.functools.alias_function(ip_addrs6, 'ipaddrs6') def connect(host, port=None, **kwargs): ''' Test connectivity to a host using a particular port from the minion. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' network.connect archlinux.org 80 salt '*' network.connect archlinux.org 80 timeout=3 salt '*' network.connect archlinux.org 80 timeout=3 family=ipv4 salt '*' network.connect google-public-dns-a.google.com port=53 proto=udp timeout=3 ''' ret = {'result': None, 'comment': ''} if not host: ret['result'] = False ret['comment'] = 'Required argument, host, is missing.' return ret if not port: ret['result'] = False ret['comment'] = 'Required argument, port, is missing.' return ret proto = kwargs.get('proto', 'tcp') timeout = kwargs.get('timeout', 5) family = kwargs.get('family', None) if salt.utils.validate.net.ipv4_addr(host) or salt.utils.validate.net.ipv6_addr(host): address = host else: address = '{0}'.format(salt.utils.network.sanitize_host(host)) try: if proto == 'udp': __proto = socket.SOL_UDP else: __proto = socket.SOL_TCP proto = 'tcp' if family: if family == 'ipv4': __family = socket.AF_INET elif family == 'ipv6': __family = socket.AF_INET6 else: __family = 0 else: __family = 0 (family, socktype, _proto, garbage, _address) = socket.getaddrinfo(address, port, __family, 0, __proto)[0] skt = socket.socket(family, socktype, _proto) skt.settimeout(timeout) if proto == 'udp': # Generate a random string of a # decent size to test UDP connection md5h = hashlib.md5() md5h.update(datetime.datetime.now().strftime('%s')) msg = md5h.hexdigest() skt.sendto(msg, _address) recv, svr = skt.recvfrom(255) skt.close() else: skt.connect(_address) skt.shutdown(2) except Exception as exc: ret['result'] = False ret['comment'] = 'Unable to connect to {0} ({1}) on {2} port {3}'\ .format(host, _address[0], proto, port) return ret ret['result'] = True ret['comment'] = 'Successfully connected to {0} ({1}) on {2} port {3}'\ .format(host, _address[0], proto, port) return ret def is_private(ip_addr): ''' Check if the given IP address is a private address .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' network.is_private 10.0.0.3 ''' return ipaddress.ip_address(ip_addr).is_private
saltstack/salt
salt/modules/win_network.py
connect
python
def connect(host, port=None, **kwargs): ''' Test connectivity to a host using a particular port from the minion. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' network.connect archlinux.org 80 salt '*' network.connect archlinux.org 80 timeout=3 salt '*' network.connect archlinux.org 80 timeout=3 family=ipv4 salt '*' network.connect google-public-dns-a.google.com port=53 proto=udp timeout=3 ''' ret = {'result': None, 'comment': ''} if not host: ret['result'] = False ret['comment'] = 'Required argument, host, is missing.' return ret if not port: ret['result'] = False ret['comment'] = 'Required argument, port, is missing.' return ret proto = kwargs.get('proto', 'tcp') timeout = kwargs.get('timeout', 5) family = kwargs.get('family', None) if salt.utils.validate.net.ipv4_addr(host) or salt.utils.validate.net.ipv6_addr(host): address = host else: address = '{0}'.format(salt.utils.network.sanitize_host(host)) try: if proto == 'udp': __proto = socket.SOL_UDP else: __proto = socket.SOL_TCP proto = 'tcp' if family: if family == 'ipv4': __family = socket.AF_INET elif family == 'ipv6': __family = socket.AF_INET6 else: __family = 0 else: __family = 0 (family, socktype, _proto, garbage, _address) = socket.getaddrinfo(address, port, __family, 0, __proto)[0] skt = socket.socket(family, socktype, _proto) skt.settimeout(timeout) if proto == 'udp': # Generate a random string of a # decent size to test UDP connection md5h = hashlib.md5() md5h.update(datetime.datetime.now().strftime('%s')) msg = md5h.hexdigest() skt.sendto(msg, _address) recv, svr = skt.recvfrom(255) skt.close() else: skt.connect(_address) skt.shutdown(2) except Exception as exc: ret['result'] = False ret['comment'] = 'Unable to connect to {0} ({1}) on {2} port {3}'\ .format(host, _address[0], proto, port) return ret ret['result'] = True ret['comment'] = 'Successfully connected to {0} ({1}) on {2} port {3}'\ .format(host, _address[0], proto, port) return ret
Test connectivity to a host using a particular port from the minion. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' network.connect archlinux.org 80 salt '*' network.connect archlinux.org 80 timeout=3 salt '*' network.connect archlinux.org 80 timeout=3 family=ipv4 salt '*' network.connect google-public-dns-a.google.com port=53 proto=udp timeout=3
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_network.py#L429-L518
[ "def ipv4_addr(addr):\n '''\n Returns True if the IPv4 address (and optional subnet) are valid, otherwise\n returns False.\n '''\n return __ip_addr(addr, socket.AF_INET)\n" ]
# -*- coding: utf-8 -*- ''' Module for gathering and managing network information ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import re import hashlib import datetime import socket # Import Salt libs import salt.utils.network import salt.utils.platform import salt.utils.validate.net from salt.modules.network import (wol, get_hostname, interface, interface_ip, subnets6, ip_in_subnet, convert_cidr, calc_net, get_fqdn, ifacestartswith, iphexval) from salt.utils.functools import namespaced_function as _namespaced_function try: import salt.utils.winapi HAS_DEPENDENCIES = True except ImportError: HAS_DEPENDENCIES = False # Import 3rd party libraries import salt.ext.six as six # pylint: disable=W0611 try: import wmi # pylint: disable=W0611 except ImportError: HAS_DEPENDENCIES = False from salt._compat import ipaddress # Define the module's virtual name __virtualname__ = 'network' def __virtual__(): ''' Only works on Windows systems ''' if not salt.utils.platform.is_windows(): return False, "Module win_network: Only available on Windows" if not HAS_DEPENDENCIES: return False, "Module win_network: Missing dependencies" global wol, get_hostname, interface, interface_ip, subnets6, ip_in_subnet global convert_cidr, calc_net, get_fqdn, ifacestartswith, iphexval wol = _namespaced_function(wol, globals()) get_hostname = _namespaced_function(get_hostname, globals()) interface = _namespaced_function(interface, globals()) interface_ip = _namespaced_function(interface_ip, globals()) subnets6 = _namespaced_function(subnets6, globals()) ip_in_subnet = _namespaced_function(ip_in_subnet, globals()) convert_cidr = _namespaced_function(convert_cidr, globals()) calc_net = _namespaced_function(calc_net, globals()) get_fqdn = _namespaced_function(get_fqdn, globals()) ifacestartswith = _namespaced_function(ifacestartswith, globals()) iphexval = _namespaced_function(iphexval, globals()) return __virtualname__ def ping(host, timeout=False, return_boolean=False): ''' Performs a ping to a host CLI Example: .. code-block:: bash salt '*' network.ping archlinux.org .. versionadded:: 2016.11.0 Return a True or False instead of ping output. .. code-block:: bash salt '*' network.ping archlinux.org return_boolean=True Set the time to wait for a response in seconds. .. code-block:: bash salt '*' network.ping archlinux.org timeout=3 ''' if timeout: # Windows ping differs by having timeout be for individual echo requests.' # Divide timeout by tries to mimic BSD behaviour. timeout = int(timeout) * 1000 // 4 cmd = ['ping', '-n', '4', '-w', six.text_type(timeout), salt.utils.network.sanitize_host(host)] else: cmd = ['ping', '-n', '4', salt.utils.network.sanitize_host(host)] if return_boolean: ret = __salt__['cmd.run_all'](cmd, python_shell=False) if ret['retcode'] != 0: return False else: return True else: return __salt__['cmd.run'](cmd, python_shell=False) def netstat(): ''' Return information on open ports and states CLI Example: .. code-block:: bash salt '*' network.netstat ''' ret = [] cmd = ['netstat', '-nao'] lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines() for line in lines: comps = line.split() if line.startswith(' TCP'): ret.append({ 'local-address': comps[1], 'proto': comps[0], 'remote-address': comps[2], 'state': comps[3], 'program': comps[4]}) if line.startswith(' UDP'): ret.append({ 'local-address': comps[1], 'proto': comps[0], 'remote-address': comps[2], 'state': None, 'program': comps[3]}) return ret def traceroute(host): ''' Performs a traceroute to a 3rd party host CLI Example: .. code-block:: bash salt '*' network.traceroute archlinux.org ''' ret = [] cmd = ['tracert', salt.utils.network.sanitize_host(host)] lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines() for line in lines: if ' ' not in line: continue if line.startswith('Trac'): continue if line.startswith('over'): continue comps = line.split() complength = len(comps) # This method still needs to better catch rows of other lengths # For example if some of the ms returns are '*' if complength == 9: result = { 'count': comps[0], 'hostname': comps[7], 'ip': comps[8], 'ms1': comps[1], 'ms2': comps[3], 'ms3': comps[5]} ret.append(result) elif complength == 8: result = { 'count': comps[0], 'hostname': None, 'ip': comps[7], 'ms1': comps[1], 'ms2': comps[3], 'ms3': comps[5]} ret.append(result) else: result = { 'count': comps[0], 'hostname': None, 'ip': None, 'ms1': None, 'ms2': None, 'ms3': None} ret.append(result) return ret def nslookup(host): ''' Query DNS for information about a domain or ip address CLI Example: .. code-block:: bash salt '*' network.nslookup archlinux.org ''' ret = [] addresses = [] cmd = ['nslookup', salt.utils.network.sanitize_host(host)] lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines() for line in lines: if addresses: # We're in the last block listing addresses addresses.append(line.strip()) continue if line.startswith('Non-authoritative'): continue if 'Addresses' in line: comps = line.split(":", 1) addresses.append(comps[1].strip()) continue if ":" in line: comps = line.split(":", 1) ret.append({comps[0].strip(): comps[1].strip()}) if addresses: ret.append({'Addresses': addresses}) return ret def get_route(ip): ''' Return routing information for given destination ip .. versionadded:: 2016.11.5 CLI Example:: salt '*' network.get_route 10.10.10.10 ''' cmd = 'Find-NetRoute -RemoteIPAddress {0}'.format(ip) out = __salt__['cmd.run'](cmd, shell='powershell', python_shell=True) regexp = re.compile( r"^IPAddress\s+:\s(?P<source>[\d\.:]+)?.*" r"^InterfaceAlias\s+:\s(?P<interface>[\w\.\:\-\ ]+)?.*" r"^NextHop\s+:\s(?P<gateway>[\d\.:]+)", flags=re.MULTILINE | re.DOTALL ) m = regexp.search(out) ret = { 'destination': ip, 'gateway': m.group('gateway'), 'interface': m.group('interface'), 'source': m.group('source') } return ret def dig(host): ''' Performs a DNS lookup with dig Note: dig must be installed on the Windows minion CLI Example: .. code-block:: bash salt '*' network.dig archlinux.org ''' cmd = ['dig', salt.utils.network.sanitize_host(host)] return __salt__['cmd.run'](cmd, python_shell=False) def interfaces_names(): ''' Return a list of all the interfaces names CLI Example: .. code-block:: bash salt '*' network.interfaces_names ''' ret = [] with salt.utils.winapi.Com(): c = wmi.WMI() for iface in c.Win32_NetworkAdapter(NetEnabled=True): ret.append(iface.NetConnectionID) return ret def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion CLI Example: .. code-block:: bash salt '*' network.interfaces ''' return salt.utils.network.win_interfaces() def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface CLI Example: .. code-block:: bash salt '*' network.hw_addr 'Wireless Connection #1' ''' return salt.utils.network.hw_addr(iface) # Alias hwaddr to preserve backward compat hwaddr = salt.utils.functools.alias_function(hw_addr, 'hwaddr') def subnets(): ''' Returns a list of subnets to which the host belongs CLI Example: .. code-block:: bash salt '*' network.subnets ''' return salt.utils.network.subnets() def in_subnet(cidr): ''' Returns True if host is within specified subnet, otherwise False CLI Example: .. code-block:: bash salt '*' network.in_subnet 10.0.0.0/16 ''' return salt.utils.network.in_subnet(cidr) def ip_addrs(interface=None, include_loopback=False, cidr=None, type=None): ''' Returns a list of IPv4 addresses assigned to the host. interface Only IP addresses from that interface will be returned. include_loopback : False Include loopback 127.0.0.1 IPv4 address. cidr Describes subnet using CIDR notation and only IPv4 addresses that belong to this subnet will be returned. .. versionchanged:: 2019.2.0 type If option set to 'public' then only public addresses will be returned. Ditto for 'private'. .. versionchanged:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' network.ip_addrs salt '*' network.ip_addrs cidr=10.0.0.0/8 salt '*' network.ip_addrs cidr=192.168.0.0/16 type=private ''' addrs = salt.utils.network.ip_addrs(interface=interface, include_loopback=include_loopback) if cidr: return [i for i in addrs if salt.utils.network.in_subnet(cidr, [i])] else: if type == 'public': return [i for i in addrs if not is_private(i)] elif type == 'private': return [i for i in addrs if is_private(i)] else: return addrs ipaddrs = salt.utils.functools.alias_function(ip_addrs, 'ipaddrs') def ip_addrs6(interface=None, include_loopback=False, cidr=None): ''' Returns a list of IPv6 addresses assigned to the host. interface Only IP addresses from that interface will be returned. include_loopback : False Include loopback ::1 IPv6 address. cidr Describes subnet using CIDR notation and only IPv6 addresses that belong to this subnet will be returned. .. versionchanged:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' network.ip_addrs6 salt '*' network.ip_addrs6 cidr=2000::/3 ''' addrs = salt.utils.network.ip_addrs6(interface=interface, include_loopback=include_loopback) if cidr: return [i for i in addrs if salt.utils.network.in_subnet(cidr, [i])] else: return addrs ipaddrs6 = salt.utils.functools.alias_function(ip_addrs6, 'ipaddrs6') def is_private(ip_addr): ''' Check if the given IP address is a private address .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' network.is_private 10.0.0.3 ''' return ipaddress.ip_address(ip_addr).is_private
saltstack/salt
salt/returners/pushover_returner.py
_post_message
python
def _post_message(user, device, message, title, priority, expire, retry, sound, api_version=1, token=None): ''' Send a message to a Pushover user or group. :param user: The user or group to send to, must be key of user or group not email address. :param message: The message to send to the PushOver user or group. :param title: Specify who the message is from. :param priority The priority of the message, defaults to 0. :param api_version: The PushOver API version, if not specified in the configuration. :param notify: Whether to notify the room, default: False. :param token: The PushOver token, if not specified in the configuration. :return: Boolean if message was sent successfully. ''' user_validate = salt.utils.pushover.validate_user(user, device, token) if not user_validate['result']: return user_validate parameters = dict() parameters['user'] = user parameters['device'] = device parameters['token'] = token parameters['title'] = title parameters['priority'] = priority parameters['expire'] = expire parameters['retry'] = retry parameters['message'] = message if sound: sound_validate = salt.utils.pushover.validate_sound(sound, token) if sound_validate['res']: parameters['sound'] = sound result = salt.utils.pushover.query(function='message', method='POST', header_dict={'Content-Type': 'application/x-www-form-urlencoded'}, data=_urlencode(parameters), opts=__opts__) return result
Send a message to a Pushover user or group. :param user: The user or group to send to, must be key of user or group not email address. :param message: The message to send to the PushOver user or group. :param title: Specify who the message is from. :param priority The priority of the message, defaults to 0. :param api_version: The PushOver API version, if not specified in the configuration. :param notify: Whether to notify the room, default: False. :param token: The PushOver token, if not specified in the configuration. :return: Boolean if message was sent successfully.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/pushover_returner.py#L151-L198
[ "def query(function,\n token=None,\n api_version='1',\n method='POST',\n header_dict=None,\n data=None,\n query_params=None,\n opts=None):\n '''\n PushOver object method function to construct and execute on the API URL.\n\n :param token: The PushOver api key.\n :param api_version: The PushOver API version to use, defaults to version 1.\n :param function: The PushOver api function to perform.\n :param method: The HTTP method, e.g. GET or POST.\n :param data: The data to be sent for POST method.\n :return: The json response from the API call or False.\n '''\n\n ret = {'message': '',\n 'res': True}\n\n pushover_functions = {\n 'message': {\n 'request': 'messages.json',\n 'response': 'status',\n },\n 'validate_user': {\n 'request': 'users/validate.json',\n 'response': 'status',\n },\n 'validate_sound': {\n 'request': 'sounds.json',\n 'response': 'status',\n },\n }\n\n api_url = 'https://api.pushover.net'\n base_url = _urljoin(api_url, api_version + '/')\n path = pushover_functions.get(function).get('request')\n url = _urljoin(base_url, path, False)\n\n if not query_params:\n query_params = {}\n\n decode = True\n if method == 'DELETE':\n decode = False\n\n result = salt.utils.http.query(\n url,\n method,\n params=query_params,\n data=data,\n header_dict=header_dict,\n decode=decode,\n decode_type='json',\n text=True,\n status=True,\n cookies=True,\n persist_session=True,\n opts=opts,\n )\n\n if result.get('status', None) == salt.ext.six.moves.http_client.OK:\n response = pushover_functions.get(function).get('response')\n if response in result and result[response] == 0:\n ret['res'] = False\n ret['message'] = result\n return ret\n else:\n try:\n if 'response' in result and result[response] == 0:\n ret['res'] = False\n ret['message'] = result\n except ValueError:\n ret['res'] = False\n ret['message'] = result\n return ret\n", "def validate_user(user,\n device,\n token):\n '''\n Send a message to a Pushover user or group.\n :param user: The user or group name, either will work.\n :param device: The device for the user.\n :param token: The PushOver token.\n '''\n res = {\n 'message': 'User key is invalid',\n 'result': False\n }\n\n parameters = dict()\n parameters['user'] = user\n parameters['token'] = token\n if device:\n parameters['device'] = device\n\n response = query(function='validate_user',\n method='POST',\n header_dict={'Content-Type': 'application/x-www-form-urlencoded'},\n data=_urlencode(parameters))\n\n if response['res']:\n if 'message' in response:\n _message = response.get('message', '')\n if 'status' in _message:\n if _message.get('dict', {}).get('status', None) == 1:\n res['result'] = True\n res['message'] = 'User key is valid.'\n else:\n res['result'] = False\n res['message'] = ''.join(_message.get('dict', {}).get('errors'))\n return res\n", "def validate_sound(sound,\n token):\n '''\n Send a message to a Pushover user or group.\n :param sound: The sound that we want to verify\n :param token: The PushOver token.\n '''\n ret = {\n 'message': 'Sound is invalid',\n 'res': False\n }\n parameters = dict()\n parameters['token'] = token\n\n response = query(function='validate_sound',\n method='GET',\n query_params=parameters)\n\n if response['res']:\n if 'message' in response:\n _message = response.get('message', '')\n if 'status' in _message:\n if _message.get('dict', {}).get('status', '') == 1:\n sounds = _message.get('dict', {}).get('sounds', '')\n if sound in sounds:\n ret['message'] = 'Valid sound {0}.'.format(sound)\n ret['res'] = True\n else:\n ret['message'] = 'Warning: {0} not a valid sound.'.format(sound)\n ret['res'] = False\n else:\n ret['message'] = ''.join(_message.get('dict', {}).get('errors'))\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Return salt data via pushover (http://www.pushover.net) .. versionadded:: 2016.3.0 The following fields can be set in the minion conf file:: pushover.user (required) pushover.token (required) pushover.title (optional) pushover.device (optional) pushover.priority (optional) pushover.expire (optional) pushover.retry (optional) pushover.profile (optional) Alternative configuration values can be used by prefacing the configuration. Any values not found in the alternative configuration will be pulled from the default location:: alternative.pushover.user alternative.pushover.token alternative.pushover.title alternative.pushover.device alternative.pushover.priority alternative.pushover.expire alternative.pushover.retry PushOver settings may also be configured as:: pushover: user: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx token: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx title: Salt Returner device: phone priority: -1 expire: 3600 retry: 5 alternative.pushover: user: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx token: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx title: Salt Returner device: phone priority: 1 expire: 4800 retry: 2 pushover_profile: pushover.token: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx pushover: user: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx profile: pushover_profile alternative.pushover: user: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx profile: pushover_profile To use the PushOver returner, append '--return pushover' to the salt command. ex: .. code-block:: bash salt '*' test.ping --return pushover To use the alternative configuration, append '--return_config alternative' to the salt command. ex: salt '*' test.ping --return pushover --return_config alternative To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command. .. code-block:: bash salt '*' test.ping --return pushover --return_kwargs '{"title": "Salt is awesome!"}' ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import pprint import logging # Import 3rd-party libs # pylint: disable=import-error,no-name-in-module,redefined-builtin from salt.ext.six.moves.urllib.parse import urlencode as _urlencode # pylint: enable=import-error,no-name-in-module,redefined-builtin # Import Salt Libs import salt.returners import salt.utils.pushover from salt.exceptions import SaltInvocationError log = logging.getLogger(__name__) __virtualname__ = 'pushover' def _get_options(ret=None): ''' Get the pushover options from salt. ''' defaults = {'priority': '0'} attrs = {'pushover_profile': 'profile', 'user': 'user', 'device': 'device', 'token': 'token', 'priority': 'priority', 'title': 'title', 'api_version': 'api_version', 'expire': 'expire', 'retry': 'retry', 'sound': 'sound', } profile_attr = 'pushover_profile' profile_attrs = {'user': 'user', 'device': 'device', 'token': 'token', 'priority': 'priority', 'title': 'title', 'api_version': 'api_version', 'expire': 'expire', 'retry': 'retry', 'sound': 'sound', } _options = salt.returners.get_returner_options(__virtualname__, ret, attrs, profile_attr=profile_attr, profile_attrs=profile_attrs, __salt__=__salt__, __opts__=__opts__, defaults=defaults) return _options def __virtual__(): ''' Return virtual name of the module. :return: The virtual name of the module. ''' return __virtualname__ def returner(ret): ''' Send an PushOver message with the data ''' _options = _get_options(ret) user = _options.get('user') device = _options.get('device') token = _options.get('token') title = _options.get('title') priority = _options.get('priority') expire = _options.get('expire') retry = _options.get('retry') sound = _options.get('sound') if not token: raise SaltInvocationError('Pushover token is unavailable.') if not user: raise SaltInvocationError('Pushover user key is unavailable.') if priority and priority == 2: if not expire and not retry: raise SaltInvocationError('Priority 2 requires pushover.expire and pushover.retry options.') message = ('id: {0}\r\n' 'function: {1}\r\n' 'function args: {2}\r\n' 'jid: {3}\r\n' 'return: {4}\r\n').format( ret.get('id'), ret.get('fun'), ret.get('fun_args'), ret.get('jid'), pprint.pformat(ret.get('return'))) result = _post_message(user=user, device=device, message=message, title=title, priority=priority, expire=expire, retry=retry, sound=sound, token=token) log.debug('pushover result %s', result) if not result['res']: log.info('Error: %s', result['message']) return
saltstack/salt
salt/returners/pushover_returner.py
returner
python
def returner(ret): ''' Send an PushOver message with the data ''' _options = _get_options(ret) user = _options.get('user') device = _options.get('device') token = _options.get('token') title = _options.get('title') priority = _options.get('priority') expire = _options.get('expire') retry = _options.get('retry') sound = _options.get('sound') if not token: raise SaltInvocationError('Pushover token is unavailable.') if not user: raise SaltInvocationError('Pushover user key is unavailable.') if priority and priority == 2: if not expire and not retry: raise SaltInvocationError('Priority 2 requires pushover.expire and pushover.retry options.') message = ('id: {0}\r\n' 'function: {1}\r\n' 'function args: {2}\r\n' 'jid: {3}\r\n' 'return: {4}\r\n').format( ret.get('id'), ret.get('fun'), ret.get('fun_args'), ret.get('jid'), pprint.pformat(ret.get('return'))) result = _post_message(user=user, device=device, message=message, title=title, priority=priority, expire=expire, retry=retry, sound=sound, token=token) log.debug('pushover result %s', result) if not result['res']: log.info('Error: %s', result['message']) return
Send an PushOver message with the data
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/pushover_returner.py#L201-L251
[ "def _get_options(ret=None):\n '''\n Get the pushover options from salt.\n '''\n\n defaults = {'priority': '0'}\n\n attrs = {'pushover_profile': 'profile',\n 'user': 'user',\n 'device': 'device',\n 'token': 'token',\n 'priority': 'priority',\n 'title': 'title',\n 'api_version': 'api_version',\n 'expire': 'expire',\n 'retry': 'retry',\n 'sound': 'sound',\n }\n\n profile_attr = 'pushover_profile'\n\n profile_attrs = {'user': 'user',\n 'device': 'device',\n 'token': 'token',\n 'priority': 'priority',\n 'title': 'title',\n 'api_version': 'api_version',\n 'expire': 'expire',\n 'retry': 'retry',\n 'sound': 'sound',\n }\n\n _options = salt.returners.get_returner_options(__virtualname__,\n ret,\n attrs,\n profile_attr=profile_attr,\n profile_attrs=profile_attrs,\n __salt__=__salt__,\n __opts__=__opts__,\n defaults=defaults)\n return _options\n", "def _post_message(user,\n device,\n message,\n title,\n priority,\n expire,\n retry,\n sound,\n api_version=1,\n token=None):\n '''\n Send a message to a Pushover user or group.\n :param user: The user or group to send to, must be key of user or group not email address.\n :param message: The message to send to the PushOver user or group.\n :param title: Specify who the message is from.\n :param priority The priority of the message, defaults to 0.\n :param api_version: The PushOver API version, if not specified in the configuration.\n :param notify: Whether to notify the room, default: False.\n :param token: The PushOver token, if not specified in the configuration.\n :return: Boolean if message was sent successfully.\n '''\n\n user_validate = salt.utils.pushover.validate_user(user, device, token)\n if not user_validate['result']:\n return user_validate\n\n parameters = dict()\n parameters['user'] = user\n parameters['device'] = device\n parameters['token'] = token\n parameters['title'] = title\n parameters['priority'] = priority\n parameters['expire'] = expire\n parameters['retry'] = retry\n parameters['message'] = message\n\n if sound:\n sound_validate = salt.utils.pushover.validate_sound(sound, token)\n if sound_validate['res']:\n parameters['sound'] = sound\n\n result = salt.utils.pushover.query(function='message',\n method='POST',\n header_dict={'Content-Type': 'application/x-www-form-urlencoded'},\n data=_urlencode(parameters),\n opts=__opts__)\n\n return result\n" ]
# -*- coding: utf-8 -*- ''' Return salt data via pushover (http://www.pushover.net) .. versionadded:: 2016.3.0 The following fields can be set in the minion conf file:: pushover.user (required) pushover.token (required) pushover.title (optional) pushover.device (optional) pushover.priority (optional) pushover.expire (optional) pushover.retry (optional) pushover.profile (optional) Alternative configuration values can be used by prefacing the configuration. Any values not found in the alternative configuration will be pulled from the default location:: alternative.pushover.user alternative.pushover.token alternative.pushover.title alternative.pushover.device alternative.pushover.priority alternative.pushover.expire alternative.pushover.retry PushOver settings may also be configured as:: pushover: user: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx token: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx title: Salt Returner device: phone priority: -1 expire: 3600 retry: 5 alternative.pushover: user: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx token: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx title: Salt Returner device: phone priority: 1 expire: 4800 retry: 2 pushover_profile: pushover.token: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx pushover: user: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx profile: pushover_profile alternative.pushover: user: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx profile: pushover_profile To use the PushOver returner, append '--return pushover' to the salt command. ex: .. code-block:: bash salt '*' test.ping --return pushover To use the alternative configuration, append '--return_config alternative' to the salt command. ex: salt '*' test.ping --return pushover --return_config alternative To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command. .. code-block:: bash salt '*' test.ping --return pushover --return_kwargs '{"title": "Salt is awesome!"}' ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import pprint import logging # Import 3rd-party libs # pylint: disable=import-error,no-name-in-module,redefined-builtin from salt.ext.six.moves.urllib.parse import urlencode as _urlencode # pylint: enable=import-error,no-name-in-module,redefined-builtin # Import Salt Libs import salt.returners import salt.utils.pushover from salt.exceptions import SaltInvocationError log = logging.getLogger(__name__) __virtualname__ = 'pushover' def _get_options(ret=None): ''' Get the pushover options from salt. ''' defaults = {'priority': '0'} attrs = {'pushover_profile': 'profile', 'user': 'user', 'device': 'device', 'token': 'token', 'priority': 'priority', 'title': 'title', 'api_version': 'api_version', 'expire': 'expire', 'retry': 'retry', 'sound': 'sound', } profile_attr = 'pushover_profile' profile_attrs = {'user': 'user', 'device': 'device', 'token': 'token', 'priority': 'priority', 'title': 'title', 'api_version': 'api_version', 'expire': 'expire', 'retry': 'retry', 'sound': 'sound', } _options = salt.returners.get_returner_options(__virtualname__, ret, attrs, profile_attr=profile_attr, profile_attrs=profile_attrs, __salt__=__salt__, __opts__=__opts__, defaults=defaults) return _options def __virtual__(): ''' Return virtual name of the module. :return: The virtual name of the module. ''' return __virtualname__ def _post_message(user, device, message, title, priority, expire, retry, sound, api_version=1, token=None): ''' Send a message to a Pushover user or group. :param user: The user or group to send to, must be key of user or group not email address. :param message: The message to send to the PushOver user or group. :param title: Specify who the message is from. :param priority The priority of the message, defaults to 0. :param api_version: The PushOver API version, if not specified in the configuration. :param notify: Whether to notify the room, default: False. :param token: The PushOver token, if not specified in the configuration. :return: Boolean if message was sent successfully. ''' user_validate = salt.utils.pushover.validate_user(user, device, token) if not user_validate['result']: return user_validate parameters = dict() parameters['user'] = user parameters['device'] = device parameters['token'] = token parameters['title'] = title parameters['priority'] = priority parameters['expire'] = expire parameters['retry'] = retry parameters['message'] = message if sound: sound_validate = salt.utils.pushover.validate_sound(sound, token) if sound_validate['res']: parameters['sound'] = sound result = salt.utils.pushover.query(function='message', method='POST', header_dict={'Content-Type': 'application/x-www-form-urlencoded'}, data=_urlencode(parameters), opts=__opts__) return result
saltstack/salt
salt/loader.py
_format_entrypoint_target
python
def _format_entrypoint_target(ep): ''' Makes a string describing the target of an EntryPoint object. Base strongly on EntryPoint.__str__(). ''' s = ep.module_name if ep.attrs: s += ':' + '.'.join(ep.attrs) return s
Makes a string describing the target of an EntryPoint object. Base strongly on EntryPoint.__str__().
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L147-L156
null
# -*- coding: utf-8 -*- ''' The Salt loader is the core to Salt's plugin system, the loader scans directories for python loadable code and organizes the code into the plugin interfaces used by Salt. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import sys import time import logging import inspect import tempfile import threading import functools import threading import traceback import types from zipimport import zipimporter # Import salt libs import salt.config import salt.defaults.events import salt.defaults.exitcodes import salt.syspaths import salt.utils.args import salt.utils.context import salt.utils.data import salt.utils.dictupdate import salt.utils.event import salt.utils.files import salt.utils.lazy import salt.utils.odict import salt.utils.platform import salt.utils.versions import salt.utils.stringutils from salt.exceptions import LoaderError from salt.template import check_render_pipe_str from salt.utils.decorators import Depends from salt.utils.thread_local_proxy import ThreadLocalProxy # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import reload_module if sys.version_info[:2] >= (3, 5): import importlib.machinery # pylint: disable=no-name-in-module,import-error import importlib.util # pylint: disable=no-name-in-module,import-error USE_IMPORTLIB = True else: import imp USE_IMPORTLIB = False try: from collections.abc import MutableMapping except ImportError: from collections import MutableMapping try: import pkg_resources HAS_PKG_RESOURCES = True except ImportError: HAS_PKG_RESOURCES = False log = logging.getLogger(__name__) SALT_BASE_PATH = os.path.abspath(salt.syspaths.INSTALL_DIR) LOADED_BASE_NAME = 'salt.loaded' if USE_IMPORTLIB: # pylint: disable=no-member MODULE_KIND_SOURCE = 1 MODULE_KIND_COMPILED = 2 MODULE_KIND_EXTENSION = 3 MODULE_KIND_PKG_DIRECTORY = 5 SUFFIXES = [] for suffix in importlib.machinery.EXTENSION_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_EXTENSION)) for suffix in importlib.machinery.SOURCE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_SOURCE)) for suffix in importlib.machinery.BYTECODE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_COMPILED)) MODULE_KIND_MAP = { MODULE_KIND_SOURCE: importlib.machinery.SourceFileLoader, MODULE_KIND_COMPILED: importlib.machinery.SourcelessFileLoader, MODULE_KIND_EXTENSION: importlib.machinery.ExtensionFileLoader } # pylint: enable=no-member else: SUFFIXES = imp.get_suffixes() PY3_PRE_EXT = \ re.compile(r'\.cpython-{0}{1}(\.opt-[1-9])?'.format(*sys.version_info[:2])) # Because on the cloud drivers we do `from salt.cloud.libcloudfuncs import *` # which simplifies code readability, it adds some unsupported functions into # the driver's module scope. # We list un-supported functions here. These will be removed from the loaded. # TODO: remove the need for this cross-module code. Maybe use NotImplemented LIBCLOUD_FUNCS_NOT_SUPPORTED = ( 'parallels.avail_sizes', 'parallels.avail_locations', 'proxmox.avail_sizes', ) # Will be set to pyximport module at runtime if cython is enabled in config. pyximport = None def static_loader( opts, ext_type, tag, pack=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, filter_name=None, ): funcs = LazyLoader( _module_dirs( opts, ext_type, tag, int_type, ext_dirs, ext_type_dirs, base_path, ), opts, tag=tag, pack=pack, ) ret = {} funcs._load_all() if filter_name: funcs = FilterDictWrapper(funcs, filter_name) for key in funcs: ret[key] = funcs[key] return ret def _module_dirs( opts, ext_type, tag=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, ): if tag is None: tag = ext_type sys_types = os.path.join(base_path or SALT_BASE_PATH, int_type or ext_type) ext_types = os.path.join(opts['extension_modules'], ext_type) ext_type_types = [] if ext_dirs: if ext_type_dirs is None: ext_type_dirs = '{0}_dirs'.format(tag) if ext_type_dirs in opts: ext_type_types.extend(opts[ext_type_dirs]) if HAS_PKG_RESOURCES and ext_type_dirs: for entry_point in pkg_resources.iter_entry_points('salt.loader', ext_type_dirs): try: loaded_entry_point = entry_point.load() for path in loaded_entry_point(): ext_type_types.append(path) except Exception as exc: log.error("Error getting module directories from %s: %s", _format_entrypoint_target(entry_point), exc) log.debug("Full backtrace for module directories error", exc_info=True) cli_module_dirs = [] # The dirs can be any module dir, or a in-tree _{ext_type} dir for _dir in opts.get('module_dirs', []): # Prepend to the list to match cli argument ordering maybe_dir = os.path.join(_dir, ext_type) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) continue maybe_dir = os.path.join(_dir, '_{0}'.format(ext_type)) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) return cli_module_dirs + ext_type_types + [ext_types, sys_types] def minion_mods( opts, context=None, utils=None, whitelist=None, initial_load=False, loaded_base_name=None, notify=False, static_modules=None, proxy=None): ''' Load execution modules Returns a dictionary of execution modules appropriate for the current system by evaluating the __virtual__() function in each module. :param dict opts: The Salt options dictionary :param dict context: A Salt context that should be made present inside generated modules in __context__ :param dict utils: Utility functions which should be made available to Salt modules in __utils__. See `utils_dirs` in salt.config for additional information about configuration. :param list whitelist: A list of modules which should be whitelisted. :param bool initial_load: Deprecated flag! Unused. :param str loaded_base_name: A string marker for the loaded base name. :param bool notify: Flag indicating that an event should be fired upon completion of module loading. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) __opts__['grains'] = __grains__ __utils__ = salt.loader.utils(__opts__) __salt__ = salt.loader.minion_mods(__opts__, utils=__utils__) __salt__['test.ping']() ''' # TODO Publish documentation for module whitelisting if not whitelist: whitelist = opts.get('whitelist_modules', None) ret = LazyLoader( _module_dirs(opts, 'modules', 'module'), opts, tag='module', pack={'__context__': context, '__utils__': utils, '__proxy__': proxy}, whitelist=whitelist, loaded_base_name=loaded_base_name, static_modules=static_modules, ) ret.pack['__salt__'] = ret # Load any provider overrides from the configuration file providers option # Note: Providers can be pkg, service, user or group - not to be confused # with cloud providers. providers = opts.get('providers', False) if providers and isinstance(providers, dict): for mod in providers: # sometimes providers opts is not to diverge modules but # for other configuration try: funcs = raw_mod(opts, providers[mod], ret) except TypeError: break else: if funcs: for func in funcs: f_key = '{0}{1}'.format(mod, func[func.rindex('.'):]) ret[f_key] = funcs[func] if notify: evt = salt.utils.event.get_event('minion', opts=opts, listen=False) evt.fire_event({'complete': True}, tag=salt.defaults.events.MINION_MOD_COMPLETE) return ret def raw_mod(opts, name, functions, mod='modules'): ''' Returns a single module loaded raw and bypassing the __virtual__ function .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') testmod = salt.loader.raw_mod(__opts__, 'test', None) testmod['test.ping']() ''' loader = LazyLoader( _module_dirs(opts, mod, 'module'), opts, tag='rawmodule', virtual_enable=False, pack={'__salt__': functions}, ) # if we don't have the module, return an empty dict if name not in loader.file_mapping: return {} loader._load_module(name) # load a single module (the one passed in) return dict(loader._dict) # return a copy of *just* the funcs for `name` def metaproxy(opts): ''' Return functions used in the meta proxy ''' return LazyLoader( _module_dirs(opts, 'metaproxy'), opts, tag='metaproxy' ) def matchers(opts): ''' Return the matcher services plugins ''' return LazyLoader( _module_dirs(opts, 'matchers'), opts, tag='matchers' ) def engines(opts, functions, runners, utils, proxy=None): ''' Return the master services plugins ''' pack = {'__salt__': functions, '__runners__': runners, '__proxy__': proxy, '__utils__': utils} return LazyLoader( _module_dirs(opts, 'engines'), opts, tag='engines', pack=pack, ) def proxy(opts, functions=None, returners=None, whitelist=None, utils=None): ''' Returns the proxy module for this salt-proxy-minion ''' ret = LazyLoader( _module_dirs(opts, 'proxy'), opts, tag='proxy', pack={'__salt__': functions, '__ret__': returners, '__utils__': utils}, ) ret.pack['__proxy__'] = ret return ret def returners(opts, functions, whitelist=None, context=None, proxy=None): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'returners', 'returner'), opts, tag='returner', whitelist=whitelist, pack={'__salt__': functions, '__context__': context, '__proxy__': proxy or {}}, ) def utils(opts, whitelist=None, context=None, proxy=proxy): ''' Returns the utility modules ''' return LazyLoader( _module_dirs(opts, 'utils', ext_type_dirs='utils_dirs'), opts, tag='utils', whitelist=whitelist, pack={'__context__': context, '__proxy__': proxy or {}}, ) def pillars(opts, functions, context=None): ''' Returns the pillars modules ''' ret = LazyLoader(_module_dirs(opts, 'pillar'), opts, tag='pillar', pack={'__salt__': functions, '__context__': context, '__utils__': utils(opts)}) ret.pack['__ext_pillar__'] = ret return FilterDictWrapper(ret, '.ext_pillar') def tops(opts): ''' Returns the tops modules ''' if 'master_tops' not in opts: return {} whitelist = list(opts['master_tops'].keys()) ret = LazyLoader( _module_dirs(opts, 'tops', 'top'), opts, tag='top', whitelist=whitelist, ) return FilterDictWrapper(ret, '.top') def wheels(opts, whitelist=None, context=None): ''' Returns the wheels modules ''' if context is None: context = {} return LazyLoader( _module_dirs(opts, 'wheel'), opts, tag='wheel', whitelist=whitelist, pack={'__context__': context}, ) def outputters(opts): ''' Returns the outputters modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only outputters present in the keyspace ''' ret = LazyLoader( _module_dirs(opts, 'output', ext_type_dirs='outputter_dirs'), opts, tag='output', ) wrapped_ret = FilterDictWrapper(ret, '.output') # TODO: this name seems terrible... __salt__ should always be execution mods ret.pack['__salt__'] = wrapped_ret return wrapped_ret def serializers(opts): ''' Returns the serializers modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only serializers present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'serializers'), opts, tag='serializers', ) def eauth_tokens(opts): ''' Returns the tokens modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only token backends present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'tokens'), opts, tag='tokens', ) def auth(opts, whitelist=None): ''' Returns the auth modules :param dict opts: The Salt options dictionary :returns: LazyLoader ''' return LazyLoader( _module_dirs(opts, 'auth'), opts, tag='auth', whitelist=whitelist, pack={'__salt__': minion_mods(opts)}, ) def fileserver(opts, backends): ''' Returns the file server modules ''' return LazyLoader(_module_dirs(opts, 'fileserver'), opts, tag='fileserver', whitelist=backends, pack={'__utils__': utils(opts)}) def roster(opts, runner=None, utils=None, whitelist=None): ''' Returns the roster modules ''' return LazyLoader( _module_dirs(opts, 'roster'), opts, tag='roster', whitelist=whitelist, pack={ '__runner__': runner, '__utils__': utils, }, ) def thorium(opts, functions, runners): ''' Load the thorium runtime modules ''' pack = {'__salt__': functions, '__runner__': runners, '__context__': {}} ret = LazyLoader(_module_dirs(opts, 'thorium'), opts, tag='thorium', pack=pack) ret.pack['__thorium__'] = ret return ret def states(opts, functions, utils, serializers, whitelist=None, proxy=None, context=None): ''' Returns the state modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') statemods = salt.loader.states(__opts__, None, None) ''' if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'states'), opts, tag='states', pack={'__salt__': functions, '__proxy__': proxy or {}}, whitelist=whitelist, ) ret.pack['__states__'] = ret ret.pack['__utils__'] = utils ret.pack['__serializers__'] = serializers ret.pack['__context__'] = context return ret def beacons(opts, functions, context=None, proxy=None): ''' Load the beacon modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. ''' return LazyLoader( _module_dirs(opts, 'beacons'), opts, tag='beacons', pack={'__context__': context, '__salt__': functions, '__proxy__': proxy or {}}, virtual_funcs=[], ) def log_handlers(opts): ''' Returns the custom logging handler modules :param dict opts: The Salt options dictionary ''' ret = LazyLoader( _module_dirs( opts, 'log_handlers', int_type='handlers', base_path=os.path.join(SALT_BASE_PATH, 'log'), ), opts, tag='log_handlers', ) return FilterDictWrapper(ret, '.setup_handlers') def ssh_wrapper(opts, functions=None, context=None): ''' Returns the custom logging handler modules ''' return LazyLoader( _module_dirs( opts, 'wrapper', base_path=os.path.join(SALT_BASE_PATH, os.path.join('client', 'ssh')), ), opts, tag='wrapper', pack={ '__salt__': functions, '__grains__': opts.get('grains', {}), '__pillar__': opts.get('pillar', {}), '__context__': context, }, ) def render(opts, functions, states=None, proxy=None, context=None): ''' Returns the render modules ''' if context is None: context = {} pack = {'__salt__': functions, '__grains__': opts.get('grains', {}), '__context__': context} if states: pack['__states__'] = states pack['__proxy__'] = proxy or {} ret = LazyLoader( _module_dirs( opts, 'renderers', 'render', ext_type_dirs='render_dirs', ), opts, tag='render', pack=pack, ) rend = FilterDictWrapper(ret, '.render') if not check_render_pipe_str(opts['renderer'], rend, opts['renderer_blacklist'], opts['renderer_whitelist']): err = ('The renderer {0} is unavailable, this error is often because ' 'the needed software is unavailable'.format(opts['renderer'])) log.critical(err) raise LoaderError(err) return rend def grain_funcs(opts, proxy=None): ''' Returns the grain functions .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') grainfuncs = salt.loader.grain_funcs(__opts__) ''' ret = LazyLoader( _module_dirs( opts, 'grains', 'grain', ext_type_dirs='grains_dirs', ), opts, tag='grains', ) ret.pack['__utils__'] = utils(opts, proxy=proxy) return ret def _load_cached_grains(opts, cfn): ''' Returns the grains cached in cfn, or None if the cache is too old or is corrupted. ''' if not os.path.isfile(cfn): log.debug('Grains cache file does not exist.') return None grains_cache_age = int(time.time() - os.path.getmtime(cfn)) if grains_cache_age > opts.get('grains_cache_expiration', 300): log.debug( 'Grains cache last modified %s seconds ago and cache ' 'expiration is set to %s. Grains cache expired. ' 'Refreshing.', grains_cache_age, opts.get('grains_cache_expiration', 300) ) return None if opts.get('refresh_grains_cache', False): log.debug('refresh_grains_cache requested, Refreshing.') return None log.debug('Retrieving grains from cache') try: serial = salt.payload.Serial(opts) with salt.utils.files.fopen(cfn, 'rb') as fp_: cached_grains = salt.utils.data.decode(serial.load(fp_), preserve_tuples=True) if not cached_grains: log.debug('Cached grains are empty, cache might be corrupted. Refreshing.') return None return cached_grains except (IOError, OSError): return None def grains(opts, force_refresh=False, proxy=None): ''' Return the functions for the dynamic grains and the values for the static grains. Since grains are computed early in the startup process, grains functions do not have __salt__ or __proxy__ available. At proxy-minion startup, this function is called with the proxymodule LazyLoader object so grains functions can communicate with their controlled device. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) print __grains__['id'] ''' # Need to re-import salt.config, somehow it got lost when a minion is starting import salt.config # if we have no grains, lets try loading from disk (TODO: move to decorator?) cfn = os.path.join( opts['cachedir'], 'grains.cache.p' ) if not force_refresh and opts.get('grains_cache', False): cached_grains = _load_cached_grains(opts, cfn) if cached_grains: return cached_grains else: log.debug('Grains refresh requested. Refreshing grains.') if opts.get('skip_grains', False): return {} grains_deep_merge = opts.get('grains_deep_merge', False) is True if 'conf_file' in opts: pre_opts = {} pre_opts.update(salt.config.load_config( opts['conf_file'], 'SALT_MINION_CONFIG', salt.config.DEFAULT_MINION_OPTS['conf_file'] )) default_include = pre_opts.get( 'default_include', opts['default_include'] ) include = pre_opts.get('include', []) pre_opts.update(salt.config.include_config( default_include, opts['conf_file'], verbose=False )) pre_opts.update(salt.config.include_config( include, opts['conf_file'], verbose=True )) if 'grains' in pre_opts: opts['grains'] = pre_opts['grains'] else: opts['grains'] = {} else: opts['grains'] = {} grains_data = {} blist = opts.get('grains_blacklist', []) funcs = grain_funcs(opts, proxy=proxy) if force_refresh: # if we refresh, lets reload grain modules funcs.clear() # Run core grains for key in funcs: if not key.startswith('core.'): continue log.trace('Loading %s grain', key) ret = funcs[key]() if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) # Run the rest of the grains for key in funcs: if key.startswith('core.') or key == '_errors': continue try: # Grains are loaded too early to take advantage of the injected # __proxy__ variable. Pass an instance of that LazyLoader # here instead to grains functions if the grains functions take # one parameter. Then the grains can have access to the # proxymodule for retrieving information from the connected # device. log.trace('Loading %s grain', key) parameters = salt.utils.args.get_function_argspec(funcs[key]).args kwargs = {} if 'proxy' in parameters: kwargs['proxy'] = proxy if 'grains' in parameters: kwargs['grains'] = grains_data ret = funcs[key](**kwargs) except Exception: if salt.utils.platform.is_proxy(): log.info('The following CRITICAL message may not be an error; the proxy may not be completely established yet.') log.critical( 'Failed to load grains defined in grain file %s in ' 'function %s, error:\n', key, funcs[key], exc_info=True ) continue if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) if opts.get('proxy_merge_grains_in_module', True) and proxy: try: proxytype = proxy.opts['proxy']['proxytype'] if proxytype + '.grains' in proxy: if proxytype + '.initialized' in proxy and proxy[proxytype + '.initialized'](): try: proxytype = proxy.opts['proxy']['proxytype'] ret = proxy[proxytype + '.grains']() if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) except Exception: log.critical('Failed to run proxy\'s grains function!', exc_info=True ) except KeyError: pass grains_data.update(opts['grains']) # Write cache if enabled if opts.get('grains_cache', False): with salt.utils.files.set_umask(0o077): try: if salt.utils.platform.is_windows(): # Late import import salt.modules.cmdmod # Make sure cache file isn't read-only salt.modules.cmdmod._run_quiet('attrib -R "{0}"'.format(cfn)) with salt.utils.files.fopen(cfn, 'w+b') as fp_: try: serial = salt.payload.Serial(opts) serial.dump(grains_data, fp_) except TypeError as e: log.error('Failed to serialize grains cache: %s', e) raise # re-throw for cleanup except Exception as e: log.error('Unable to write to grains cache file %s: %s', cfn, e) # Based on the original exception, the file may or may not have been # created. If it was, we will remove it now, as the exception means # the serialized data is not to be trusted, no matter what the # exception is. if os.path.isfile(cfn): os.unlink(cfn) if grains_deep_merge: salt.utils.dictupdate.update(grains_data, opts['grains']) else: grains_data.update(opts['grains']) return salt.utils.data.decode(grains_data, preserve_tuples=True) # TODO: get rid of? Does anyone use this? You should use raw() instead def call(fun, **kwargs): ''' Directly call a function inside a loader directory ''' args = kwargs.get('args', []) dirs = kwargs.get('dirs', []) funcs = LazyLoader( [os.path.join(SALT_BASE_PATH, 'modules')] + dirs, None, tag='modules', virtual_enable=False, ) return funcs[fun](*args) def runner(opts, utils=None, context=None, whitelist=None): ''' Directly call a function inside a loader directory ''' if utils is None: utils = {} if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'runners', 'runner', ext_type_dirs='runner_dirs'), opts, tag='runners', pack={'__utils__': utils, '__context__': context}, whitelist=whitelist, ) # TODO: change from __salt__ to something else, we overload __salt__ too much ret.pack['__salt__'] = ret return ret def queues(opts): ''' Directly call a function inside a loader directory ''' return LazyLoader( _module_dirs(opts, 'queues', 'queue', ext_type_dirs='queue_dirs'), opts, tag='queues', ) def sdb(opts, functions=None, whitelist=None, utils=None): ''' Make a very small database call ''' if utils is None: utils = {} return LazyLoader( _module_dirs(opts, 'sdb'), opts, tag='sdb', pack={ '__sdb__': functions, '__opts__': opts, '__utils__': utils, '__salt__': minion_mods(opts, utils), }, whitelist=whitelist, ) def pkgdb(opts): ''' Return modules for SPM's package database .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgdb', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgdb' ) def pkgfiles(opts): ''' Return modules for SPM's file handling .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgfiles', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgfiles' ) def clouds(opts): ''' Return the cloud functions ''' # Let's bring __active_provider_name__, defaulting to None, to all cloud # drivers. This will get temporarily updated/overridden with a context # manager when needed. functions = LazyLoader( _module_dirs(opts, 'clouds', 'cloud', base_path=os.path.join(SALT_BASE_PATH, 'cloud'), int_type='clouds'), opts, tag='clouds', pack={'__utils__': salt.loader.utils(opts), '__active_provider_name__': None}, ) for funcname in LIBCLOUD_FUNCS_NOT_SUPPORTED: log.trace( '\'%s\' has been marked as not supported. Removing from the ' 'list of supported cloud functions', funcname ) functions.pop(funcname, None) return functions def netapi(opts): ''' Return the network api functions ''' return LazyLoader( _module_dirs(opts, 'netapi'), opts, tag='netapi', ) def executors(opts, functions=None, context=None, proxy=None): ''' Returns the executor modules ''' executors = LazyLoader( _module_dirs(opts, 'executors', 'executor'), opts, tag='executor', pack={'__salt__': functions, '__context__': context or {}, '__proxy__': proxy or {}}, ) executors.pack['__executors__'] = executors return executors def cache(opts, serial): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'cache', 'cache'), opts, tag='cache', pack={'__opts__': opts, '__context__': {'serial': serial}}, ) def _generate_module(name): if name in sys.modules: return code = "'''Salt loaded {0} parent module'''".format(name.split('.')[-1]) # ModuleType can't accept a unicode type on PY2 module = types.ModuleType(str(name)) # future lint: disable=blacklisted-function exec(code, module.__dict__) sys.modules[name] = module def _mod_type(module_path): if module_path.startswith(SALT_BASE_PATH): return 'int' return 'ext' def _inject_into_mod(mod, name, value, force_lock=False): ''' Inject a variable into a module. This is used to inject "globals" like ``__salt__``, ``__pillar``, or ``grains``. Instead of injecting the value directly, a ``ThreadLocalProxy`` is created. If such a proxy is already present under the specified name, it is updated with the new value. This update only affects the current thread, so that the same name can refer to different values depending on the thread of execution. This is important for data that is not truly global. For example, pillar data might be dynamically overriden through function parameters and thus the actual values available in pillar might depend on the thread that is calling a module. mod: module object into which the value is going to be injected. name: name of the variable that is injected into the module. value: value that is injected into the variable. The value is not injected directly, but instead set as the new reference of the proxy that has been created for the variable. force_lock: whether the lock should be acquired before checking whether a proxy object for the specified name has already been injected into the module. If ``False`` (the default), this function checks for the module's variable without acquiring the lock and only acquires the lock if a new proxy has to be created and injected. ''' old_value = getattr(mod, name, None) # We use a double-checked locking scheme in order to avoid taking the lock # when a proxy object has already been injected. # In most programming languages, double-checked locking is considered # unsafe when used without explicit memory barriers because one might read # an uninitialized value. In CPython it is safe due to the global # interpreter lock (GIL). In Python implementations that do not have the # GIL, it could be unsafe, but at least Jython also guarantees that (for # Python objects) memory is not corrupted when writing and reading without # explicit synchronization # (http://www.jython.org/jythonbook/en/1.0/Concurrency.html). # Please note that in order to make this code safe in a runtime environment # that does not make this guarantees, it is not sufficient. The # ThreadLocalProxy must also be created with fallback_to_shared set to # False or a lock must be added to the ThreadLocalProxy. if force_lock: with _inject_into_mod.lock: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: setattr(mod, name, ThreadLocalProxy(value, True)) else: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: _inject_into_mod(mod, name, value, True) # Lock used when injecting globals. This is needed to avoid a race condition # when two threads try to load the same module concurrently. This must be # outside the loader because there might be more than one loader for the same # namespace. _inject_into_mod.lock = threading.RLock() # TODO: move somewhere else? class FilterDictWrapper(MutableMapping): ''' Create a dict which wraps another dict with a specific key suffix on get This is to replace "filter_load" ''' def __init__(self, d, suffix): self._dict = d self.suffix = suffix def __setitem__(self, key, val): self._dict[key] = val def __delitem__(self, key): del self._dict[key] def __getitem__(self, key): return self._dict[key + self.suffix] def __len__(self): return len(self._dict) def __iter__(self): for key in self._dict: if key.endswith(self.suffix): yield key.replace(self.suffix, '') class LazyLoader(salt.utils.lazy.LazyDict): ''' A pseduo-dictionary which has a set of keys which are the name of the module and function, delimited by a dot. When the value of the key is accessed, the function is then loaded from disk and into memory. .. note:: Iterating over keys will cause all modules to be loaded. :param list module_dirs: A list of directories on disk to search for modules :param dict opts: The salt options dictionary. :param str tag: The tag for the type of module to load :param func mod_type_check: A function which can be used to verify files :param dict pack: A dictionary of function to be packed into modules as they are loaded :param list whitelist: A list of modules to whitelist :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules. :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality. If not true, the module will not load. :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values are function references themselves which are loaded on-demand. # TODO: - move modules_max_memory into here - singletons (per tag) ''' mod_dict_class = salt.utils.odict.OrderedDict def __init__(self, module_dirs, opts=None, tag='module', loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, proxy=None, virtual_funcs=None, ): # pylint: disable=W0231 ''' In pack, if any of the values are None they will be replaced with an empty context-specific dict ''' self.inject_globals = {} self.pack = {} if pack is None else pack if opts is None: opts = {} threadsafety = not opts.get('multiprocessing') self.context_dict = salt.utils.context.ContextDict(threadsafe=threadsafety) self.opts = self.__prep_mod_opts(opts) self.module_dirs = module_dirs self.tag = tag self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME self.mod_type_check = mod_type_check or _mod_type if '__context__' not in self.pack: self.pack['__context__'] = None for k, v in six.iteritems(self.pack): if v is None: # if the value of a pack is None, lets make an empty dict value = self.context_dict.get(k, {}) if isinstance(value, ThreadLocalProxy): value = ThreadLocalProxy.unproxy(value) self.context_dict[k] = value self.pack[k] = salt.utils.context.NamespacedDictWrapper(self.context_dict, k) self.whitelist = whitelist self.virtual_enable = virtual_enable self.initial_load = True # names of modules that we don't have (errors, __virtual__, etc.) self.missing_modules = {} # mapping of name -> error self.loaded_modules = {} # mapping of module_name -> dict_of_functions self.loaded_files = set() # TODO: just remove them from file_mapping? self.static_modules = static_modules if static_modules else [] if virtual_funcs is None: virtual_funcs = [] self.virtual_funcs = virtual_funcs self.disabled = set( self.opts.get( 'disable_{0}{1}'.format( self.tag, '' if self.tag[-1] == 's' else 's' ), [] ) ) # A map of suffix to description for imp self.suffix_map = {} # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [''] for (suffix, mode, kind) in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) self._lock = threading.RLock() self._refresh_file_mapping() super(LazyLoader, self).__init__() # late init the lazy loader # create all of the import namespaces _generate_module('{0}.int'.format(self.loaded_base_name)) _generate_module('{0}.int.{1}'.format(self.loaded_base_name, tag)) _generate_module('{0}.ext'.format(self.loaded_base_name)) _generate_module('{0}.ext.{1}'.format(self.loaded_base_name, tag)) def __getitem__(self, item): ''' Override the __getitem__ in order to decorate the returned function if we need to last-minute inject globals ''' func = super(LazyLoader, self).__getitem__(item) if self.inject_globals: return global_injector_decorator(self.inject_globals)(func) else: return func def __getattr__(self, mod_name): ''' Allow for "direct" attribute access-- this allows jinja templates to access things like `salt.test.ping()` ''' if mod_name in ('__getstate__', '__setstate__'): return object.__getattribute__(self, mod_name) # if we have an attribute named that, lets return it. try: return object.__getattr__(self, mod_name) # pylint: disable=no-member except AttributeError: pass # otherwise we assume its jinja template access if mod_name not in self.loaded_modules and not self.loaded: for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and mod_name in self.loaded_modules: break if mod_name in self.loaded_modules: return self.loaded_modules[mod_name] else: raise AttributeError(mod_name) def missing_fun_string(self, function_name): ''' Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ''' mod_name = function_name.split('.')[0] if mod_name in self.loaded_modules: return '\'{0}\' is not available.'.format(function_name) else: try: reason = self.missing_modules[mod_name] except KeyError: return '\'{0}\' is not available.'.format(function_name) else: if reason is not None: return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason) else: return '\'{0}\' __virtual__ returned False'.format(mod_name) def _refresh_file_mapping(self): ''' refresh the mapping of the FS on disk ''' # map of suffix to description for imp if self.opts.get('cython_enable', True) is True: try: global pyximport pyximport = __import__('pyximport') # pylint: disable=import-error pyximport.install() # add to suffix_map so file_mapping will pick it up self.suffix_map['.pyx'] = tuple() except ImportError: log.info('Cython is enabled in the options but not present ' 'in the system path. Skipping Cython modules.') # Allow for zipimport of modules if self.opts.get('enable_zip_modules', True) is True: self.suffix_map['.zip'] = tuple() # allow for module dirs if USE_IMPORTLIB: self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY) else: self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY) # create mapping of filename (without suffix) to (path, suffix) # The files are added in order of priority, so order *must* be retained. self.file_mapping = salt.utils.odict.OrderedDict() opt_match = [] def _replace_pre_ext(obj): ''' Hack so we can get the optimization level that we replaced (if any) out of the re.sub call below. We use a list here because it is a persistent data structure that we will be able to access after re.sub is called. ''' opt_match.append(obj) return '' for mod_dir in self.module_dirs: try: # Make sure we have a sorted listdir in order to have # expectable override results files = sorted( x for x in os.listdir(mod_dir) if x != '__pycache__' ) except OSError: continue # Next mod_dir if six.PY3: try: pycache_files = [ os.path.join('__pycache__', x) for x in sorted(os.listdir(os.path.join(mod_dir, '__pycache__'))) ] except OSError: pass else: files.extend(pycache_files) for filename in files: try: dirname, basename = os.path.split(filename) if basename.startswith('_'): # skip private modules # log messages omitted for obviousness continue # Next filename f_noext, ext = os.path.splitext(basename) if six.PY3: f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext) try: opt_level = int( opt_match.pop().group(1).rsplit('-', 1)[-1] ) except (AttributeError, IndexError, ValueError): # No regex match or no optimization level matched opt_level = 0 try: opt_index = self.opts['optimization_order'].index(opt_level) except KeyError: log.trace( 'Disallowed optimization level %d for module ' 'name \'%s\', skipping. Add %d to the ' '\'optimization_order\' config option if you ' 'do not want to ignore this optimization ' 'level.', opt_level, f_noext, opt_level ) continue else: # Optimization level not reflected in filename on PY2 opt_index = 0 # make sure it is a suffix we support if ext not in self.suffix_map: continue # Next filename if f_noext in self.disabled: log.trace( 'Skipping %s, it is disabled by configuration', filename ) continue # Next filename fpath = os.path.join(mod_dir, filename) # if its a directory, lets allow us to load that if ext == '': # is there something __init__? subfiles = os.listdir(fpath) for suffix in self.suffix_order: if '' == suffix: continue # Next suffix (__init__ must have a suffix) init_file = '__init__{0}'.format(suffix) if init_file in subfiles: break else: continue # Next filename try: curr_ext = self.file_mapping[f_noext][1] curr_opt_index = self.file_mapping[f_noext][2] except KeyError: pass else: if '' in (curr_ext, ext) and curr_ext != ext: log.error( 'Module/package collision: \'%s\' and \'%s\'', fpath, self.file_mapping[f_noext][0] ) if six.PY3 and ext == '.pyc' and curr_ext == '.pyc': # Check the optimization level if opt_index >= curr_opt_index: # Module name match, but a higher-priority # optimization level was already matched, skipping. continue elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext): # Match found but a higher-priorty match already # exists, so skip this. continue if six.PY3 and not dirname and ext == '.pyc': # On Python 3, we should only load .pyc files from the # __pycache__ subdirectory (i.e. when dirname is not an # empty string). continue # Made it this far - add it self.file_mapping[f_noext] = (fpath, ext, opt_index) except OSError: continue for smod in self.static_modules: f_noext = smod.split('.')[-1] self.file_mapping[f_noext] = (smod, '.o', 0) def clear(self): ''' Clear the dict ''' with self._lock: super(LazyLoader, self).clear() # clear the lazy loader self.loaded_files = set() self.missing_modules = {} self.loaded_modules = {} # if we have been loaded before, lets clear the file mapping since # we obviously want a re-do if hasattr(self, 'opts'): self._refresh_file_mapping() self.initial_load = False def __prep_mod_opts(self, opts): ''' Strip out of the opts any logger instance ''' if '__grains__' not in self.pack: grains = opts.get('grains', {}) if isinstance(grains, ThreadLocalProxy): grains = ThreadLocalProxy.unproxy(grains) self.context_dict['grains'] = grains self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains') if '__pillar__' not in self.pack: pillar = opts.get('pillar', {}) if isinstance(pillar, ThreadLocalProxy): pillar = ThreadLocalProxy.unproxy(pillar) self.context_dict['pillar'] = pillar self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar') mod_opts = {} for key, val in list(opts.items()): if key == 'logger': continue mod_opts[key] = val return mod_opts def _iter_files(self, mod_name): ''' Iterate over all file_mapping files in order of closeness to mod_name ''' # do we have an exact match? if mod_name in self.file_mapping: yield mod_name # do we have a partial match? for k in self.file_mapping: if mod_name in k: yield k # anyone else? Bueller? for k in self.file_mapping: if mod_name not in k: yield k def _reload_submodules(self, mod): submodules = ( getattr(mod, sname) for sname in dir(mod) if isinstance(getattr(mod, sname), mod.__class__) ) # reload only custom "sub"modules for submodule in submodules: # it is a submodule if the name is in a namespace under mod if submodule.__name__.startswith(mod.__name__ + '.'): reload_module(submodule) self._reload_submodules(submodule) def _load_module(self, name): mod = None fpath, suffix = self.file_mapping[name][:2] self.loaded_files.add(name) fpath_dirname = os.path.dirname(fpath) try: sys.path.append(fpath_dirname) if suffix == '.pyx': mod = pyximport.load_module(name, fpath, tempfile.gettempdir()) elif suffix == '.o': top_mod = __import__(fpath, globals(), locals(), []) comps = fpath.split('.') if len(comps) < 2: mod = top_mod else: mod = top_mod for subname in comps[1:]: mod = getattr(mod, subname) elif suffix == '.zip': mod = zipimporter(fpath).load_module(name) else: desc = self.suffix_map[suffix] # if it is a directory, we don't open a file try: mod_namespace = '.'.join(( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name)) except TypeError: mod_namespace = '{0}.{1}.{2}.{3}'.format( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name) if suffix == '': if USE_IMPORTLIB: # pylint: disable=no-member # Package directory, look for __init__ loader_details = [ (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES), (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES), (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), ] file_finder = importlib.machinery.FileFinder( fpath_dirname, *loader_details ) spec = file_finder.find_spec(mod_namespace) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: mod = imp.load_module(mod_namespace, None, fpath, desc) # reload all submodules if necessary if not self.initial_load: self._reload_submodules(mod) else: if USE_IMPORTLIB: # pylint: disable=no-member loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath) spec = importlib.util.spec_from_file_location( mod_namespace, fpath, loader=loader ) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() #mod = importlib.util.module_from_spec(spec) #spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: with salt.utils.files.fopen(fpath, desc[1]) as fn_: mod = imp.load_module(mod_namespace, fn_, fpath, desc) except IOError: raise except ImportError as exc: if 'magic number' in six.text_type(exc): error_msg = 'Failed to import {0} {1}. Bad magic number. If migrating from Python2 to Python3, remove all .pyc files and try again.'.format(self.tag, name) log.warning(error_msg) self.missing_modules[name] = error_msg log.debug( 'Failed to import %s %s:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = exc return False except Exception as error: log.error( 'Failed to import %s %s, this is due most likely to a ' 'syntax error:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False except SystemExit as error: try: fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1] except Exception: pass else: tgt_fn = os.path.join('salt', 'utils', 'process.py') if fn_.endswith(tgt_fn) and '_handle_signals' in caller: # Race conditon, SIGTERM or SIGINT received while loader # was in process of loading a module. Call sys.exit to # ensure that the process is killed. sys.exit(salt.defaults.exitcodes.EX_OK) log.error( 'Failed to import %s %s as the module called exit()\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False finally: sys.path.remove(fpath_dirname) if hasattr(mod, '__opts__'): mod.__opts__.update(self.opts) else: mod.__opts__ = self.opts # pack whatever other globals we were asked to for p_name, p_value in six.iteritems(self.pack): _inject_into_mod(mod, p_name, p_value) module_name = mod.__name__.rsplit('.', 1)[-1] # Call a module's initialization method if it exists module_init = getattr(mod, '__init__', None) if inspect.isfunction(module_init): try: module_init(self.opts) except TypeError as e: log.error(e) except Exception: err_string = '__init__ failed' log.debug( 'Error loading %s.%s: %s', self.tag, module_name, err_string, exc_info=True ) self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False # if virtual modules are enabled, we need to look for the # __virtual__() function inside that module and run it. if self.virtual_enable: virtual_funcs_to_process = ['__virtual__'] + self.virtual_funcs for virtual_func in virtual_funcs_to_process: virtual_ret, module_name, virtual_err, virtual_aliases = \ self._process_virtual(mod, module_name, virtual_func) if virtual_err is not None: log.trace( 'Error loading %s.%s: %s', self.tag, module_name, virtual_err ) # if _process_virtual returned a non-True value then we are # supposed to not process this module if virtual_ret is not True and module_name not in self.missing_modules: # If a module has information about why it could not be loaded, record it self.missing_modules[module_name] = virtual_err self.missing_modules[name] = virtual_err return False else: virtual_aliases = () # If this is a proxy minion then MOST modules cannot work. Therefore, require that # any module that does work with salt-proxy-minion define __proxyenabled__ as a list # containing the names of the proxy types that the module supports. # # Render modules and state modules are OK though if 'proxy' in self.opts: if self.tag in ['grains', 'proxy']: if not hasattr(mod, '__proxyenabled__') or \ (self.opts['proxy']['proxytype'] not in mod.__proxyenabled__ and '*' not in mod.__proxyenabled__): err_string = 'not a proxy_minion enabled module' self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False if getattr(mod, '__load__', False) is not False: log.info( 'The functions from module \'%s\' are being loaded from the ' 'provided __load__ attribute', module_name ) # If we had another module by the same virtual name, we should put any # new functions under the existing dictionary. mod_names = [module_name] + list(virtual_aliases) mod_dict = dict(( (x, self.loaded_modules.get(x, self.mod_dict_class())) for x in mod_names )) for attr in getattr(mod, '__load__', dir(mod)): if attr.startswith('_') and attr != '__call__': # private functions are skipped, # except __call__ which is default entrance # for multi-function batch-like state syntax continue func = getattr(mod, attr) if not inspect.isfunction(func) and not isinstance(func, functools.partial): # Not a function!? Skip it!!! continue # Let's get the function name. # If the module has the __func_alias__ attribute, it must be a # dictionary mapping in the form of(key -> value): # <real-func-name> -> <desired-func-name> # # It default's of course to the found callable attribute name # if no alias is defined. funcname = getattr(mod, '__func_alias__', {}).get(attr, attr) for tgt_mod in mod_names: try: full_funcname = '.'.join((tgt_mod, funcname)) except TypeError: full_funcname = '{0}.{1}'.format(tgt_mod, funcname) # Save many references for lookups # Careful not to overwrite existing (higher priority) functions if full_funcname not in self._dict: self._dict[full_funcname] = func if funcname not in mod_dict[tgt_mod]: setattr(mod_dict[tgt_mod], funcname, func) mod_dict[tgt_mod][funcname] = func self._apply_outputter(func, mod) # enforce depends try: Depends.enforce_dependencies(self._dict, self.tag) except RuntimeError as exc: log.info( 'Depends.enforce_dependencies() failed for the following ' 'reason: %s', exc ) for tgt_mod in mod_names: self.loaded_modules[tgt_mod] = mod_dict[tgt_mod] return True def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise KeyError('The key \'{0}\' should contain a \'.\''.format(key)) mod_name, _ = key.split('.', 1) with self._lock: # It is possible that the key is in the dictionary after # acquiring the lock due to another thread loading it. if mod_name in self.missing_modules or key in self._dict: return True # if the modulename isn't in the whitelist, don't bother if self.whitelist and mod_name not in self.whitelist: log.error( 'Failed to load function %s because its module (%s) is ' 'not in the whitelist: %s', key, mod_name, self.whitelist ) raise KeyError(key) def _inner_load(mod_name): for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and key in self._dict: return True return False # try to load the module ret = None reloaded = False # re-scan up to once, IOErrors or a failed load cause re-scans of the # filesystem while True: try: ret = _inner_load(mod_name) if not reloaded and ret is not True: self._refresh_file_mapping() reloaded = True continue break except IOError: if not reloaded: self._refresh_file_mapping() reloaded = True continue return ret def _load_all(self): ''' Load all of them ''' with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True def reload_modules(self): with self._lock: self.loaded_files = set() self._load_all() def _apply_outputter(self, func, mod): ''' Apply the __outputter__ variable to the functions ''' if hasattr(mod, '__outputter__'): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__] def _process_virtual(self, mod, module_name, virtual_func='__virtual__'): ''' Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1] ''' # The __virtual__ function will return either a True or False value. # If it returns a True value it can also set a module level attribute # named __virtualname__ with the name that the module should be # referred to as. # # This allows us to have things like the pkg module working on all # platforms under the name 'pkg'. It also allows for modules like # augeas_cfg to be referred to as 'augeas', which would otherwise have # namespace collisions. And finally it allows modules to return False # if they are not intended to run on the given platform or are missing # dependencies. virtual_aliases = getattr(mod, '__virtual_aliases__', tuple()) try: error_reason = None if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__): try: start = time.time() virtual = getattr(mod, virtual_func)() if isinstance(virtual, tuple): error_reason = virtual[1] virtual = virtual[0] if self.opts.get('virtual_timer', False): end = time.time() - start msg = 'Virtual function took {0} seconds for {1}'.format( end, module_name) log.warning(msg) except Exception as exc: error_reason = ( 'Exception raised when processing __virtual__ function' ' for {0}. Module will not be loaded: {1}'.format( mod.__name__, exc)) log.error(error_reason, exc_info_on_loglevel=logging.DEBUG) virtual = None # Get the module's virtual name virtualname = getattr(mod, '__virtualname__', virtual) if not virtual: # if __virtual__() evaluates to False then the module # wasn't meant for this platform or it's not supposed to # load for some other reason. # Some modules might accidentally return None and are # improperly loaded if virtual is None: log.warning( '%s.__virtual__() is wrongly returning `None`. ' 'It should either return `True`, `False` or a new ' 'name. If you\'re the developer of the module ' '\'%s\', please fix this.', mod.__name__, module_name ) return (False, module_name, error_reason, virtual_aliases) # At this point, __virtual__ did not return a # boolean value, let's check for deprecated usage # or module renames if virtual is not True and module_name != virtual: # The module is renaming itself. Updating the module name # with the new name log.trace('Loaded %s as virtual %s', module_name, virtual) if virtualname != virtual: # The __virtualname__ attribute does not match what's # being returned by the __virtual__() function. This # should be considered an error. log.error( 'The module \'%s\' is showing some bad usage. Its ' '__virtualname__ attribute is set to \'%s\' yet the ' '__virtual__() function is returning \'%s\'. These ' 'values should match!', mod.__name__, virtualname, virtual ) module_name = virtualname # If the __virtual__ function returns True and __virtualname__ # is set then use it elif virtual is True and virtualname != module_name: if virtualname is not True: module_name = virtualname except KeyError: # Key errors come out of the virtual function when passing # in incomplete grains sets, these can be safely ignored # and logged to debug, still, it includes the traceback to # help debugging. log.debug('KeyError when loading %s', module_name, exc_info=True) except Exception: # If the module throws an exception during __virtual__() # then log the information and continue to the next. log.error( 'Failed to read the virtual function for %s: %s', self.tag, module_name, exc_info=True ) return (False, module_name, error_reason, virtual_aliases) return (True, module_name, None, virtual_aliases) def global_injector_decorator(inject_globals): ''' Decorator used by the LazyLoader to inject globals into a function at execute time. globals Dictionary with global variables to inject ''' def inner_decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): with salt.utils.context.func_globals_inject(f, **inject_globals): return f(*args, **kwargs) return wrapper return inner_decorator
saltstack/salt
salt/loader.py
minion_mods
python
def minion_mods( opts, context=None, utils=None, whitelist=None, initial_load=False, loaded_base_name=None, notify=False, static_modules=None, proxy=None): ''' Load execution modules Returns a dictionary of execution modules appropriate for the current system by evaluating the __virtual__() function in each module. :param dict opts: The Salt options dictionary :param dict context: A Salt context that should be made present inside generated modules in __context__ :param dict utils: Utility functions which should be made available to Salt modules in __utils__. See `utils_dirs` in salt.config for additional information about configuration. :param list whitelist: A list of modules which should be whitelisted. :param bool initial_load: Deprecated flag! Unused. :param str loaded_base_name: A string marker for the loaded base name. :param bool notify: Flag indicating that an event should be fired upon completion of module loading. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) __opts__['grains'] = __grains__ __utils__ = salt.loader.utils(__opts__) __salt__ = salt.loader.minion_mods(__opts__, utils=__utils__) __salt__['test.ping']() ''' # TODO Publish documentation for module whitelisting if not whitelist: whitelist = opts.get('whitelist_modules', None) ret = LazyLoader( _module_dirs(opts, 'modules', 'module'), opts, tag='module', pack={'__context__': context, '__utils__': utils, '__proxy__': proxy}, whitelist=whitelist, loaded_base_name=loaded_base_name, static_modules=static_modules, ) ret.pack['__salt__'] = ret # Load any provider overrides from the configuration file providers option # Note: Providers can be pkg, service, user or group - not to be confused # with cloud providers. providers = opts.get('providers', False) if providers and isinstance(providers, dict): for mod in providers: # sometimes providers opts is not to diverge modules but # for other configuration try: funcs = raw_mod(opts, providers[mod], ret) except TypeError: break else: if funcs: for func in funcs: f_key = '{0}{1}'.format(mod, func[func.rindex('.'):]) ret[f_key] = funcs[func] if notify: evt = salt.utils.event.get_event('minion', opts=opts, listen=False) evt.fire_event({'complete': True}, tag=salt.defaults.events.MINION_MOD_COMPLETE) return ret
Load execution modules Returns a dictionary of execution modules appropriate for the current system by evaluating the __virtual__() function in each module. :param dict opts: The Salt options dictionary :param dict context: A Salt context that should be made present inside generated modules in __context__ :param dict utils: Utility functions which should be made available to Salt modules in __utils__. See `utils_dirs` in salt.config for additional information about configuration. :param list whitelist: A list of modules which should be whitelisted. :param bool initial_load: Deprecated flag! Unused. :param str loaded_base_name: A string marker for the loaded base name. :param bool notify: Flag indicating that an event should be fired upon completion of module loading. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) __opts__['grains'] = __grains__ __utils__ = salt.loader.utils(__opts__) __salt__ = salt.loader.minion_mods(__opts__, utils=__utils__) __salt__['test.ping']()
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L205-L287
[ "def get_event(\n node, sock_dir=None, transport='zeromq',\n opts=None, listen=True, io_loop=None, keep_loop=False, raise_errors=False):\n '''\n Return an event object suitable for the named transport\n\n :param IOLoop io_loop: Pass in an io_loop if you want asynchronous\n operation for obtaining events. Eg use of\n set_event_handler() API. Otherwise, operation\n will be synchronous.\n '''\n sock_dir = sock_dir or opts['sock_dir']\n # TODO: AIO core is separate from transport\n if node == 'master':\n return MasterEvent(sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n return SaltEvent(node,\n sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n", "def fire_event(self, data, tag, timeout=1000):\n '''\n Send a single event into the publisher with payload dict \"data\" and\n event identifier \"tag\"\n\n The default is 1000 ms\n '''\n if not six.text_type(tag): # no empty tags allowed\n raise ValueError('Empty tag.')\n\n if not isinstance(data, MutableMapping): # data must be dict\n raise ValueError(\n 'Dict object expected, not \\'{0}\\'.'.format(data)\n )\n\n if not self.cpush:\n if timeout is not None:\n timeout_s = float(timeout) / 1000\n else:\n timeout_s = None\n if not self.connect_pull(timeout=timeout_s):\n return False\n\n data['_stamp'] = datetime.datetime.utcnow().isoformat()\n\n tagend = TAGEND\n if six.PY2:\n dump_data = self.serial.dumps(data)\n else:\n # Since the pack / unpack logic here is for local events only,\n # it is safe to change the wire protocol. The mechanism\n # that sends events from minion to master is outside this\n # file.\n dump_data = self.serial.dumps(data, use_bin_type=True)\n\n serialized_data = salt.utils.dicttrim.trim_dict(\n dump_data,\n self.opts['max_event_size'],\n is_msgpacked=True,\n use_bin_type=six.PY3\n )\n log.debug('Sending event: tag = %s; data = %s', tag, data)\n event = b''.join([\n salt.utils.stringutils.to_bytes(tag),\n salt.utils.stringutils.to_bytes(tagend),\n serialized_data])\n msg = salt.utils.stringutils.to_bytes(event, 'utf-8')\n if self._run_io_loop_sync:\n with salt.utils.asynchronous.current_ioloop(self.io_loop):\n try:\n self.io_loop.run_sync(lambda: self.pusher.send(msg))\n except Exception as ex:\n log.debug(ex)\n raise\n else:\n self.io_loop.spawn_callback(self.pusher.send, msg)\n return True\n" ]
# -*- coding: utf-8 -*- ''' The Salt loader is the core to Salt's plugin system, the loader scans directories for python loadable code and organizes the code into the plugin interfaces used by Salt. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import sys import time import logging import inspect import tempfile import threading import functools import threading import traceback import types from zipimport import zipimporter # Import salt libs import salt.config import salt.defaults.events import salt.defaults.exitcodes import salt.syspaths import salt.utils.args import salt.utils.context import salt.utils.data import salt.utils.dictupdate import salt.utils.event import salt.utils.files import salt.utils.lazy import salt.utils.odict import salt.utils.platform import salt.utils.versions import salt.utils.stringutils from salt.exceptions import LoaderError from salt.template import check_render_pipe_str from salt.utils.decorators import Depends from salt.utils.thread_local_proxy import ThreadLocalProxy # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import reload_module if sys.version_info[:2] >= (3, 5): import importlib.machinery # pylint: disable=no-name-in-module,import-error import importlib.util # pylint: disable=no-name-in-module,import-error USE_IMPORTLIB = True else: import imp USE_IMPORTLIB = False try: from collections.abc import MutableMapping except ImportError: from collections import MutableMapping try: import pkg_resources HAS_PKG_RESOURCES = True except ImportError: HAS_PKG_RESOURCES = False log = logging.getLogger(__name__) SALT_BASE_PATH = os.path.abspath(salt.syspaths.INSTALL_DIR) LOADED_BASE_NAME = 'salt.loaded' if USE_IMPORTLIB: # pylint: disable=no-member MODULE_KIND_SOURCE = 1 MODULE_KIND_COMPILED = 2 MODULE_KIND_EXTENSION = 3 MODULE_KIND_PKG_DIRECTORY = 5 SUFFIXES = [] for suffix in importlib.machinery.EXTENSION_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_EXTENSION)) for suffix in importlib.machinery.SOURCE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_SOURCE)) for suffix in importlib.machinery.BYTECODE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_COMPILED)) MODULE_KIND_MAP = { MODULE_KIND_SOURCE: importlib.machinery.SourceFileLoader, MODULE_KIND_COMPILED: importlib.machinery.SourcelessFileLoader, MODULE_KIND_EXTENSION: importlib.machinery.ExtensionFileLoader } # pylint: enable=no-member else: SUFFIXES = imp.get_suffixes() PY3_PRE_EXT = \ re.compile(r'\.cpython-{0}{1}(\.opt-[1-9])?'.format(*sys.version_info[:2])) # Because on the cloud drivers we do `from salt.cloud.libcloudfuncs import *` # which simplifies code readability, it adds some unsupported functions into # the driver's module scope. # We list un-supported functions here. These will be removed from the loaded. # TODO: remove the need for this cross-module code. Maybe use NotImplemented LIBCLOUD_FUNCS_NOT_SUPPORTED = ( 'parallels.avail_sizes', 'parallels.avail_locations', 'proxmox.avail_sizes', ) # Will be set to pyximport module at runtime if cython is enabled in config. pyximport = None def static_loader( opts, ext_type, tag, pack=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, filter_name=None, ): funcs = LazyLoader( _module_dirs( opts, ext_type, tag, int_type, ext_dirs, ext_type_dirs, base_path, ), opts, tag=tag, pack=pack, ) ret = {} funcs._load_all() if filter_name: funcs = FilterDictWrapper(funcs, filter_name) for key in funcs: ret[key] = funcs[key] return ret def _format_entrypoint_target(ep): ''' Makes a string describing the target of an EntryPoint object. Base strongly on EntryPoint.__str__(). ''' s = ep.module_name if ep.attrs: s += ':' + '.'.join(ep.attrs) return s def _module_dirs( opts, ext_type, tag=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, ): if tag is None: tag = ext_type sys_types = os.path.join(base_path or SALT_BASE_PATH, int_type or ext_type) ext_types = os.path.join(opts['extension_modules'], ext_type) ext_type_types = [] if ext_dirs: if ext_type_dirs is None: ext_type_dirs = '{0}_dirs'.format(tag) if ext_type_dirs in opts: ext_type_types.extend(opts[ext_type_dirs]) if HAS_PKG_RESOURCES and ext_type_dirs: for entry_point in pkg_resources.iter_entry_points('salt.loader', ext_type_dirs): try: loaded_entry_point = entry_point.load() for path in loaded_entry_point(): ext_type_types.append(path) except Exception as exc: log.error("Error getting module directories from %s: %s", _format_entrypoint_target(entry_point), exc) log.debug("Full backtrace for module directories error", exc_info=True) cli_module_dirs = [] # The dirs can be any module dir, or a in-tree _{ext_type} dir for _dir in opts.get('module_dirs', []): # Prepend to the list to match cli argument ordering maybe_dir = os.path.join(_dir, ext_type) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) continue maybe_dir = os.path.join(_dir, '_{0}'.format(ext_type)) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) return cli_module_dirs + ext_type_types + [ext_types, sys_types] def raw_mod(opts, name, functions, mod='modules'): ''' Returns a single module loaded raw and bypassing the __virtual__ function .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') testmod = salt.loader.raw_mod(__opts__, 'test', None) testmod['test.ping']() ''' loader = LazyLoader( _module_dirs(opts, mod, 'module'), opts, tag='rawmodule', virtual_enable=False, pack={'__salt__': functions}, ) # if we don't have the module, return an empty dict if name not in loader.file_mapping: return {} loader._load_module(name) # load a single module (the one passed in) return dict(loader._dict) # return a copy of *just* the funcs for `name` def metaproxy(opts): ''' Return functions used in the meta proxy ''' return LazyLoader( _module_dirs(opts, 'metaproxy'), opts, tag='metaproxy' ) def matchers(opts): ''' Return the matcher services plugins ''' return LazyLoader( _module_dirs(opts, 'matchers'), opts, tag='matchers' ) def engines(opts, functions, runners, utils, proxy=None): ''' Return the master services plugins ''' pack = {'__salt__': functions, '__runners__': runners, '__proxy__': proxy, '__utils__': utils} return LazyLoader( _module_dirs(opts, 'engines'), opts, tag='engines', pack=pack, ) def proxy(opts, functions=None, returners=None, whitelist=None, utils=None): ''' Returns the proxy module for this salt-proxy-minion ''' ret = LazyLoader( _module_dirs(opts, 'proxy'), opts, tag='proxy', pack={'__salt__': functions, '__ret__': returners, '__utils__': utils}, ) ret.pack['__proxy__'] = ret return ret def returners(opts, functions, whitelist=None, context=None, proxy=None): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'returners', 'returner'), opts, tag='returner', whitelist=whitelist, pack={'__salt__': functions, '__context__': context, '__proxy__': proxy or {}}, ) def utils(opts, whitelist=None, context=None, proxy=proxy): ''' Returns the utility modules ''' return LazyLoader( _module_dirs(opts, 'utils', ext_type_dirs='utils_dirs'), opts, tag='utils', whitelist=whitelist, pack={'__context__': context, '__proxy__': proxy or {}}, ) def pillars(opts, functions, context=None): ''' Returns the pillars modules ''' ret = LazyLoader(_module_dirs(opts, 'pillar'), opts, tag='pillar', pack={'__salt__': functions, '__context__': context, '__utils__': utils(opts)}) ret.pack['__ext_pillar__'] = ret return FilterDictWrapper(ret, '.ext_pillar') def tops(opts): ''' Returns the tops modules ''' if 'master_tops' not in opts: return {} whitelist = list(opts['master_tops'].keys()) ret = LazyLoader( _module_dirs(opts, 'tops', 'top'), opts, tag='top', whitelist=whitelist, ) return FilterDictWrapper(ret, '.top') def wheels(opts, whitelist=None, context=None): ''' Returns the wheels modules ''' if context is None: context = {} return LazyLoader( _module_dirs(opts, 'wheel'), opts, tag='wheel', whitelist=whitelist, pack={'__context__': context}, ) def outputters(opts): ''' Returns the outputters modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only outputters present in the keyspace ''' ret = LazyLoader( _module_dirs(opts, 'output', ext_type_dirs='outputter_dirs'), opts, tag='output', ) wrapped_ret = FilterDictWrapper(ret, '.output') # TODO: this name seems terrible... __salt__ should always be execution mods ret.pack['__salt__'] = wrapped_ret return wrapped_ret def serializers(opts): ''' Returns the serializers modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only serializers present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'serializers'), opts, tag='serializers', ) def eauth_tokens(opts): ''' Returns the tokens modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only token backends present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'tokens'), opts, tag='tokens', ) def auth(opts, whitelist=None): ''' Returns the auth modules :param dict opts: The Salt options dictionary :returns: LazyLoader ''' return LazyLoader( _module_dirs(opts, 'auth'), opts, tag='auth', whitelist=whitelist, pack={'__salt__': minion_mods(opts)}, ) def fileserver(opts, backends): ''' Returns the file server modules ''' return LazyLoader(_module_dirs(opts, 'fileserver'), opts, tag='fileserver', whitelist=backends, pack={'__utils__': utils(opts)}) def roster(opts, runner=None, utils=None, whitelist=None): ''' Returns the roster modules ''' return LazyLoader( _module_dirs(opts, 'roster'), opts, tag='roster', whitelist=whitelist, pack={ '__runner__': runner, '__utils__': utils, }, ) def thorium(opts, functions, runners): ''' Load the thorium runtime modules ''' pack = {'__salt__': functions, '__runner__': runners, '__context__': {}} ret = LazyLoader(_module_dirs(opts, 'thorium'), opts, tag='thorium', pack=pack) ret.pack['__thorium__'] = ret return ret def states(opts, functions, utils, serializers, whitelist=None, proxy=None, context=None): ''' Returns the state modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') statemods = salt.loader.states(__opts__, None, None) ''' if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'states'), opts, tag='states', pack={'__salt__': functions, '__proxy__': proxy or {}}, whitelist=whitelist, ) ret.pack['__states__'] = ret ret.pack['__utils__'] = utils ret.pack['__serializers__'] = serializers ret.pack['__context__'] = context return ret def beacons(opts, functions, context=None, proxy=None): ''' Load the beacon modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. ''' return LazyLoader( _module_dirs(opts, 'beacons'), opts, tag='beacons', pack={'__context__': context, '__salt__': functions, '__proxy__': proxy or {}}, virtual_funcs=[], ) def log_handlers(opts): ''' Returns the custom logging handler modules :param dict opts: The Salt options dictionary ''' ret = LazyLoader( _module_dirs( opts, 'log_handlers', int_type='handlers', base_path=os.path.join(SALT_BASE_PATH, 'log'), ), opts, tag='log_handlers', ) return FilterDictWrapper(ret, '.setup_handlers') def ssh_wrapper(opts, functions=None, context=None): ''' Returns the custom logging handler modules ''' return LazyLoader( _module_dirs( opts, 'wrapper', base_path=os.path.join(SALT_BASE_PATH, os.path.join('client', 'ssh')), ), opts, tag='wrapper', pack={ '__salt__': functions, '__grains__': opts.get('grains', {}), '__pillar__': opts.get('pillar', {}), '__context__': context, }, ) def render(opts, functions, states=None, proxy=None, context=None): ''' Returns the render modules ''' if context is None: context = {} pack = {'__salt__': functions, '__grains__': opts.get('grains', {}), '__context__': context} if states: pack['__states__'] = states pack['__proxy__'] = proxy or {} ret = LazyLoader( _module_dirs( opts, 'renderers', 'render', ext_type_dirs='render_dirs', ), opts, tag='render', pack=pack, ) rend = FilterDictWrapper(ret, '.render') if not check_render_pipe_str(opts['renderer'], rend, opts['renderer_blacklist'], opts['renderer_whitelist']): err = ('The renderer {0} is unavailable, this error is often because ' 'the needed software is unavailable'.format(opts['renderer'])) log.critical(err) raise LoaderError(err) return rend def grain_funcs(opts, proxy=None): ''' Returns the grain functions .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') grainfuncs = salt.loader.grain_funcs(__opts__) ''' ret = LazyLoader( _module_dirs( opts, 'grains', 'grain', ext_type_dirs='grains_dirs', ), opts, tag='grains', ) ret.pack['__utils__'] = utils(opts, proxy=proxy) return ret def _load_cached_grains(opts, cfn): ''' Returns the grains cached in cfn, or None if the cache is too old or is corrupted. ''' if not os.path.isfile(cfn): log.debug('Grains cache file does not exist.') return None grains_cache_age = int(time.time() - os.path.getmtime(cfn)) if grains_cache_age > opts.get('grains_cache_expiration', 300): log.debug( 'Grains cache last modified %s seconds ago and cache ' 'expiration is set to %s. Grains cache expired. ' 'Refreshing.', grains_cache_age, opts.get('grains_cache_expiration', 300) ) return None if opts.get('refresh_grains_cache', False): log.debug('refresh_grains_cache requested, Refreshing.') return None log.debug('Retrieving grains from cache') try: serial = salt.payload.Serial(opts) with salt.utils.files.fopen(cfn, 'rb') as fp_: cached_grains = salt.utils.data.decode(serial.load(fp_), preserve_tuples=True) if not cached_grains: log.debug('Cached grains are empty, cache might be corrupted. Refreshing.') return None return cached_grains except (IOError, OSError): return None def grains(opts, force_refresh=False, proxy=None): ''' Return the functions for the dynamic grains and the values for the static grains. Since grains are computed early in the startup process, grains functions do not have __salt__ or __proxy__ available. At proxy-minion startup, this function is called with the proxymodule LazyLoader object so grains functions can communicate with their controlled device. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) print __grains__['id'] ''' # Need to re-import salt.config, somehow it got lost when a minion is starting import salt.config # if we have no grains, lets try loading from disk (TODO: move to decorator?) cfn = os.path.join( opts['cachedir'], 'grains.cache.p' ) if not force_refresh and opts.get('grains_cache', False): cached_grains = _load_cached_grains(opts, cfn) if cached_grains: return cached_grains else: log.debug('Grains refresh requested. Refreshing grains.') if opts.get('skip_grains', False): return {} grains_deep_merge = opts.get('grains_deep_merge', False) is True if 'conf_file' in opts: pre_opts = {} pre_opts.update(salt.config.load_config( opts['conf_file'], 'SALT_MINION_CONFIG', salt.config.DEFAULT_MINION_OPTS['conf_file'] )) default_include = pre_opts.get( 'default_include', opts['default_include'] ) include = pre_opts.get('include', []) pre_opts.update(salt.config.include_config( default_include, opts['conf_file'], verbose=False )) pre_opts.update(salt.config.include_config( include, opts['conf_file'], verbose=True )) if 'grains' in pre_opts: opts['grains'] = pre_opts['grains'] else: opts['grains'] = {} else: opts['grains'] = {} grains_data = {} blist = opts.get('grains_blacklist', []) funcs = grain_funcs(opts, proxy=proxy) if force_refresh: # if we refresh, lets reload grain modules funcs.clear() # Run core grains for key in funcs: if not key.startswith('core.'): continue log.trace('Loading %s grain', key) ret = funcs[key]() if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) # Run the rest of the grains for key in funcs: if key.startswith('core.') or key == '_errors': continue try: # Grains are loaded too early to take advantage of the injected # __proxy__ variable. Pass an instance of that LazyLoader # here instead to grains functions if the grains functions take # one parameter. Then the grains can have access to the # proxymodule for retrieving information from the connected # device. log.trace('Loading %s grain', key) parameters = salt.utils.args.get_function_argspec(funcs[key]).args kwargs = {} if 'proxy' in parameters: kwargs['proxy'] = proxy if 'grains' in parameters: kwargs['grains'] = grains_data ret = funcs[key](**kwargs) except Exception: if salt.utils.platform.is_proxy(): log.info('The following CRITICAL message may not be an error; the proxy may not be completely established yet.') log.critical( 'Failed to load grains defined in grain file %s in ' 'function %s, error:\n', key, funcs[key], exc_info=True ) continue if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) if opts.get('proxy_merge_grains_in_module', True) and proxy: try: proxytype = proxy.opts['proxy']['proxytype'] if proxytype + '.grains' in proxy: if proxytype + '.initialized' in proxy and proxy[proxytype + '.initialized'](): try: proxytype = proxy.opts['proxy']['proxytype'] ret = proxy[proxytype + '.grains']() if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) except Exception: log.critical('Failed to run proxy\'s grains function!', exc_info=True ) except KeyError: pass grains_data.update(opts['grains']) # Write cache if enabled if opts.get('grains_cache', False): with salt.utils.files.set_umask(0o077): try: if salt.utils.platform.is_windows(): # Late import import salt.modules.cmdmod # Make sure cache file isn't read-only salt.modules.cmdmod._run_quiet('attrib -R "{0}"'.format(cfn)) with salt.utils.files.fopen(cfn, 'w+b') as fp_: try: serial = salt.payload.Serial(opts) serial.dump(grains_data, fp_) except TypeError as e: log.error('Failed to serialize grains cache: %s', e) raise # re-throw for cleanup except Exception as e: log.error('Unable to write to grains cache file %s: %s', cfn, e) # Based on the original exception, the file may or may not have been # created. If it was, we will remove it now, as the exception means # the serialized data is not to be trusted, no matter what the # exception is. if os.path.isfile(cfn): os.unlink(cfn) if grains_deep_merge: salt.utils.dictupdate.update(grains_data, opts['grains']) else: grains_data.update(opts['grains']) return salt.utils.data.decode(grains_data, preserve_tuples=True) # TODO: get rid of? Does anyone use this? You should use raw() instead def call(fun, **kwargs): ''' Directly call a function inside a loader directory ''' args = kwargs.get('args', []) dirs = kwargs.get('dirs', []) funcs = LazyLoader( [os.path.join(SALT_BASE_PATH, 'modules')] + dirs, None, tag='modules', virtual_enable=False, ) return funcs[fun](*args) def runner(opts, utils=None, context=None, whitelist=None): ''' Directly call a function inside a loader directory ''' if utils is None: utils = {} if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'runners', 'runner', ext_type_dirs='runner_dirs'), opts, tag='runners', pack={'__utils__': utils, '__context__': context}, whitelist=whitelist, ) # TODO: change from __salt__ to something else, we overload __salt__ too much ret.pack['__salt__'] = ret return ret def queues(opts): ''' Directly call a function inside a loader directory ''' return LazyLoader( _module_dirs(opts, 'queues', 'queue', ext_type_dirs='queue_dirs'), opts, tag='queues', ) def sdb(opts, functions=None, whitelist=None, utils=None): ''' Make a very small database call ''' if utils is None: utils = {} return LazyLoader( _module_dirs(opts, 'sdb'), opts, tag='sdb', pack={ '__sdb__': functions, '__opts__': opts, '__utils__': utils, '__salt__': minion_mods(opts, utils), }, whitelist=whitelist, ) def pkgdb(opts): ''' Return modules for SPM's package database .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgdb', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgdb' ) def pkgfiles(opts): ''' Return modules for SPM's file handling .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgfiles', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgfiles' ) def clouds(opts): ''' Return the cloud functions ''' # Let's bring __active_provider_name__, defaulting to None, to all cloud # drivers. This will get temporarily updated/overridden with a context # manager when needed. functions = LazyLoader( _module_dirs(opts, 'clouds', 'cloud', base_path=os.path.join(SALT_BASE_PATH, 'cloud'), int_type='clouds'), opts, tag='clouds', pack={'__utils__': salt.loader.utils(opts), '__active_provider_name__': None}, ) for funcname in LIBCLOUD_FUNCS_NOT_SUPPORTED: log.trace( '\'%s\' has been marked as not supported. Removing from the ' 'list of supported cloud functions', funcname ) functions.pop(funcname, None) return functions def netapi(opts): ''' Return the network api functions ''' return LazyLoader( _module_dirs(opts, 'netapi'), opts, tag='netapi', ) def executors(opts, functions=None, context=None, proxy=None): ''' Returns the executor modules ''' executors = LazyLoader( _module_dirs(opts, 'executors', 'executor'), opts, tag='executor', pack={'__salt__': functions, '__context__': context or {}, '__proxy__': proxy or {}}, ) executors.pack['__executors__'] = executors return executors def cache(opts, serial): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'cache', 'cache'), opts, tag='cache', pack={'__opts__': opts, '__context__': {'serial': serial}}, ) def _generate_module(name): if name in sys.modules: return code = "'''Salt loaded {0} parent module'''".format(name.split('.')[-1]) # ModuleType can't accept a unicode type on PY2 module = types.ModuleType(str(name)) # future lint: disable=blacklisted-function exec(code, module.__dict__) sys.modules[name] = module def _mod_type(module_path): if module_path.startswith(SALT_BASE_PATH): return 'int' return 'ext' def _inject_into_mod(mod, name, value, force_lock=False): ''' Inject a variable into a module. This is used to inject "globals" like ``__salt__``, ``__pillar``, or ``grains``. Instead of injecting the value directly, a ``ThreadLocalProxy`` is created. If such a proxy is already present under the specified name, it is updated with the new value. This update only affects the current thread, so that the same name can refer to different values depending on the thread of execution. This is important for data that is not truly global. For example, pillar data might be dynamically overriden through function parameters and thus the actual values available in pillar might depend on the thread that is calling a module. mod: module object into which the value is going to be injected. name: name of the variable that is injected into the module. value: value that is injected into the variable. The value is not injected directly, but instead set as the new reference of the proxy that has been created for the variable. force_lock: whether the lock should be acquired before checking whether a proxy object for the specified name has already been injected into the module. If ``False`` (the default), this function checks for the module's variable without acquiring the lock and only acquires the lock if a new proxy has to be created and injected. ''' old_value = getattr(mod, name, None) # We use a double-checked locking scheme in order to avoid taking the lock # when a proxy object has already been injected. # In most programming languages, double-checked locking is considered # unsafe when used without explicit memory barriers because one might read # an uninitialized value. In CPython it is safe due to the global # interpreter lock (GIL). In Python implementations that do not have the # GIL, it could be unsafe, but at least Jython also guarantees that (for # Python objects) memory is not corrupted when writing and reading without # explicit synchronization # (http://www.jython.org/jythonbook/en/1.0/Concurrency.html). # Please note that in order to make this code safe in a runtime environment # that does not make this guarantees, it is not sufficient. The # ThreadLocalProxy must also be created with fallback_to_shared set to # False or a lock must be added to the ThreadLocalProxy. if force_lock: with _inject_into_mod.lock: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: setattr(mod, name, ThreadLocalProxy(value, True)) else: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: _inject_into_mod(mod, name, value, True) # Lock used when injecting globals. This is needed to avoid a race condition # when two threads try to load the same module concurrently. This must be # outside the loader because there might be more than one loader for the same # namespace. _inject_into_mod.lock = threading.RLock() # TODO: move somewhere else? class FilterDictWrapper(MutableMapping): ''' Create a dict which wraps another dict with a specific key suffix on get This is to replace "filter_load" ''' def __init__(self, d, suffix): self._dict = d self.suffix = suffix def __setitem__(self, key, val): self._dict[key] = val def __delitem__(self, key): del self._dict[key] def __getitem__(self, key): return self._dict[key + self.suffix] def __len__(self): return len(self._dict) def __iter__(self): for key in self._dict: if key.endswith(self.suffix): yield key.replace(self.suffix, '') class LazyLoader(salt.utils.lazy.LazyDict): ''' A pseduo-dictionary which has a set of keys which are the name of the module and function, delimited by a dot. When the value of the key is accessed, the function is then loaded from disk and into memory. .. note:: Iterating over keys will cause all modules to be loaded. :param list module_dirs: A list of directories on disk to search for modules :param dict opts: The salt options dictionary. :param str tag: The tag for the type of module to load :param func mod_type_check: A function which can be used to verify files :param dict pack: A dictionary of function to be packed into modules as they are loaded :param list whitelist: A list of modules to whitelist :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules. :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality. If not true, the module will not load. :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values are function references themselves which are loaded on-demand. # TODO: - move modules_max_memory into here - singletons (per tag) ''' mod_dict_class = salt.utils.odict.OrderedDict def __init__(self, module_dirs, opts=None, tag='module', loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, proxy=None, virtual_funcs=None, ): # pylint: disable=W0231 ''' In pack, if any of the values are None they will be replaced with an empty context-specific dict ''' self.inject_globals = {} self.pack = {} if pack is None else pack if opts is None: opts = {} threadsafety = not opts.get('multiprocessing') self.context_dict = salt.utils.context.ContextDict(threadsafe=threadsafety) self.opts = self.__prep_mod_opts(opts) self.module_dirs = module_dirs self.tag = tag self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME self.mod_type_check = mod_type_check or _mod_type if '__context__' not in self.pack: self.pack['__context__'] = None for k, v in six.iteritems(self.pack): if v is None: # if the value of a pack is None, lets make an empty dict value = self.context_dict.get(k, {}) if isinstance(value, ThreadLocalProxy): value = ThreadLocalProxy.unproxy(value) self.context_dict[k] = value self.pack[k] = salt.utils.context.NamespacedDictWrapper(self.context_dict, k) self.whitelist = whitelist self.virtual_enable = virtual_enable self.initial_load = True # names of modules that we don't have (errors, __virtual__, etc.) self.missing_modules = {} # mapping of name -> error self.loaded_modules = {} # mapping of module_name -> dict_of_functions self.loaded_files = set() # TODO: just remove them from file_mapping? self.static_modules = static_modules if static_modules else [] if virtual_funcs is None: virtual_funcs = [] self.virtual_funcs = virtual_funcs self.disabled = set( self.opts.get( 'disable_{0}{1}'.format( self.tag, '' if self.tag[-1] == 's' else 's' ), [] ) ) # A map of suffix to description for imp self.suffix_map = {} # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [''] for (suffix, mode, kind) in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) self._lock = threading.RLock() self._refresh_file_mapping() super(LazyLoader, self).__init__() # late init the lazy loader # create all of the import namespaces _generate_module('{0}.int'.format(self.loaded_base_name)) _generate_module('{0}.int.{1}'.format(self.loaded_base_name, tag)) _generate_module('{0}.ext'.format(self.loaded_base_name)) _generate_module('{0}.ext.{1}'.format(self.loaded_base_name, tag)) def __getitem__(self, item): ''' Override the __getitem__ in order to decorate the returned function if we need to last-minute inject globals ''' func = super(LazyLoader, self).__getitem__(item) if self.inject_globals: return global_injector_decorator(self.inject_globals)(func) else: return func def __getattr__(self, mod_name): ''' Allow for "direct" attribute access-- this allows jinja templates to access things like `salt.test.ping()` ''' if mod_name in ('__getstate__', '__setstate__'): return object.__getattribute__(self, mod_name) # if we have an attribute named that, lets return it. try: return object.__getattr__(self, mod_name) # pylint: disable=no-member except AttributeError: pass # otherwise we assume its jinja template access if mod_name not in self.loaded_modules and not self.loaded: for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and mod_name in self.loaded_modules: break if mod_name in self.loaded_modules: return self.loaded_modules[mod_name] else: raise AttributeError(mod_name) def missing_fun_string(self, function_name): ''' Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ''' mod_name = function_name.split('.')[0] if mod_name in self.loaded_modules: return '\'{0}\' is not available.'.format(function_name) else: try: reason = self.missing_modules[mod_name] except KeyError: return '\'{0}\' is not available.'.format(function_name) else: if reason is not None: return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason) else: return '\'{0}\' __virtual__ returned False'.format(mod_name) def _refresh_file_mapping(self): ''' refresh the mapping of the FS on disk ''' # map of suffix to description for imp if self.opts.get('cython_enable', True) is True: try: global pyximport pyximport = __import__('pyximport') # pylint: disable=import-error pyximport.install() # add to suffix_map so file_mapping will pick it up self.suffix_map['.pyx'] = tuple() except ImportError: log.info('Cython is enabled in the options but not present ' 'in the system path. Skipping Cython modules.') # Allow for zipimport of modules if self.opts.get('enable_zip_modules', True) is True: self.suffix_map['.zip'] = tuple() # allow for module dirs if USE_IMPORTLIB: self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY) else: self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY) # create mapping of filename (without suffix) to (path, suffix) # The files are added in order of priority, so order *must* be retained. self.file_mapping = salt.utils.odict.OrderedDict() opt_match = [] def _replace_pre_ext(obj): ''' Hack so we can get the optimization level that we replaced (if any) out of the re.sub call below. We use a list here because it is a persistent data structure that we will be able to access after re.sub is called. ''' opt_match.append(obj) return '' for mod_dir in self.module_dirs: try: # Make sure we have a sorted listdir in order to have # expectable override results files = sorted( x for x in os.listdir(mod_dir) if x != '__pycache__' ) except OSError: continue # Next mod_dir if six.PY3: try: pycache_files = [ os.path.join('__pycache__', x) for x in sorted(os.listdir(os.path.join(mod_dir, '__pycache__'))) ] except OSError: pass else: files.extend(pycache_files) for filename in files: try: dirname, basename = os.path.split(filename) if basename.startswith('_'): # skip private modules # log messages omitted for obviousness continue # Next filename f_noext, ext = os.path.splitext(basename) if six.PY3: f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext) try: opt_level = int( opt_match.pop().group(1).rsplit('-', 1)[-1] ) except (AttributeError, IndexError, ValueError): # No regex match or no optimization level matched opt_level = 0 try: opt_index = self.opts['optimization_order'].index(opt_level) except KeyError: log.trace( 'Disallowed optimization level %d for module ' 'name \'%s\', skipping. Add %d to the ' '\'optimization_order\' config option if you ' 'do not want to ignore this optimization ' 'level.', opt_level, f_noext, opt_level ) continue else: # Optimization level not reflected in filename on PY2 opt_index = 0 # make sure it is a suffix we support if ext not in self.suffix_map: continue # Next filename if f_noext in self.disabled: log.trace( 'Skipping %s, it is disabled by configuration', filename ) continue # Next filename fpath = os.path.join(mod_dir, filename) # if its a directory, lets allow us to load that if ext == '': # is there something __init__? subfiles = os.listdir(fpath) for suffix in self.suffix_order: if '' == suffix: continue # Next suffix (__init__ must have a suffix) init_file = '__init__{0}'.format(suffix) if init_file in subfiles: break else: continue # Next filename try: curr_ext = self.file_mapping[f_noext][1] curr_opt_index = self.file_mapping[f_noext][2] except KeyError: pass else: if '' in (curr_ext, ext) and curr_ext != ext: log.error( 'Module/package collision: \'%s\' and \'%s\'', fpath, self.file_mapping[f_noext][0] ) if six.PY3 and ext == '.pyc' and curr_ext == '.pyc': # Check the optimization level if opt_index >= curr_opt_index: # Module name match, but a higher-priority # optimization level was already matched, skipping. continue elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext): # Match found but a higher-priorty match already # exists, so skip this. continue if six.PY3 and not dirname and ext == '.pyc': # On Python 3, we should only load .pyc files from the # __pycache__ subdirectory (i.e. when dirname is not an # empty string). continue # Made it this far - add it self.file_mapping[f_noext] = (fpath, ext, opt_index) except OSError: continue for smod in self.static_modules: f_noext = smod.split('.')[-1] self.file_mapping[f_noext] = (smod, '.o', 0) def clear(self): ''' Clear the dict ''' with self._lock: super(LazyLoader, self).clear() # clear the lazy loader self.loaded_files = set() self.missing_modules = {} self.loaded_modules = {} # if we have been loaded before, lets clear the file mapping since # we obviously want a re-do if hasattr(self, 'opts'): self._refresh_file_mapping() self.initial_load = False def __prep_mod_opts(self, opts): ''' Strip out of the opts any logger instance ''' if '__grains__' not in self.pack: grains = opts.get('grains', {}) if isinstance(grains, ThreadLocalProxy): grains = ThreadLocalProxy.unproxy(grains) self.context_dict['grains'] = grains self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains') if '__pillar__' not in self.pack: pillar = opts.get('pillar', {}) if isinstance(pillar, ThreadLocalProxy): pillar = ThreadLocalProxy.unproxy(pillar) self.context_dict['pillar'] = pillar self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar') mod_opts = {} for key, val in list(opts.items()): if key == 'logger': continue mod_opts[key] = val return mod_opts def _iter_files(self, mod_name): ''' Iterate over all file_mapping files in order of closeness to mod_name ''' # do we have an exact match? if mod_name in self.file_mapping: yield mod_name # do we have a partial match? for k in self.file_mapping: if mod_name in k: yield k # anyone else? Bueller? for k in self.file_mapping: if mod_name not in k: yield k def _reload_submodules(self, mod): submodules = ( getattr(mod, sname) for sname in dir(mod) if isinstance(getattr(mod, sname), mod.__class__) ) # reload only custom "sub"modules for submodule in submodules: # it is a submodule if the name is in a namespace under mod if submodule.__name__.startswith(mod.__name__ + '.'): reload_module(submodule) self._reload_submodules(submodule) def _load_module(self, name): mod = None fpath, suffix = self.file_mapping[name][:2] self.loaded_files.add(name) fpath_dirname = os.path.dirname(fpath) try: sys.path.append(fpath_dirname) if suffix == '.pyx': mod = pyximport.load_module(name, fpath, tempfile.gettempdir()) elif suffix == '.o': top_mod = __import__(fpath, globals(), locals(), []) comps = fpath.split('.') if len(comps) < 2: mod = top_mod else: mod = top_mod for subname in comps[1:]: mod = getattr(mod, subname) elif suffix == '.zip': mod = zipimporter(fpath).load_module(name) else: desc = self.suffix_map[suffix] # if it is a directory, we don't open a file try: mod_namespace = '.'.join(( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name)) except TypeError: mod_namespace = '{0}.{1}.{2}.{3}'.format( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name) if suffix == '': if USE_IMPORTLIB: # pylint: disable=no-member # Package directory, look for __init__ loader_details = [ (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES), (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES), (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), ] file_finder = importlib.machinery.FileFinder( fpath_dirname, *loader_details ) spec = file_finder.find_spec(mod_namespace) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: mod = imp.load_module(mod_namespace, None, fpath, desc) # reload all submodules if necessary if not self.initial_load: self._reload_submodules(mod) else: if USE_IMPORTLIB: # pylint: disable=no-member loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath) spec = importlib.util.spec_from_file_location( mod_namespace, fpath, loader=loader ) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() #mod = importlib.util.module_from_spec(spec) #spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: with salt.utils.files.fopen(fpath, desc[1]) as fn_: mod = imp.load_module(mod_namespace, fn_, fpath, desc) except IOError: raise except ImportError as exc: if 'magic number' in six.text_type(exc): error_msg = 'Failed to import {0} {1}. Bad magic number. If migrating from Python2 to Python3, remove all .pyc files and try again.'.format(self.tag, name) log.warning(error_msg) self.missing_modules[name] = error_msg log.debug( 'Failed to import %s %s:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = exc return False except Exception as error: log.error( 'Failed to import %s %s, this is due most likely to a ' 'syntax error:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False except SystemExit as error: try: fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1] except Exception: pass else: tgt_fn = os.path.join('salt', 'utils', 'process.py') if fn_.endswith(tgt_fn) and '_handle_signals' in caller: # Race conditon, SIGTERM or SIGINT received while loader # was in process of loading a module. Call sys.exit to # ensure that the process is killed. sys.exit(salt.defaults.exitcodes.EX_OK) log.error( 'Failed to import %s %s as the module called exit()\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False finally: sys.path.remove(fpath_dirname) if hasattr(mod, '__opts__'): mod.__opts__.update(self.opts) else: mod.__opts__ = self.opts # pack whatever other globals we were asked to for p_name, p_value in six.iteritems(self.pack): _inject_into_mod(mod, p_name, p_value) module_name = mod.__name__.rsplit('.', 1)[-1] # Call a module's initialization method if it exists module_init = getattr(mod, '__init__', None) if inspect.isfunction(module_init): try: module_init(self.opts) except TypeError as e: log.error(e) except Exception: err_string = '__init__ failed' log.debug( 'Error loading %s.%s: %s', self.tag, module_name, err_string, exc_info=True ) self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False # if virtual modules are enabled, we need to look for the # __virtual__() function inside that module and run it. if self.virtual_enable: virtual_funcs_to_process = ['__virtual__'] + self.virtual_funcs for virtual_func in virtual_funcs_to_process: virtual_ret, module_name, virtual_err, virtual_aliases = \ self._process_virtual(mod, module_name, virtual_func) if virtual_err is not None: log.trace( 'Error loading %s.%s: %s', self.tag, module_name, virtual_err ) # if _process_virtual returned a non-True value then we are # supposed to not process this module if virtual_ret is not True and module_name not in self.missing_modules: # If a module has information about why it could not be loaded, record it self.missing_modules[module_name] = virtual_err self.missing_modules[name] = virtual_err return False else: virtual_aliases = () # If this is a proxy minion then MOST modules cannot work. Therefore, require that # any module that does work with salt-proxy-minion define __proxyenabled__ as a list # containing the names of the proxy types that the module supports. # # Render modules and state modules are OK though if 'proxy' in self.opts: if self.tag in ['grains', 'proxy']: if not hasattr(mod, '__proxyenabled__') or \ (self.opts['proxy']['proxytype'] not in mod.__proxyenabled__ and '*' not in mod.__proxyenabled__): err_string = 'not a proxy_minion enabled module' self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False if getattr(mod, '__load__', False) is not False: log.info( 'The functions from module \'%s\' are being loaded from the ' 'provided __load__ attribute', module_name ) # If we had another module by the same virtual name, we should put any # new functions under the existing dictionary. mod_names = [module_name] + list(virtual_aliases) mod_dict = dict(( (x, self.loaded_modules.get(x, self.mod_dict_class())) for x in mod_names )) for attr in getattr(mod, '__load__', dir(mod)): if attr.startswith('_') and attr != '__call__': # private functions are skipped, # except __call__ which is default entrance # for multi-function batch-like state syntax continue func = getattr(mod, attr) if not inspect.isfunction(func) and not isinstance(func, functools.partial): # Not a function!? Skip it!!! continue # Let's get the function name. # If the module has the __func_alias__ attribute, it must be a # dictionary mapping in the form of(key -> value): # <real-func-name> -> <desired-func-name> # # It default's of course to the found callable attribute name # if no alias is defined. funcname = getattr(mod, '__func_alias__', {}).get(attr, attr) for tgt_mod in mod_names: try: full_funcname = '.'.join((tgt_mod, funcname)) except TypeError: full_funcname = '{0}.{1}'.format(tgt_mod, funcname) # Save many references for lookups # Careful not to overwrite existing (higher priority) functions if full_funcname not in self._dict: self._dict[full_funcname] = func if funcname not in mod_dict[tgt_mod]: setattr(mod_dict[tgt_mod], funcname, func) mod_dict[tgt_mod][funcname] = func self._apply_outputter(func, mod) # enforce depends try: Depends.enforce_dependencies(self._dict, self.tag) except RuntimeError as exc: log.info( 'Depends.enforce_dependencies() failed for the following ' 'reason: %s', exc ) for tgt_mod in mod_names: self.loaded_modules[tgt_mod] = mod_dict[tgt_mod] return True def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise KeyError('The key \'{0}\' should contain a \'.\''.format(key)) mod_name, _ = key.split('.', 1) with self._lock: # It is possible that the key is in the dictionary after # acquiring the lock due to another thread loading it. if mod_name in self.missing_modules or key in self._dict: return True # if the modulename isn't in the whitelist, don't bother if self.whitelist and mod_name not in self.whitelist: log.error( 'Failed to load function %s because its module (%s) is ' 'not in the whitelist: %s', key, mod_name, self.whitelist ) raise KeyError(key) def _inner_load(mod_name): for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and key in self._dict: return True return False # try to load the module ret = None reloaded = False # re-scan up to once, IOErrors or a failed load cause re-scans of the # filesystem while True: try: ret = _inner_load(mod_name) if not reloaded and ret is not True: self._refresh_file_mapping() reloaded = True continue break except IOError: if not reloaded: self._refresh_file_mapping() reloaded = True continue return ret def _load_all(self): ''' Load all of them ''' with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True def reload_modules(self): with self._lock: self.loaded_files = set() self._load_all() def _apply_outputter(self, func, mod): ''' Apply the __outputter__ variable to the functions ''' if hasattr(mod, '__outputter__'): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__] def _process_virtual(self, mod, module_name, virtual_func='__virtual__'): ''' Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1] ''' # The __virtual__ function will return either a True or False value. # If it returns a True value it can also set a module level attribute # named __virtualname__ with the name that the module should be # referred to as. # # This allows us to have things like the pkg module working on all # platforms under the name 'pkg'. It also allows for modules like # augeas_cfg to be referred to as 'augeas', which would otherwise have # namespace collisions. And finally it allows modules to return False # if they are not intended to run on the given platform or are missing # dependencies. virtual_aliases = getattr(mod, '__virtual_aliases__', tuple()) try: error_reason = None if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__): try: start = time.time() virtual = getattr(mod, virtual_func)() if isinstance(virtual, tuple): error_reason = virtual[1] virtual = virtual[0] if self.opts.get('virtual_timer', False): end = time.time() - start msg = 'Virtual function took {0} seconds for {1}'.format( end, module_name) log.warning(msg) except Exception as exc: error_reason = ( 'Exception raised when processing __virtual__ function' ' for {0}. Module will not be loaded: {1}'.format( mod.__name__, exc)) log.error(error_reason, exc_info_on_loglevel=logging.DEBUG) virtual = None # Get the module's virtual name virtualname = getattr(mod, '__virtualname__', virtual) if not virtual: # if __virtual__() evaluates to False then the module # wasn't meant for this platform or it's not supposed to # load for some other reason. # Some modules might accidentally return None and are # improperly loaded if virtual is None: log.warning( '%s.__virtual__() is wrongly returning `None`. ' 'It should either return `True`, `False` or a new ' 'name. If you\'re the developer of the module ' '\'%s\', please fix this.', mod.__name__, module_name ) return (False, module_name, error_reason, virtual_aliases) # At this point, __virtual__ did not return a # boolean value, let's check for deprecated usage # or module renames if virtual is not True and module_name != virtual: # The module is renaming itself. Updating the module name # with the new name log.trace('Loaded %s as virtual %s', module_name, virtual) if virtualname != virtual: # The __virtualname__ attribute does not match what's # being returned by the __virtual__() function. This # should be considered an error. log.error( 'The module \'%s\' is showing some bad usage. Its ' '__virtualname__ attribute is set to \'%s\' yet the ' '__virtual__() function is returning \'%s\'. These ' 'values should match!', mod.__name__, virtualname, virtual ) module_name = virtualname # If the __virtual__ function returns True and __virtualname__ # is set then use it elif virtual is True and virtualname != module_name: if virtualname is not True: module_name = virtualname except KeyError: # Key errors come out of the virtual function when passing # in incomplete grains sets, these can be safely ignored # and logged to debug, still, it includes the traceback to # help debugging. log.debug('KeyError when loading %s', module_name, exc_info=True) except Exception: # If the module throws an exception during __virtual__() # then log the information and continue to the next. log.error( 'Failed to read the virtual function for %s: %s', self.tag, module_name, exc_info=True ) return (False, module_name, error_reason, virtual_aliases) return (True, module_name, None, virtual_aliases) def global_injector_decorator(inject_globals): ''' Decorator used by the LazyLoader to inject globals into a function at execute time. globals Dictionary with global variables to inject ''' def inner_decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): with salt.utils.context.func_globals_inject(f, **inject_globals): return f(*args, **kwargs) return wrapper return inner_decorator
saltstack/salt
salt/loader.py
raw_mod
python
def raw_mod(opts, name, functions, mod='modules'): ''' Returns a single module loaded raw and bypassing the __virtual__ function .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') testmod = salt.loader.raw_mod(__opts__, 'test', None) testmod['test.ping']() ''' loader = LazyLoader( _module_dirs(opts, mod, 'module'), opts, tag='rawmodule', virtual_enable=False, pack={'__salt__': functions}, ) # if we don't have the module, return an empty dict if name not in loader.file_mapping: return {} loader._load_module(name) # load a single module (the one passed in) return dict(loader._dict)
Returns a single module loaded raw and bypassing the __virtual__ function .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') testmod = salt.loader.raw_mod(__opts__, 'test', None) testmod['test.ping']()
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L290-L315
null
# -*- coding: utf-8 -*- ''' The Salt loader is the core to Salt's plugin system, the loader scans directories for python loadable code and organizes the code into the plugin interfaces used by Salt. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import sys import time import logging import inspect import tempfile import threading import functools import threading import traceback import types from zipimport import zipimporter # Import salt libs import salt.config import salt.defaults.events import salt.defaults.exitcodes import salt.syspaths import salt.utils.args import salt.utils.context import salt.utils.data import salt.utils.dictupdate import salt.utils.event import salt.utils.files import salt.utils.lazy import salt.utils.odict import salt.utils.platform import salt.utils.versions import salt.utils.stringutils from salt.exceptions import LoaderError from salt.template import check_render_pipe_str from salt.utils.decorators import Depends from salt.utils.thread_local_proxy import ThreadLocalProxy # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import reload_module if sys.version_info[:2] >= (3, 5): import importlib.machinery # pylint: disable=no-name-in-module,import-error import importlib.util # pylint: disable=no-name-in-module,import-error USE_IMPORTLIB = True else: import imp USE_IMPORTLIB = False try: from collections.abc import MutableMapping except ImportError: from collections import MutableMapping try: import pkg_resources HAS_PKG_RESOURCES = True except ImportError: HAS_PKG_RESOURCES = False log = logging.getLogger(__name__) SALT_BASE_PATH = os.path.abspath(salt.syspaths.INSTALL_DIR) LOADED_BASE_NAME = 'salt.loaded' if USE_IMPORTLIB: # pylint: disable=no-member MODULE_KIND_SOURCE = 1 MODULE_KIND_COMPILED = 2 MODULE_KIND_EXTENSION = 3 MODULE_KIND_PKG_DIRECTORY = 5 SUFFIXES = [] for suffix in importlib.machinery.EXTENSION_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_EXTENSION)) for suffix in importlib.machinery.SOURCE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_SOURCE)) for suffix in importlib.machinery.BYTECODE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_COMPILED)) MODULE_KIND_MAP = { MODULE_KIND_SOURCE: importlib.machinery.SourceFileLoader, MODULE_KIND_COMPILED: importlib.machinery.SourcelessFileLoader, MODULE_KIND_EXTENSION: importlib.machinery.ExtensionFileLoader } # pylint: enable=no-member else: SUFFIXES = imp.get_suffixes() PY3_PRE_EXT = \ re.compile(r'\.cpython-{0}{1}(\.opt-[1-9])?'.format(*sys.version_info[:2])) # Because on the cloud drivers we do `from salt.cloud.libcloudfuncs import *` # which simplifies code readability, it adds some unsupported functions into # the driver's module scope. # We list un-supported functions here. These will be removed from the loaded. # TODO: remove the need for this cross-module code. Maybe use NotImplemented LIBCLOUD_FUNCS_NOT_SUPPORTED = ( 'parallels.avail_sizes', 'parallels.avail_locations', 'proxmox.avail_sizes', ) # Will be set to pyximport module at runtime if cython is enabled in config. pyximport = None def static_loader( opts, ext_type, tag, pack=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, filter_name=None, ): funcs = LazyLoader( _module_dirs( opts, ext_type, tag, int_type, ext_dirs, ext_type_dirs, base_path, ), opts, tag=tag, pack=pack, ) ret = {} funcs._load_all() if filter_name: funcs = FilterDictWrapper(funcs, filter_name) for key in funcs: ret[key] = funcs[key] return ret def _format_entrypoint_target(ep): ''' Makes a string describing the target of an EntryPoint object. Base strongly on EntryPoint.__str__(). ''' s = ep.module_name if ep.attrs: s += ':' + '.'.join(ep.attrs) return s def _module_dirs( opts, ext_type, tag=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, ): if tag is None: tag = ext_type sys_types = os.path.join(base_path or SALT_BASE_PATH, int_type or ext_type) ext_types = os.path.join(opts['extension_modules'], ext_type) ext_type_types = [] if ext_dirs: if ext_type_dirs is None: ext_type_dirs = '{0}_dirs'.format(tag) if ext_type_dirs in opts: ext_type_types.extend(opts[ext_type_dirs]) if HAS_PKG_RESOURCES and ext_type_dirs: for entry_point in pkg_resources.iter_entry_points('salt.loader', ext_type_dirs): try: loaded_entry_point = entry_point.load() for path in loaded_entry_point(): ext_type_types.append(path) except Exception as exc: log.error("Error getting module directories from %s: %s", _format_entrypoint_target(entry_point), exc) log.debug("Full backtrace for module directories error", exc_info=True) cli_module_dirs = [] # The dirs can be any module dir, or a in-tree _{ext_type} dir for _dir in opts.get('module_dirs', []): # Prepend to the list to match cli argument ordering maybe_dir = os.path.join(_dir, ext_type) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) continue maybe_dir = os.path.join(_dir, '_{0}'.format(ext_type)) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) return cli_module_dirs + ext_type_types + [ext_types, sys_types] def minion_mods( opts, context=None, utils=None, whitelist=None, initial_load=False, loaded_base_name=None, notify=False, static_modules=None, proxy=None): ''' Load execution modules Returns a dictionary of execution modules appropriate for the current system by evaluating the __virtual__() function in each module. :param dict opts: The Salt options dictionary :param dict context: A Salt context that should be made present inside generated modules in __context__ :param dict utils: Utility functions which should be made available to Salt modules in __utils__. See `utils_dirs` in salt.config for additional information about configuration. :param list whitelist: A list of modules which should be whitelisted. :param bool initial_load: Deprecated flag! Unused. :param str loaded_base_name: A string marker for the loaded base name. :param bool notify: Flag indicating that an event should be fired upon completion of module loading. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) __opts__['grains'] = __grains__ __utils__ = salt.loader.utils(__opts__) __salt__ = salt.loader.minion_mods(__opts__, utils=__utils__) __salt__['test.ping']() ''' # TODO Publish documentation for module whitelisting if not whitelist: whitelist = opts.get('whitelist_modules', None) ret = LazyLoader( _module_dirs(opts, 'modules', 'module'), opts, tag='module', pack={'__context__': context, '__utils__': utils, '__proxy__': proxy}, whitelist=whitelist, loaded_base_name=loaded_base_name, static_modules=static_modules, ) ret.pack['__salt__'] = ret # Load any provider overrides from the configuration file providers option # Note: Providers can be pkg, service, user or group - not to be confused # with cloud providers. providers = opts.get('providers', False) if providers and isinstance(providers, dict): for mod in providers: # sometimes providers opts is not to diverge modules but # for other configuration try: funcs = raw_mod(opts, providers[mod], ret) except TypeError: break else: if funcs: for func in funcs: f_key = '{0}{1}'.format(mod, func[func.rindex('.'):]) ret[f_key] = funcs[func] if notify: evt = salt.utils.event.get_event('minion', opts=opts, listen=False) evt.fire_event({'complete': True}, tag=salt.defaults.events.MINION_MOD_COMPLETE) return ret # return a copy of *just* the funcs for `name` def metaproxy(opts): ''' Return functions used in the meta proxy ''' return LazyLoader( _module_dirs(opts, 'metaproxy'), opts, tag='metaproxy' ) def matchers(opts): ''' Return the matcher services plugins ''' return LazyLoader( _module_dirs(opts, 'matchers'), opts, tag='matchers' ) def engines(opts, functions, runners, utils, proxy=None): ''' Return the master services plugins ''' pack = {'__salt__': functions, '__runners__': runners, '__proxy__': proxy, '__utils__': utils} return LazyLoader( _module_dirs(opts, 'engines'), opts, tag='engines', pack=pack, ) def proxy(opts, functions=None, returners=None, whitelist=None, utils=None): ''' Returns the proxy module for this salt-proxy-minion ''' ret = LazyLoader( _module_dirs(opts, 'proxy'), opts, tag='proxy', pack={'__salt__': functions, '__ret__': returners, '__utils__': utils}, ) ret.pack['__proxy__'] = ret return ret def returners(opts, functions, whitelist=None, context=None, proxy=None): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'returners', 'returner'), opts, tag='returner', whitelist=whitelist, pack={'__salt__': functions, '__context__': context, '__proxy__': proxy or {}}, ) def utils(opts, whitelist=None, context=None, proxy=proxy): ''' Returns the utility modules ''' return LazyLoader( _module_dirs(opts, 'utils', ext_type_dirs='utils_dirs'), opts, tag='utils', whitelist=whitelist, pack={'__context__': context, '__proxy__': proxy or {}}, ) def pillars(opts, functions, context=None): ''' Returns the pillars modules ''' ret = LazyLoader(_module_dirs(opts, 'pillar'), opts, tag='pillar', pack={'__salt__': functions, '__context__': context, '__utils__': utils(opts)}) ret.pack['__ext_pillar__'] = ret return FilterDictWrapper(ret, '.ext_pillar') def tops(opts): ''' Returns the tops modules ''' if 'master_tops' not in opts: return {} whitelist = list(opts['master_tops'].keys()) ret = LazyLoader( _module_dirs(opts, 'tops', 'top'), opts, tag='top', whitelist=whitelist, ) return FilterDictWrapper(ret, '.top') def wheels(opts, whitelist=None, context=None): ''' Returns the wheels modules ''' if context is None: context = {} return LazyLoader( _module_dirs(opts, 'wheel'), opts, tag='wheel', whitelist=whitelist, pack={'__context__': context}, ) def outputters(opts): ''' Returns the outputters modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only outputters present in the keyspace ''' ret = LazyLoader( _module_dirs(opts, 'output', ext_type_dirs='outputter_dirs'), opts, tag='output', ) wrapped_ret = FilterDictWrapper(ret, '.output') # TODO: this name seems terrible... __salt__ should always be execution mods ret.pack['__salt__'] = wrapped_ret return wrapped_ret def serializers(opts): ''' Returns the serializers modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only serializers present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'serializers'), opts, tag='serializers', ) def eauth_tokens(opts): ''' Returns the tokens modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only token backends present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'tokens'), opts, tag='tokens', ) def auth(opts, whitelist=None): ''' Returns the auth modules :param dict opts: The Salt options dictionary :returns: LazyLoader ''' return LazyLoader( _module_dirs(opts, 'auth'), opts, tag='auth', whitelist=whitelist, pack={'__salt__': minion_mods(opts)}, ) def fileserver(opts, backends): ''' Returns the file server modules ''' return LazyLoader(_module_dirs(opts, 'fileserver'), opts, tag='fileserver', whitelist=backends, pack={'__utils__': utils(opts)}) def roster(opts, runner=None, utils=None, whitelist=None): ''' Returns the roster modules ''' return LazyLoader( _module_dirs(opts, 'roster'), opts, tag='roster', whitelist=whitelist, pack={ '__runner__': runner, '__utils__': utils, }, ) def thorium(opts, functions, runners): ''' Load the thorium runtime modules ''' pack = {'__salt__': functions, '__runner__': runners, '__context__': {}} ret = LazyLoader(_module_dirs(opts, 'thorium'), opts, tag='thorium', pack=pack) ret.pack['__thorium__'] = ret return ret def states(opts, functions, utils, serializers, whitelist=None, proxy=None, context=None): ''' Returns the state modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') statemods = salt.loader.states(__opts__, None, None) ''' if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'states'), opts, tag='states', pack={'__salt__': functions, '__proxy__': proxy or {}}, whitelist=whitelist, ) ret.pack['__states__'] = ret ret.pack['__utils__'] = utils ret.pack['__serializers__'] = serializers ret.pack['__context__'] = context return ret def beacons(opts, functions, context=None, proxy=None): ''' Load the beacon modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. ''' return LazyLoader( _module_dirs(opts, 'beacons'), opts, tag='beacons', pack={'__context__': context, '__salt__': functions, '__proxy__': proxy or {}}, virtual_funcs=[], ) def log_handlers(opts): ''' Returns the custom logging handler modules :param dict opts: The Salt options dictionary ''' ret = LazyLoader( _module_dirs( opts, 'log_handlers', int_type='handlers', base_path=os.path.join(SALT_BASE_PATH, 'log'), ), opts, tag='log_handlers', ) return FilterDictWrapper(ret, '.setup_handlers') def ssh_wrapper(opts, functions=None, context=None): ''' Returns the custom logging handler modules ''' return LazyLoader( _module_dirs( opts, 'wrapper', base_path=os.path.join(SALT_BASE_PATH, os.path.join('client', 'ssh')), ), opts, tag='wrapper', pack={ '__salt__': functions, '__grains__': opts.get('grains', {}), '__pillar__': opts.get('pillar', {}), '__context__': context, }, ) def render(opts, functions, states=None, proxy=None, context=None): ''' Returns the render modules ''' if context is None: context = {} pack = {'__salt__': functions, '__grains__': opts.get('grains', {}), '__context__': context} if states: pack['__states__'] = states pack['__proxy__'] = proxy or {} ret = LazyLoader( _module_dirs( opts, 'renderers', 'render', ext_type_dirs='render_dirs', ), opts, tag='render', pack=pack, ) rend = FilterDictWrapper(ret, '.render') if not check_render_pipe_str(opts['renderer'], rend, opts['renderer_blacklist'], opts['renderer_whitelist']): err = ('The renderer {0} is unavailable, this error is often because ' 'the needed software is unavailable'.format(opts['renderer'])) log.critical(err) raise LoaderError(err) return rend def grain_funcs(opts, proxy=None): ''' Returns the grain functions .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') grainfuncs = salt.loader.grain_funcs(__opts__) ''' ret = LazyLoader( _module_dirs( opts, 'grains', 'grain', ext_type_dirs='grains_dirs', ), opts, tag='grains', ) ret.pack['__utils__'] = utils(opts, proxy=proxy) return ret def _load_cached_grains(opts, cfn): ''' Returns the grains cached in cfn, or None if the cache is too old or is corrupted. ''' if not os.path.isfile(cfn): log.debug('Grains cache file does not exist.') return None grains_cache_age = int(time.time() - os.path.getmtime(cfn)) if grains_cache_age > opts.get('grains_cache_expiration', 300): log.debug( 'Grains cache last modified %s seconds ago and cache ' 'expiration is set to %s. Grains cache expired. ' 'Refreshing.', grains_cache_age, opts.get('grains_cache_expiration', 300) ) return None if opts.get('refresh_grains_cache', False): log.debug('refresh_grains_cache requested, Refreshing.') return None log.debug('Retrieving grains from cache') try: serial = salt.payload.Serial(opts) with salt.utils.files.fopen(cfn, 'rb') as fp_: cached_grains = salt.utils.data.decode(serial.load(fp_), preserve_tuples=True) if not cached_grains: log.debug('Cached grains are empty, cache might be corrupted. Refreshing.') return None return cached_grains except (IOError, OSError): return None def grains(opts, force_refresh=False, proxy=None): ''' Return the functions for the dynamic grains and the values for the static grains. Since grains are computed early in the startup process, grains functions do not have __salt__ or __proxy__ available. At proxy-minion startup, this function is called with the proxymodule LazyLoader object so grains functions can communicate with their controlled device. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) print __grains__['id'] ''' # Need to re-import salt.config, somehow it got lost when a minion is starting import salt.config # if we have no grains, lets try loading from disk (TODO: move to decorator?) cfn = os.path.join( opts['cachedir'], 'grains.cache.p' ) if not force_refresh and opts.get('grains_cache', False): cached_grains = _load_cached_grains(opts, cfn) if cached_grains: return cached_grains else: log.debug('Grains refresh requested. Refreshing grains.') if opts.get('skip_grains', False): return {} grains_deep_merge = opts.get('grains_deep_merge', False) is True if 'conf_file' in opts: pre_opts = {} pre_opts.update(salt.config.load_config( opts['conf_file'], 'SALT_MINION_CONFIG', salt.config.DEFAULT_MINION_OPTS['conf_file'] )) default_include = pre_opts.get( 'default_include', opts['default_include'] ) include = pre_opts.get('include', []) pre_opts.update(salt.config.include_config( default_include, opts['conf_file'], verbose=False )) pre_opts.update(salt.config.include_config( include, opts['conf_file'], verbose=True )) if 'grains' in pre_opts: opts['grains'] = pre_opts['grains'] else: opts['grains'] = {} else: opts['grains'] = {} grains_data = {} blist = opts.get('grains_blacklist', []) funcs = grain_funcs(opts, proxy=proxy) if force_refresh: # if we refresh, lets reload grain modules funcs.clear() # Run core grains for key in funcs: if not key.startswith('core.'): continue log.trace('Loading %s grain', key) ret = funcs[key]() if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) # Run the rest of the grains for key in funcs: if key.startswith('core.') or key == '_errors': continue try: # Grains are loaded too early to take advantage of the injected # __proxy__ variable. Pass an instance of that LazyLoader # here instead to grains functions if the grains functions take # one parameter. Then the grains can have access to the # proxymodule for retrieving information from the connected # device. log.trace('Loading %s grain', key) parameters = salt.utils.args.get_function_argspec(funcs[key]).args kwargs = {} if 'proxy' in parameters: kwargs['proxy'] = proxy if 'grains' in parameters: kwargs['grains'] = grains_data ret = funcs[key](**kwargs) except Exception: if salt.utils.platform.is_proxy(): log.info('The following CRITICAL message may not be an error; the proxy may not be completely established yet.') log.critical( 'Failed to load grains defined in grain file %s in ' 'function %s, error:\n', key, funcs[key], exc_info=True ) continue if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) if opts.get('proxy_merge_grains_in_module', True) and proxy: try: proxytype = proxy.opts['proxy']['proxytype'] if proxytype + '.grains' in proxy: if proxytype + '.initialized' in proxy and proxy[proxytype + '.initialized'](): try: proxytype = proxy.opts['proxy']['proxytype'] ret = proxy[proxytype + '.grains']() if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) except Exception: log.critical('Failed to run proxy\'s grains function!', exc_info=True ) except KeyError: pass grains_data.update(opts['grains']) # Write cache if enabled if opts.get('grains_cache', False): with salt.utils.files.set_umask(0o077): try: if salt.utils.platform.is_windows(): # Late import import salt.modules.cmdmod # Make sure cache file isn't read-only salt.modules.cmdmod._run_quiet('attrib -R "{0}"'.format(cfn)) with salt.utils.files.fopen(cfn, 'w+b') as fp_: try: serial = salt.payload.Serial(opts) serial.dump(grains_data, fp_) except TypeError as e: log.error('Failed to serialize grains cache: %s', e) raise # re-throw for cleanup except Exception as e: log.error('Unable to write to grains cache file %s: %s', cfn, e) # Based on the original exception, the file may or may not have been # created. If it was, we will remove it now, as the exception means # the serialized data is not to be trusted, no matter what the # exception is. if os.path.isfile(cfn): os.unlink(cfn) if grains_deep_merge: salt.utils.dictupdate.update(grains_data, opts['grains']) else: grains_data.update(opts['grains']) return salt.utils.data.decode(grains_data, preserve_tuples=True) # TODO: get rid of? Does anyone use this? You should use raw() instead def call(fun, **kwargs): ''' Directly call a function inside a loader directory ''' args = kwargs.get('args', []) dirs = kwargs.get('dirs', []) funcs = LazyLoader( [os.path.join(SALT_BASE_PATH, 'modules')] + dirs, None, tag='modules', virtual_enable=False, ) return funcs[fun](*args) def runner(opts, utils=None, context=None, whitelist=None): ''' Directly call a function inside a loader directory ''' if utils is None: utils = {} if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'runners', 'runner', ext_type_dirs='runner_dirs'), opts, tag='runners', pack={'__utils__': utils, '__context__': context}, whitelist=whitelist, ) # TODO: change from __salt__ to something else, we overload __salt__ too much ret.pack['__salt__'] = ret return ret def queues(opts): ''' Directly call a function inside a loader directory ''' return LazyLoader( _module_dirs(opts, 'queues', 'queue', ext_type_dirs='queue_dirs'), opts, tag='queues', ) def sdb(opts, functions=None, whitelist=None, utils=None): ''' Make a very small database call ''' if utils is None: utils = {} return LazyLoader( _module_dirs(opts, 'sdb'), opts, tag='sdb', pack={ '__sdb__': functions, '__opts__': opts, '__utils__': utils, '__salt__': minion_mods(opts, utils), }, whitelist=whitelist, ) def pkgdb(opts): ''' Return modules for SPM's package database .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgdb', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgdb' ) def pkgfiles(opts): ''' Return modules for SPM's file handling .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgfiles', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgfiles' ) def clouds(opts): ''' Return the cloud functions ''' # Let's bring __active_provider_name__, defaulting to None, to all cloud # drivers. This will get temporarily updated/overridden with a context # manager when needed. functions = LazyLoader( _module_dirs(opts, 'clouds', 'cloud', base_path=os.path.join(SALT_BASE_PATH, 'cloud'), int_type='clouds'), opts, tag='clouds', pack={'__utils__': salt.loader.utils(opts), '__active_provider_name__': None}, ) for funcname in LIBCLOUD_FUNCS_NOT_SUPPORTED: log.trace( '\'%s\' has been marked as not supported. Removing from the ' 'list of supported cloud functions', funcname ) functions.pop(funcname, None) return functions def netapi(opts): ''' Return the network api functions ''' return LazyLoader( _module_dirs(opts, 'netapi'), opts, tag='netapi', ) def executors(opts, functions=None, context=None, proxy=None): ''' Returns the executor modules ''' executors = LazyLoader( _module_dirs(opts, 'executors', 'executor'), opts, tag='executor', pack={'__salt__': functions, '__context__': context or {}, '__proxy__': proxy or {}}, ) executors.pack['__executors__'] = executors return executors def cache(opts, serial): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'cache', 'cache'), opts, tag='cache', pack={'__opts__': opts, '__context__': {'serial': serial}}, ) def _generate_module(name): if name in sys.modules: return code = "'''Salt loaded {0} parent module'''".format(name.split('.')[-1]) # ModuleType can't accept a unicode type on PY2 module = types.ModuleType(str(name)) # future lint: disable=blacklisted-function exec(code, module.__dict__) sys.modules[name] = module def _mod_type(module_path): if module_path.startswith(SALT_BASE_PATH): return 'int' return 'ext' def _inject_into_mod(mod, name, value, force_lock=False): ''' Inject a variable into a module. This is used to inject "globals" like ``__salt__``, ``__pillar``, or ``grains``. Instead of injecting the value directly, a ``ThreadLocalProxy`` is created. If such a proxy is already present under the specified name, it is updated with the new value. This update only affects the current thread, so that the same name can refer to different values depending on the thread of execution. This is important for data that is not truly global. For example, pillar data might be dynamically overriden through function parameters and thus the actual values available in pillar might depend on the thread that is calling a module. mod: module object into which the value is going to be injected. name: name of the variable that is injected into the module. value: value that is injected into the variable. The value is not injected directly, but instead set as the new reference of the proxy that has been created for the variable. force_lock: whether the lock should be acquired before checking whether a proxy object for the specified name has already been injected into the module. If ``False`` (the default), this function checks for the module's variable without acquiring the lock and only acquires the lock if a new proxy has to be created and injected. ''' old_value = getattr(mod, name, None) # We use a double-checked locking scheme in order to avoid taking the lock # when a proxy object has already been injected. # In most programming languages, double-checked locking is considered # unsafe when used without explicit memory barriers because one might read # an uninitialized value. In CPython it is safe due to the global # interpreter lock (GIL). In Python implementations that do not have the # GIL, it could be unsafe, but at least Jython also guarantees that (for # Python objects) memory is not corrupted when writing and reading without # explicit synchronization # (http://www.jython.org/jythonbook/en/1.0/Concurrency.html). # Please note that in order to make this code safe in a runtime environment # that does not make this guarantees, it is not sufficient. The # ThreadLocalProxy must also be created with fallback_to_shared set to # False or a lock must be added to the ThreadLocalProxy. if force_lock: with _inject_into_mod.lock: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: setattr(mod, name, ThreadLocalProxy(value, True)) else: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: _inject_into_mod(mod, name, value, True) # Lock used when injecting globals. This is needed to avoid a race condition # when two threads try to load the same module concurrently. This must be # outside the loader because there might be more than one loader for the same # namespace. _inject_into_mod.lock = threading.RLock() # TODO: move somewhere else? class FilterDictWrapper(MutableMapping): ''' Create a dict which wraps another dict with a specific key suffix on get This is to replace "filter_load" ''' def __init__(self, d, suffix): self._dict = d self.suffix = suffix def __setitem__(self, key, val): self._dict[key] = val def __delitem__(self, key): del self._dict[key] def __getitem__(self, key): return self._dict[key + self.suffix] def __len__(self): return len(self._dict) def __iter__(self): for key in self._dict: if key.endswith(self.suffix): yield key.replace(self.suffix, '') class LazyLoader(salt.utils.lazy.LazyDict): ''' A pseduo-dictionary which has a set of keys which are the name of the module and function, delimited by a dot. When the value of the key is accessed, the function is then loaded from disk and into memory. .. note:: Iterating over keys will cause all modules to be loaded. :param list module_dirs: A list of directories on disk to search for modules :param dict opts: The salt options dictionary. :param str tag: The tag for the type of module to load :param func mod_type_check: A function which can be used to verify files :param dict pack: A dictionary of function to be packed into modules as they are loaded :param list whitelist: A list of modules to whitelist :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules. :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality. If not true, the module will not load. :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values are function references themselves which are loaded on-demand. # TODO: - move modules_max_memory into here - singletons (per tag) ''' mod_dict_class = salt.utils.odict.OrderedDict def __init__(self, module_dirs, opts=None, tag='module', loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, proxy=None, virtual_funcs=None, ): # pylint: disable=W0231 ''' In pack, if any of the values are None they will be replaced with an empty context-specific dict ''' self.inject_globals = {} self.pack = {} if pack is None else pack if opts is None: opts = {} threadsafety = not opts.get('multiprocessing') self.context_dict = salt.utils.context.ContextDict(threadsafe=threadsafety) self.opts = self.__prep_mod_opts(opts) self.module_dirs = module_dirs self.tag = tag self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME self.mod_type_check = mod_type_check or _mod_type if '__context__' not in self.pack: self.pack['__context__'] = None for k, v in six.iteritems(self.pack): if v is None: # if the value of a pack is None, lets make an empty dict value = self.context_dict.get(k, {}) if isinstance(value, ThreadLocalProxy): value = ThreadLocalProxy.unproxy(value) self.context_dict[k] = value self.pack[k] = salt.utils.context.NamespacedDictWrapper(self.context_dict, k) self.whitelist = whitelist self.virtual_enable = virtual_enable self.initial_load = True # names of modules that we don't have (errors, __virtual__, etc.) self.missing_modules = {} # mapping of name -> error self.loaded_modules = {} # mapping of module_name -> dict_of_functions self.loaded_files = set() # TODO: just remove them from file_mapping? self.static_modules = static_modules if static_modules else [] if virtual_funcs is None: virtual_funcs = [] self.virtual_funcs = virtual_funcs self.disabled = set( self.opts.get( 'disable_{0}{1}'.format( self.tag, '' if self.tag[-1] == 's' else 's' ), [] ) ) # A map of suffix to description for imp self.suffix_map = {} # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [''] for (suffix, mode, kind) in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) self._lock = threading.RLock() self._refresh_file_mapping() super(LazyLoader, self).__init__() # late init the lazy loader # create all of the import namespaces _generate_module('{0}.int'.format(self.loaded_base_name)) _generate_module('{0}.int.{1}'.format(self.loaded_base_name, tag)) _generate_module('{0}.ext'.format(self.loaded_base_name)) _generate_module('{0}.ext.{1}'.format(self.loaded_base_name, tag)) def __getitem__(self, item): ''' Override the __getitem__ in order to decorate the returned function if we need to last-minute inject globals ''' func = super(LazyLoader, self).__getitem__(item) if self.inject_globals: return global_injector_decorator(self.inject_globals)(func) else: return func def __getattr__(self, mod_name): ''' Allow for "direct" attribute access-- this allows jinja templates to access things like `salt.test.ping()` ''' if mod_name in ('__getstate__', '__setstate__'): return object.__getattribute__(self, mod_name) # if we have an attribute named that, lets return it. try: return object.__getattr__(self, mod_name) # pylint: disable=no-member except AttributeError: pass # otherwise we assume its jinja template access if mod_name not in self.loaded_modules and not self.loaded: for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and mod_name in self.loaded_modules: break if mod_name in self.loaded_modules: return self.loaded_modules[mod_name] else: raise AttributeError(mod_name) def missing_fun_string(self, function_name): ''' Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ''' mod_name = function_name.split('.')[0] if mod_name in self.loaded_modules: return '\'{0}\' is not available.'.format(function_name) else: try: reason = self.missing_modules[mod_name] except KeyError: return '\'{0}\' is not available.'.format(function_name) else: if reason is not None: return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason) else: return '\'{0}\' __virtual__ returned False'.format(mod_name) def _refresh_file_mapping(self): ''' refresh the mapping of the FS on disk ''' # map of suffix to description for imp if self.opts.get('cython_enable', True) is True: try: global pyximport pyximport = __import__('pyximport') # pylint: disable=import-error pyximport.install() # add to suffix_map so file_mapping will pick it up self.suffix_map['.pyx'] = tuple() except ImportError: log.info('Cython is enabled in the options but not present ' 'in the system path. Skipping Cython modules.') # Allow for zipimport of modules if self.opts.get('enable_zip_modules', True) is True: self.suffix_map['.zip'] = tuple() # allow for module dirs if USE_IMPORTLIB: self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY) else: self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY) # create mapping of filename (without suffix) to (path, suffix) # The files are added in order of priority, so order *must* be retained. self.file_mapping = salt.utils.odict.OrderedDict() opt_match = [] def _replace_pre_ext(obj): ''' Hack so we can get the optimization level that we replaced (if any) out of the re.sub call below. We use a list here because it is a persistent data structure that we will be able to access after re.sub is called. ''' opt_match.append(obj) return '' for mod_dir in self.module_dirs: try: # Make sure we have a sorted listdir in order to have # expectable override results files = sorted( x for x in os.listdir(mod_dir) if x != '__pycache__' ) except OSError: continue # Next mod_dir if six.PY3: try: pycache_files = [ os.path.join('__pycache__', x) for x in sorted(os.listdir(os.path.join(mod_dir, '__pycache__'))) ] except OSError: pass else: files.extend(pycache_files) for filename in files: try: dirname, basename = os.path.split(filename) if basename.startswith('_'): # skip private modules # log messages omitted for obviousness continue # Next filename f_noext, ext = os.path.splitext(basename) if six.PY3: f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext) try: opt_level = int( opt_match.pop().group(1).rsplit('-', 1)[-1] ) except (AttributeError, IndexError, ValueError): # No regex match or no optimization level matched opt_level = 0 try: opt_index = self.opts['optimization_order'].index(opt_level) except KeyError: log.trace( 'Disallowed optimization level %d for module ' 'name \'%s\', skipping. Add %d to the ' '\'optimization_order\' config option if you ' 'do not want to ignore this optimization ' 'level.', opt_level, f_noext, opt_level ) continue else: # Optimization level not reflected in filename on PY2 opt_index = 0 # make sure it is a suffix we support if ext not in self.suffix_map: continue # Next filename if f_noext in self.disabled: log.trace( 'Skipping %s, it is disabled by configuration', filename ) continue # Next filename fpath = os.path.join(mod_dir, filename) # if its a directory, lets allow us to load that if ext == '': # is there something __init__? subfiles = os.listdir(fpath) for suffix in self.suffix_order: if '' == suffix: continue # Next suffix (__init__ must have a suffix) init_file = '__init__{0}'.format(suffix) if init_file in subfiles: break else: continue # Next filename try: curr_ext = self.file_mapping[f_noext][1] curr_opt_index = self.file_mapping[f_noext][2] except KeyError: pass else: if '' in (curr_ext, ext) and curr_ext != ext: log.error( 'Module/package collision: \'%s\' and \'%s\'', fpath, self.file_mapping[f_noext][0] ) if six.PY3 and ext == '.pyc' and curr_ext == '.pyc': # Check the optimization level if opt_index >= curr_opt_index: # Module name match, but a higher-priority # optimization level was already matched, skipping. continue elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext): # Match found but a higher-priorty match already # exists, so skip this. continue if six.PY3 and not dirname and ext == '.pyc': # On Python 3, we should only load .pyc files from the # __pycache__ subdirectory (i.e. when dirname is not an # empty string). continue # Made it this far - add it self.file_mapping[f_noext] = (fpath, ext, opt_index) except OSError: continue for smod in self.static_modules: f_noext = smod.split('.')[-1] self.file_mapping[f_noext] = (smod, '.o', 0) def clear(self): ''' Clear the dict ''' with self._lock: super(LazyLoader, self).clear() # clear the lazy loader self.loaded_files = set() self.missing_modules = {} self.loaded_modules = {} # if we have been loaded before, lets clear the file mapping since # we obviously want a re-do if hasattr(self, 'opts'): self._refresh_file_mapping() self.initial_load = False def __prep_mod_opts(self, opts): ''' Strip out of the opts any logger instance ''' if '__grains__' not in self.pack: grains = opts.get('grains', {}) if isinstance(grains, ThreadLocalProxy): grains = ThreadLocalProxy.unproxy(grains) self.context_dict['grains'] = grains self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains') if '__pillar__' not in self.pack: pillar = opts.get('pillar', {}) if isinstance(pillar, ThreadLocalProxy): pillar = ThreadLocalProxy.unproxy(pillar) self.context_dict['pillar'] = pillar self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar') mod_opts = {} for key, val in list(opts.items()): if key == 'logger': continue mod_opts[key] = val return mod_opts def _iter_files(self, mod_name): ''' Iterate over all file_mapping files in order of closeness to mod_name ''' # do we have an exact match? if mod_name in self.file_mapping: yield mod_name # do we have a partial match? for k in self.file_mapping: if mod_name in k: yield k # anyone else? Bueller? for k in self.file_mapping: if mod_name not in k: yield k def _reload_submodules(self, mod): submodules = ( getattr(mod, sname) for sname in dir(mod) if isinstance(getattr(mod, sname), mod.__class__) ) # reload only custom "sub"modules for submodule in submodules: # it is a submodule if the name is in a namespace under mod if submodule.__name__.startswith(mod.__name__ + '.'): reload_module(submodule) self._reload_submodules(submodule) def _load_module(self, name): mod = None fpath, suffix = self.file_mapping[name][:2] self.loaded_files.add(name) fpath_dirname = os.path.dirname(fpath) try: sys.path.append(fpath_dirname) if suffix == '.pyx': mod = pyximport.load_module(name, fpath, tempfile.gettempdir()) elif suffix == '.o': top_mod = __import__(fpath, globals(), locals(), []) comps = fpath.split('.') if len(comps) < 2: mod = top_mod else: mod = top_mod for subname in comps[1:]: mod = getattr(mod, subname) elif suffix == '.zip': mod = zipimporter(fpath).load_module(name) else: desc = self.suffix_map[suffix] # if it is a directory, we don't open a file try: mod_namespace = '.'.join(( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name)) except TypeError: mod_namespace = '{0}.{1}.{2}.{3}'.format( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name) if suffix == '': if USE_IMPORTLIB: # pylint: disable=no-member # Package directory, look for __init__ loader_details = [ (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES), (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES), (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), ] file_finder = importlib.machinery.FileFinder( fpath_dirname, *loader_details ) spec = file_finder.find_spec(mod_namespace) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: mod = imp.load_module(mod_namespace, None, fpath, desc) # reload all submodules if necessary if not self.initial_load: self._reload_submodules(mod) else: if USE_IMPORTLIB: # pylint: disable=no-member loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath) spec = importlib.util.spec_from_file_location( mod_namespace, fpath, loader=loader ) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() #mod = importlib.util.module_from_spec(spec) #spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: with salt.utils.files.fopen(fpath, desc[1]) as fn_: mod = imp.load_module(mod_namespace, fn_, fpath, desc) except IOError: raise except ImportError as exc: if 'magic number' in six.text_type(exc): error_msg = 'Failed to import {0} {1}. Bad magic number. If migrating from Python2 to Python3, remove all .pyc files and try again.'.format(self.tag, name) log.warning(error_msg) self.missing_modules[name] = error_msg log.debug( 'Failed to import %s %s:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = exc return False except Exception as error: log.error( 'Failed to import %s %s, this is due most likely to a ' 'syntax error:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False except SystemExit as error: try: fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1] except Exception: pass else: tgt_fn = os.path.join('salt', 'utils', 'process.py') if fn_.endswith(tgt_fn) and '_handle_signals' in caller: # Race conditon, SIGTERM or SIGINT received while loader # was in process of loading a module. Call sys.exit to # ensure that the process is killed. sys.exit(salt.defaults.exitcodes.EX_OK) log.error( 'Failed to import %s %s as the module called exit()\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False finally: sys.path.remove(fpath_dirname) if hasattr(mod, '__opts__'): mod.__opts__.update(self.opts) else: mod.__opts__ = self.opts # pack whatever other globals we were asked to for p_name, p_value in six.iteritems(self.pack): _inject_into_mod(mod, p_name, p_value) module_name = mod.__name__.rsplit('.', 1)[-1] # Call a module's initialization method if it exists module_init = getattr(mod, '__init__', None) if inspect.isfunction(module_init): try: module_init(self.opts) except TypeError as e: log.error(e) except Exception: err_string = '__init__ failed' log.debug( 'Error loading %s.%s: %s', self.tag, module_name, err_string, exc_info=True ) self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False # if virtual modules are enabled, we need to look for the # __virtual__() function inside that module and run it. if self.virtual_enable: virtual_funcs_to_process = ['__virtual__'] + self.virtual_funcs for virtual_func in virtual_funcs_to_process: virtual_ret, module_name, virtual_err, virtual_aliases = \ self._process_virtual(mod, module_name, virtual_func) if virtual_err is not None: log.trace( 'Error loading %s.%s: %s', self.tag, module_name, virtual_err ) # if _process_virtual returned a non-True value then we are # supposed to not process this module if virtual_ret is not True and module_name not in self.missing_modules: # If a module has information about why it could not be loaded, record it self.missing_modules[module_name] = virtual_err self.missing_modules[name] = virtual_err return False else: virtual_aliases = () # If this is a proxy minion then MOST modules cannot work. Therefore, require that # any module that does work with salt-proxy-minion define __proxyenabled__ as a list # containing the names of the proxy types that the module supports. # # Render modules and state modules are OK though if 'proxy' in self.opts: if self.tag in ['grains', 'proxy']: if not hasattr(mod, '__proxyenabled__') or \ (self.opts['proxy']['proxytype'] not in mod.__proxyenabled__ and '*' not in mod.__proxyenabled__): err_string = 'not a proxy_minion enabled module' self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False if getattr(mod, '__load__', False) is not False: log.info( 'The functions from module \'%s\' are being loaded from the ' 'provided __load__ attribute', module_name ) # If we had another module by the same virtual name, we should put any # new functions under the existing dictionary. mod_names = [module_name] + list(virtual_aliases) mod_dict = dict(( (x, self.loaded_modules.get(x, self.mod_dict_class())) for x in mod_names )) for attr in getattr(mod, '__load__', dir(mod)): if attr.startswith('_') and attr != '__call__': # private functions are skipped, # except __call__ which is default entrance # for multi-function batch-like state syntax continue func = getattr(mod, attr) if not inspect.isfunction(func) and not isinstance(func, functools.partial): # Not a function!? Skip it!!! continue # Let's get the function name. # If the module has the __func_alias__ attribute, it must be a # dictionary mapping in the form of(key -> value): # <real-func-name> -> <desired-func-name> # # It default's of course to the found callable attribute name # if no alias is defined. funcname = getattr(mod, '__func_alias__', {}).get(attr, attr) for tgt_mod in mod_names: try: full_funcname = '.'.join((tgt_mod, funcname)) except TypeError: full_funcname = '{0}.{1}'.format(tgt_mod, funcname) # Save many references for lookups # Careful not to overwrite existing (higher priority) functions if full_funcname not in self._dict: self._dict[full_funcname] = func if funcname not in mod_dict[tgt_mod]: setattr(mod_dict[tgt_mod], funcname, func) mod_dict[tgt_mod][funcname] = func self._apply_outputter(func, mod) # enforce depends try: Depends.enforce_dependencies(self._dict, self.tag) except RuntimeError as exc: log.info( 'Depends.enforce_dependencies() failed for the following ' 'reason: %s', exc ) for tgt_mod in mod_names: self.loaded_modules[tgt_mod] = mod_dict[tgt_mod] return True def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise KeyError('The key \'{0}\' should contain a \'.\''.format(key)) mod_name, _ = key.split('.', 1) with self._lock: # It is possible that the key is in the dictionary after # acquiring the lock due to another thread loading it. if mod_name in self.missing_modules or key in self._dict: return True # if the modulename isn't in the whitelist, don't bother if self.whitelist and mod_name not in self.whitelist: log.error( 'Failed to load function %s because its module (%s) is ' 'not in the whitelist: %s', key, mod_name, self.whitelist ) raise KeyError(key) def _inner_load(mod_name): for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and key in self._dict: return True return False # try to load the module ret = None reloaded = False # re-scan up to once, IOErrors or a failed load cause re-scans of the # filesystem while True: try: ret = _inner_load(mod_name) if not reloaded and ret is not True: self._refresh_file_mapping() reloaded = True continue break except IOError: if not reloaded: self._refresh_file_mapping() reloaded = True continue return ret def _load_all(self): ''' Load all of them ''' with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True def reload_modules(self): with self._lock: self.loaded_files = set() self._load_all() def _apply_outputter(self, func, mod): ''' Apply the __outputter__ variable to the functions ''' if hasattr(mod, '__outputter__'): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__] def _process_virtual(self, mod, module_name, virtual_func='__virtual__'): ''' Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1] ''' # The __virtual__ function will return either a True or False value. # If it returns a True value it can also set a module level attribute # named __virtualname__ with the name that the module should be # referred to as. # # This allows us to have things like the pkg module working on all # platforms under the name 'pkg'. It also allows for modules like # augeas_cfg to be referred to as 'augeas', which would otherwise have # namespace collisions. And finally it allows modules to return False # if they are not intended to run on the given platform or are missing # dependencies. virtual_aliases = getattr(mod, '__virtual_aliases__', tuple()) try: error_reason = None if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__): try: start = time.time() virtual = getattr(mod, virtual_func)() if isinstance(virtual, tuple): error_reason = virtual[1] virtual = virtual[0] if self.opts.get('virtual_timer', False): end = time.time() - start msg = 'Virtual function took {0} seconds for {1}'.format( end, module_name) log.warning(msg) except Exception as exc: error_reason = ( 'Exception raised when processing __virtual__ function' ' for {0}. Module will not be loaded: {1}'.format( mod.__name__, exc)) log.error(error_reason, exc_info_on_loglevel=logging.DEBUG) virtual = None # Get the module's virtual name virtualname = getattr(mod, '__virtualname__', virtual) if not virtual: # if __virtual__() evaluates to False then the module # wasn't meant for this platform or it's not supposed to # load for some other reason. # Some modules might accidentally return None and are # improperly loaded if virtual is None: log.warning( '%s.__virtual__() is wrongly returning `None`. ' 'It should either return `True`, `False` or a new ' 'name. If you\'re the developer of the module ' '\'%s\', please fix this.', mod.__name__, module_name ) return (False, module_name, error_reason, virtual_aliases) # At this point, __virtual__ did not return a # boolean value, let's check for deprecated usage # or module renames if virtual is not True and module_name != virtual: # The module is renaming itself. Updating the module name # with the new name log.trace('Loaded %s as virtual %s', module_name, virtual) if virtualname != virtual: # The __virtualname__ attribute does not match what's # being returned by the __virtual__() function. This # should be considered an error. log.error( 'The module \'%s\' is showing some bad usage. Its ' '__virtualname__ attribute is set to \'%s\' yet the ' '__virtual__() function is returning \'%s\'. These ' 'values should match!', mod.__name__, virtualname, virtual ) module_name = virtualname # If the __virtual__ function returns True and __virtualname__ # is set then use it elif virtual is True and virtualname != module_name: if virtualname is not True: module_name = virtualname except KeyError: # Key errors come out of the virtual function when passing # in incomplete grains sets, these can be safely ignored # and logged to debug, still, it includes the traceback to # help debugging. log.debug('KeyError when loading %s', module_name, exc_info=True) except Exception: # If the module throws an exception during __virtual__() # then log the information and continue to the next. log.error( 'Failed to read the virtual function for %s: %s', self.tag, module_name, exc_info=True ) return (False, module_name, error_reason, virtual_aliases) return (True, module_name, None, virtual_aliases) def global_injector_decorator(inject_globals): ''' Decorator used by the LazyLoader to inject globals into a function at execute time. globals Dictionary with global variables to inject ''' def inner_decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): with salt.utils.context.func_globals_inject(f, **inject_globals): return f(*args, **kwargs) return wrapper return inner_decorator
saltstack/salt
salt/loader.py
engines
python
def engines(opts, functions, runners, utils, proxy=None): ''' Return the master services plugins ''' pack = {'__salt__': functions, '__runners__': runners, '__proxy__': proxy, '__utils__': utils} return LazyLoader( _module_dirs(opts, 'engines'), opts, tag='engines', pack=pack, )
Return the master services plugins
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L341-L354
null
# -*- coding: utf-8 -*- ''' The Salt loader is the core to Salt's plugin system, the loader scans directories for python loadable code and organizes the code into the plugin interfaces used by Salt. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import sys import time import logging import inspect import tempfile import threading import functools import threading import traceback import types from zipimport import zipimporter # Import salt libs import salt.config import salt.defaults.events import salt.defaults.exitcodes import salt.syspaths import salt.utils.args import salt.utils.context import salt.utils.data import salt.utils.dictupdate import salt.utils.event import salt.utils.files import salt.utils.lazy import salt.utils.odict import salt.utils.platform import salt.utils.versions import salt.utils.stringutils from salt.exceptions import LoaderError from salt.template import check_render_pipe_str from salt.utils.decorators import Depends from salt.utils.thread_local_proxy import ThreadLocalProxy # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import reload_module if sys.version_info[:2] >= (3, 5): import importlib.machinery # pylint: disable=no-name-in-module,import-error import importlib.util # pylint: disable=no-name-in-module,import-error USE_IMPORTLIB = True else: import imp USE_IMPORTLIB = False try: from collections.abc import MutableMapping except ImportError: from collections import MutableMapping try: import pkg_resources HAS_PKG_RESOURCES = True except ImportError: HAS_PKG_RESOURCES = False log = logging.getLogger(__name__) SALT_BASE_PATH = os.path.abspath(salt.syspaths.INSTALL_DIR) LOADED_BASE_NAME = 'salt.loaded' if USE_IMPORTLIB: # pylint: disable=no-member MODULE_KIND_SOURCE = 1 MODULE_KIND_COMPILED = 2 MODULE_KIND_EXTENSION = 3 MODULE_KIND_PKG_DIRECTORY = 5 SUFFIXES = [] for suffix in importlib.machinery.EXTENSION_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_EXTENSION)) for suffix in importlib.machinery.SOURCE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_SOURCE)) for suffix in importlib.machinery.BYTECODE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_COMPILED)) MODULE_KIND_MAP = { MODULE_KIND_SOURCE: importlib.machinery.SourceFileLoader, MODULE_KIND_COMPILED: importlib.machinery.SourcelessFileLoader, MODULE_KIND_EXTENSION: importlib.machinery.ExtensionFileLoader } # pylint: enable=no-member else: SUFFIXES = imp.get_suffixes() PY3_PRE_EXT = \ re.compile(r'\.cpython-{0}{1}(\.opt-[1-9])?'.format(*sys.version_info[:2])) # Because on the cloud drivers we do `from salt.cloud.libcloudfuncs import *` # which simplifies code readability, it adds some unsupported functions into # the driver's module scope. # We list un-supported functions here. These will be removed from the loaded. # TODO: remove the need for this cross-module code. Maybe use NotImplemented LIBCLOUD_FUNCS_NOT_SUPPORTED = ( 'parallels.avail_sizes', 'parallels.avail_locations', 'proxmox.avail_sizes', ) # Will be set to pyximport module at runtime if cython is enabled in config. pyximport = None def static_loader( opts, ext_type, tag, pack=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, filter_name=None, ): funcs = LazyLoader( _module_dirs( opts, ext_type, tag, int_type, ext_dirs, ext_type_dirs, base_path, ), opts, tag=tag, pack=pack, ) ret = {} funcs._load_all() if filter_name: funcs = FilterDictWrapper(funcs, filter_name) for key in funcs: ret[key] = funcs[key] return ret def _format_entrypoint_target(ep): ''' Makes a string describing the target of an EntryPoint object. Base strongly on EntryPoint.__str__(). ''' s = ep.module_name if ep.attrs: s += ':' + '.'.join(ep.attrs) return s def _module_dirs( opts, ext_type, tag=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, ): if tag is None: tag = ext_type sys_types = os.path.join(base_path or SALT_BASE_PATH, int_type or ext_type) ext_types = os.path.join(opts['extension_modules'], ext_type) ext_type_types = [] if ext_dirs: if ext_type_dirs is None: ext_type_dirs = '{0}_dirs'.format(tag) if ext_type_dirs in opts: ext_type_types.extend(opts[ext_type_dirs]) if HAS_PKG_RESOURCES and ext_type_dirs: for entry_point in pkg_resources.iter_entry_points('salt.loader', ext_type_dirs): try: loaded_entry_point = entry_point.load() for path in loaded_entry_point(): ext_type_types.append(path) except Exception as exc: log.error("Error getting module directories from %s: %s", _format_entrypoint_target(entry_point), exc) log.debug("Full backtrace for module directories error", exc_info=True) cli_module_dirs = [] # The dirs can be any module dir, or a in-tree _{ext_type} dir for _dir in opts.get('module_dirs', []): # Prepend to the list to match cli argument ordering maybe_dir = os.path.join(_dir, ext_type) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) continue maybe_dir = os.path.join(_dir, '_{0}'.format(ext_type)) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) return cli_module_dirs + ext_type_types + [ext_types, sys_types] def minion_mods( opts, context=None, utils=None, whitelist=None, initial_load=False, loaded_base_name=None, notify=False, static_modules=None, proxy=None): ''' Load execution modules Returns a dictionary of execution modules appropriate for the current system by evaluating the __virtual__() function in each module. :param dict opts: The Salt options dictionary :param dict context: A Salt context that should be made present inside generated modules in __context__ :param dict utils: Utility functions which should be made available to Salt modules in __utils__. See `utils_dirs` in salt.config for additional information about configuration. :param list whitelist: A list of modules which should be whitelisted. :param bool initial_load: Deprecated flag! Unused. :param str loaded_base_name: A string marker for the loaded base name. :param bool notify: Flag indicating that an event should be fired upon completion of module loading. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) __opts__['grains'] = __grains__ __utils__ = salt.loader.utils(__opts__) __salt__ = salt.loader.minion_mods(__opts__, utils=__utils__) __salt__['test.ping']() ''' # TODO Publish documentation for module whitelisting if not whitelist: whitelist = opts.get('whitelist_modules', None) ret = LazyLoader( _module_dirs(opts, 'modules', 'module'), opts, tag='module', pack={'__context__': context, '__utils__': utils, '__proxy__': proxy}, whitelist=whitelist, loaded_base_name=loaded_base_name, static_modules=static_modules, ) ret.pack['__salt__'] = ret # Load any provider overrides from the configuration file providers option # Note: Providers can be pkg, service, user or group - not to be confused # with cloud providers. providers = opts.get('providers', False) if providers and isinstance(providers, dict): for mod in providers: # sometimes providers opts is not to diverge modules but # for other configuration try: funcs = raw_mod(opts, providers[mod], ret) except TypeError: break else: if funcs: for func in funcs: f_key = '{0}{1}'.format(mod, func[func.rindex('.'):]) ret[f_key] = funcs[func] if notify: evt = salt.utils.event.get_event('minion', opts=opts, listen=False) evt.fire_event({'complete': True}, tag=salt.defaults.events.MINION_MOD_COMPLETE) return ret def raw_mod(opts, name, functions, mod='modules'): ''' Returns a single module loaded raw and bypassing the __virtual__ function .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') testmod = salt.loader.raw_mod(__opts__, 'test', None) testmod['test.ping']() ''' loader = LazyLoader( _module_dirs(opts, mod, 'module'), opts, tag='rawmodule', virtual_enable=False, pack={'__salt__': functions}, ) # if we don't have the module, return an empty dict if name not in loader.file_mapping: return {} loader._load_module(name) # load a single module (the one passed in) return dict(loader._dict) # return a copy of *just* the funcs for `name` def metaproxy(opts): ''' Return functions used in the meta proxy ''' return LazyLoader( _module_dirs(opts, 'metaproxy'), opts, tag='metaproxy' ) def matchers(opts): ''' Return the matcher services plugins ''' return LazyLoader( _module_dirs(opts, 'matchers'), opts, tag='matchers' ) def proxy(opts, functions=None, returners=None, whitelist=None, utils=None): ''' Returns the proxy module for this salt-proxy-minion ''' ret = LazyLoader( _module_dirs(opts, 'proxy'), opts, tag='proxy', pack={'__salt__': functions, '__ret__': returners, '__utils__': utils}, ) ret.pack['__proxy__'] = ret return ret def returners(opts, functions, whitelist=None, context=None, proxy=None): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'returners', 'returner'), opts, tag='returner', whitelist=whitelist, pack={'__salt__': functions, '__context__': context, '__proxy__': proxy or {}}, ) def utils(opts, whitelist=None, context=None, proxy=proxy): ''' Returns the utility modules ''' return LazyLoader( _module_dirs(opts, 'utils', ext_type_dirs='utils_dirs'), opts, tag='utils', whitelist=whitelist, pack={'__context__': context, '__proxy__': proxy or {}}, ) def pillars(opts, functions, context=None): ''' Returns the pillars modules ''' ret = LazyLoader(_module_dirs(opts, 'pillar'), opts, tag='pillar', pack={'__salt__': functions, '__context__': context, '__utils__': utils(opts)}) ret.pack['__ext_pillar__'] = ret return FilterDictWrapper(ret, '.ext_pillar') def tops(opts): ''' Returns the tops modules ''' if 'master_tops' not in opts: return {} whitelist = list(opts['master_tops'].keys()) ret = LazyLoader( _module_dirs(opts, 'tops', 'top'), opts, tag='top', whitelist=whitelist, ) return FilterDictWrapper(ret, '.top') def wheels(opts, whitelist=None, context=None): ''' Returns the wheels modules ''' if context is None: context = {} return LazyLoader( _module_dirs(opts, 'wheel'), opts, tag='wheel', whitelist=whitelist, pack={'__context__': context}, ) def outputters(opts): ''' Returns the outputters modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only outputters present in the keyspace ''' ret = LazyLoader( _module_dirs(opts, 'output', ext_type_dirs='outputter_dirs'), opts, tag='output', ) wrapped_ret = FilterDictWrapper(ret, '.output') # TODO: this name seems terrible... __salt__ should always be execution mods ret.pack['__salt__'] = wrapped_ret return wrapped_ret def serializers(opts): ''' Returns the serializers modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only serializers present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'serializers'), opts, tag='serializers', ) def eauth_tokens(opts): ''' Returns the tokens modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only token backends present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'tokens'), opts, tag='tokens', ) def auth(opts, whitelist=None): ''' Returns the auth modules :param dict opts: The Salt options dictionary :returns: LazyLoader ''' return LazyLoader( _module_dirs(opts, 'auth'), opts, tag='auth', whitelist=whitelist, pack={'__salt__': minion_mods(opts)}, ) def fileserver(opts, backends): ''' Returns the file server modules ''' return LazyLoader(_module_dirs(opts, 'fileserver'), opts, tag='fileserver', whitelist=backends, pack={'__utils__': utils(opts)}) def roster(opts, runner=None, utils=None, whitelist=None): ''' Returns the roster modules ''' return LazyLoader( _module_dirs(opts, 'roster'), opts, tag='roster', whitelist=whitelist, pack={ '__runner__': runner, '__utils__': utils, }, ) def thorium(opts, functions, runners): ''' Load the thorium runtime modules ''' pack = {'__salt__': functions, '__runner__': runners, '__context__': {}} ret = LazyLoader(_module_dirs(opts, 'thorium'), opts, tag='thorium', pack=pack) ret.pack['__thorium__'] = ret return ret def states(opts, functions, utils, serializers, whitelist=None, proxy=None, context=None): ''' Returns the state modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') statemods = salt.loader.states(__opts__, None, None) ''' if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'states'), opts, tag='states', pack={'__salt__': functions, '__proxy__': proxy or {}}, whitelist=whitelist, ) ret.pack['__states__'] = ret ret.pack['__utils__'] = utils ret.pack['__serializers__'] = serializers ret.pack['__context__'] = context return ret def beacons(opts, functions, context=None, proxy=None): ''' Load the beacon modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. ''' return LazyLoader( _module_dirs(opts, 'beacons'), opts, tag='beacons', pack={'__context__': context, '__salt__': functions, '__proxy__': proxy or {}}, virtual_funcs=[], ) def log_handlers(opts): ''' Returns the custom logging handler modules :param dict opts: The Salt options dictionary ''' ret = LazyLoader( _module_dirs( opts, 'log_handlers', int_type='handlers', base_path=os.path.join(SALT_BASE_PATH, 'log'), ), opts, tag='log_handlers', ) return FilterDictWrapper(ret, '.setup_handlers') def ssh_wrapper(opts, functions=None, context=None): ''' Returns the custom logging handler modules ''' return LazyLoader( _module_dirs( opts, 'wrapper', base_path=os.path.join(SALT_BASE_PATH, os.path.join('client', 'ssh')), ), opts, tag='wrapper', pack={ '__salt__': functions, '__grains__': opts.get('grains', {}), '__pillar__': opts.get('pillar', {}), '__context__': context, }, ) def render(opts, functions, states=None, proxy=None, context=None): ''' Returns the render modules ''' if context is None: context = {} pack = {'__salt__': functions, '__grains__': opts.get('grains', {}), '__context__': context} if states: pack['__states__'] = states pack['__proxy__'] = proxy or {} ret = LazyLoader( _module_dirs( opts, 'renderers', 'render', ext_type_dirs='render_dirs', ), opts, tag='render', pack=pack, ) rend = FilterDictWrapper(ret, '.render') if not check_render_pipe_str(opts['renderer'], rend, opts['renderer_blacklist'], opts['renderer_whitelist']): err = ('The renderer {0} is unavailable, this error is often because ' 'the needed software is unavailable'.format(opts['renderer'])) log.critical(err) raise LoaderError(err) return rend def grain_funcs(opts, proxy=None): ''' Returns the grain functions .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') grainfuncs = salt.loader.grain_funcs(__opts__) ''' ret = LazyLoader( _module_dirs( opts, 'grains', 'grain', ext_type_dirs='grains_dirs', ), opts, tag='grains', ) ret.pack['__utils__'] = utils(opts, proxy=proxy) return ret def _load_cached_grains(opts, cfn): ''' Returns the grains cached in cfn, or None if the cache is too old or is corrupted. ''' if not os.path.isfile(cfn): log.debug('Grains cache file does not exist.') return None grains_cache_age = int(time.time() - os.path.getmtime(cfn)) if grains_cache_age > opts.get('grains_cache_expiration', 300): log.debug( 'Grains cache last modified %s seconds ago and cache ' 'expiration is set to %s. Grains cache expired. ' 'Refreshing.', grains_cache_age, opts.get('grains_cache_expiration', 300) ) return None if opts.get('refresh_grains_cache', False): log.debug('refresh_grains_cache requested, Refreshing.') return None log.debug('Retrieving grains from cache') try: serial = salt.payload.Serial(opts) with salt.utils.files.fopen(cfn, 'rb') as fp_: cached_grains = salt.utils.data.decode(serial.load(fp_), preserve_tuples=True) if not cached_grains: log.debug('Cached grains are empty, cache might be corrupted. Refreshing.') return None return cached_grains except (IOError, OSError): return None def grains(opts, force_refresh=False, proxy=None): ''' Return the functions for the dynamic grains and the values for the static grains. Since grains are computed early in the startup process, grains functions do not have __salt__ or __proxy__ available. At proxy-minion startup, this function is called with the proxymodule LazyLoader object so grains functions can communicate with their controlled device. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) print __grains__['id'] ''' # Need to re-import salt.config, somehow it got lost when a minion is starting import salt.config # if we have no grains, lets try loading from disk (TODO: move to decorator?) cfn = os.path.join( opts['cachedir'], 'grains.cache.p' ) if not force_refresh and opts.get('grains_cache', False): cached_grains = _load_cached_grains(opts, cfn) if cached_grains: return cached_grains else: log.debug('Grains refresh requested. Refreshing grains.') if opts.get('skip_grains', False): return {} grains_deep_merge = opts.get('grains_deep_merge', False) is True if 'conf_file' in opts: pre_opts = {} pre_opts.update(salt.config.load_config( opts['conf_file'], 'SALT_MINION_CONFIG', salt.config.DEFAULT_MINION_OPTS['conf_file'] )) default_include = pre_opts.get( 'default_include', opts['default_include'] ) include = pre_opts.get('include', []) pre_opts.update(salt.config.include_config( default_include, opts['conf_file'], verbose=False )) pre_opts.update(salt.config.include_config( include, opts['conf_file'], verbose=True )) if 'grains' in pre_opts: opts['grains'] = pre_opts['grains'] else: opts['grains'] = {} else: opts['grains'] = {} grains_data = {} blist = opts.get('grains_blacklist', []) funcs = grain_funcs(opts, proxy=proxy) if force_refresh: # if we refresh, lets reload grain modules funcs.clear() # Run core grains for key in funcs: if not key.startswith('core.'): continue log.trace('Loading %s grain', key) ret = funcs[key]() if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) # Run the rest of the grains for key in funcs: if key.startswith('core.') or key == '_errors': continue try: # Grains are loaded too early to take advantage of the injected # __proxy__ variable. Pass an instance of that LazyLoader # here instead to grains functions if the grains functions take # one parameter. Then the grains can have access to the # proxymodule for retrieving information from the connected # device. log.trace('Loading %s grain', key) parameters = salt.utils.args.get_function_argspec(funcs[key]).args kwargs = {} if 'proxy' in parameters: kwargs['proxy'] = proxy if 'grains' in parameters: kwargs['grains'] = grains_data ret = funcs[key](**kwargs) except Exception: if salt.utils.platform.is_proxy(): log.info('The following CRITICAL message may not be an error; the proxy may not be completely established yet.') log.critical( 'Failed to load grains defined in grain file %s in ' 'function %s, error:\n', key, funcs[key], exc_info=True ) continue if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) if opts.get('proxy_merge_grains_in_module', True) and proxy: try: proxytype = proxy.opts['proxy']['proxytype'] if proxytype + '.grains' in proxy: if proxytype + '.initialized' in proxy and proxy[proxytype + '.initialized'](): try: proxytype = proxy.opts['proxy']['proxytype'] ret = proxy[proxytype + '.grains']() if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) except Exception: log.critical('Failed to run proxy\'s grains function!', exc_info=True ) except KeyError: pass grains_data.update(opts['grains']) # Write cache if enabled if opts.get('grains_cache', False): with salt.utils.files.set_umask(0o077): try: if salt.utils.platform.is_windows(): # Late import import salt.modules.cmdmod # Make sure cache file isn't read-only salt.modules.cmdmod._run_quiet('attrib -R "{0}"'.format(cfn)) with salt.utils.files.fopen(cfn, 'w+b') as fp_: try: serial = salt.payload.Serial(opts) serial.dump(grains_data, fp_) except TypeError as e: log.error('Failed to serialize grains cache: %s', e) raise # re-throw for cleanup except Exception as e: log.error('Unable to write to grains cache file %s: %s', cfn, e) # Based on the original exception, the file may or may not have been # created. If it was, we will remove it now, as the exception means # the serialized data is not to be trusted, no matter what the # exception is. if os.path.isfile(cfn): os.unlink(cfn) if grains_deep_merge: salt.utils.dictupdate.update(grains_data, opts['grains']) else: grains_data.update(opts['grains']) return salt.utils.data.decode(grains_data, preserve_tuples=True) # TODO: get rid of? Does anyone use this? You should use raw() instead def call(fun, **kwargs): ''' Directly call a function inside a loader directory ''' args = kwargs.get('args', []) dirs = kwargs.get('dirs', []) funcs = LazyLoader( [os.path.join(SALT_BASE_PATH, 'modules')] + dirs, None, tag='modules', virtual_enable=False, ) return funcs[fun](*args) def runner(opts, utils=None, context=None, whitelist=None): ''' Directly call a function inside a loader directory ''' if utils is None: utils = {} if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'runners', 'runner', ext_type_dirs='runner_dirs'), opts, tag='runners', pack={'__utils__': utils, '__context__': context}, whitelist=whitelist, ) # TODO: change from __salt__ to something else, we overload __salt__ too much ret.pack['__salt__'] = ret return ret def queues(opts): ''' Directly call a function inside a loader directory ''' return LazyLoader( _module_dirs(opts, 'queues', 'queue', ext_type_dirs='queue_dirs'), opts, tag='queues', ) def sdb(opts, functions=None, whitelist=None, utils=None): ''' Make a very small database call ''' if utils is None: utils = {} return LazyLoader( _module_dirs(opts, 'sdb'), opts, tag='sdb', pack={ '__sdb__': functions, '__opts__': opts, '__utils__': utils, '__salt__': minion_mods(opts, utils), }, whitelist=whitelist, ) def pkgdb(opts): ''' Return modules for SPM's package database .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgdb', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgdb' ) def pkgfiles(opts): ''' Return modules for SPM's file handling .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgfiles', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgfiles' ) def clouds(opts): ''' Return the cloud functions ''' # Let's bring __active_provider_name__, defaulting to None, to all cloud # drivers. This will get temporarily updated/overridden with a context # manager when needed. functions = LazyLoader( _module_dirs(opts, 'clouds', 'cloud', base_path=os.path.join(SALT_BASE_PATH, 'cloud'), int_type='clouds'), opts, tag='clouds', pack={'__utils__': salt.loader.utils(opts), '__active_provider_name__': None}, ) for funcname in LIBCLOUD_FUNCS_NOT_SUPPORTED: log.trace( '\'%s\' has been marked as not supported. Removing from the ' 'list of supported cloud functions', funcname ) functions.pop(funcname, None) return functions def netapi(opts): ''' Return the network api functions ''' return LazyLoader( _module_dirs(opts, 'netapi'), opts, tag='netapi', ) def executors(opts, functions=None, context=None, proxy=None): ''' Returns the executor modules ''' executors = LazyLoader( _module_dirs(opts, 'executors', 'executor'), opts, tag='executor', pack={'__salt__': functions, '__context__': context or {}, '__proxy__': proxy or {}}, ) executors.pack['__executors__'] = executors return executors def cache(opts, serial): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'cache', 'cache'), opts, tag='cache', pack={'__opts__': opts, '__context__': {'serial': serial}}, ) def _generate_module(name): if name in sys.modules: return code = "'''Salt loaded {0} parent module'''".format(name.split('.')[-1]) # ModuleType can't accept a unicode type on PY2 module = types.ModuleType(str(name)) # future lint: disable=blacklisted-function exec(code, module.__dict__) sys.modules[name] = module def _mod_type(module_path): if module_path.startswith(SALT_BASE_PATH): return 'int' return 'ext' def _inject_into_mod(mod, name, value, force_lock=False): ''' Inject a variable into a module. This is used to inject "globals" like ``__salt__``, ``__pillar``, or ``grains``. Instead of injecting the value directly, a ``ThreadLocalProxy`` is created. If such a proxy is already present under the specified name, it is updated with the new value. This update only affects the current thread, so that the same name can refer to different values depending on the thread of execution. This is important for data that is not truly global. For example, pillar data might be dynamically overriden through function parameters and thus the actual values available in pillar might depend on the thread that is calling a module. mod: module object into which the value is going to be injected. name: name of the variable that is injected into the module. value: value that is injected into the variable. The value is not injected directly, but instead set as the new reference of the proxy that has been created for the variable. force_lock: whether the lock should be acquired before checking whether a proxy object for the specified name has already been injected into the module. If ``False`` (the default), this function checks for the module's variable without acquiring the lock and only acquires the lock if a new proxy has to be created and injected. ''' old_value = getattr(mod, name, None) # We use a double-checked locking scheme in order to avoid taking the lock # when a proxy object has already been injected. # In most programming languages, double-checked locking is considered # unsafe when used without explicit memory barriers because one might read # an uninitialized value. In CPython it is safe due to the global # interpreter lock (GIL). In Python implementations that do not have the # GIL, it could be unsafe, but at least Jython also guarantees that (for # Python objects) memory is not corrupted when writing and reading without # explicit synchronization # (http://www.jython.org/jythonbook/en/1.0/Concurrency.html). # Please note that in order to make this code safe in a runtime environment # that does not make this guarantees, it is not sufficient. The # ThreadLocalProxy must also be created with fallback_to_shared set to # False or a lock must be added to the ThreadLocalProxy. if force_lock: with _inject_into_mod.lock: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: setattr(mod, name, ThreadLocalProxy(value, True)) else: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: _inject_into_mod(mod, name, value, True) # Lock used when injecting globals. This is needed to avoid a race condition # when two threads try to load the same module concurrently. This must be # outside the loader because there might be more than one loader for the same # namespace. _inject_into_mod.lock = threading.RLock() # TODO: move somewhere else? class FilterDictWrapper(MutableMapping): ''' Create a dict which wraps another dict with a specific key suffix on get This is to replace "filter_load" ''' def __init__(self, d, suffix): self._dict = d self.suffix = suffix def __setitem__(self, key, val): self._dict[key] = val def __delitem__(self, key): del self._dict[key] def __getitem__(self, key): return self._dict[key + self.suffix] def __len__(self): return len(self._dict) def __iter__(self): for key in self._dict: if key.endswith(self.suffix): yield key.replace(self.suffix, '') class LazyLoader(salt.utils.lazy.LazyDict): ''' A pseduo-dictionary which has a set of keys which are the name of the module and function, delimited by a dot. When the value of the key is accessed, the function is then loaded from disk and into memory. .. note:: Iterating over keys will cause all modules to be loaded. :param list module_dirs: A list of directories on disk to search for modules :param dict opts: The salt options dictionary. :param str tag: The tag for the type of module to load :param func mod_type_check: A function which can be used to verify files :param dict pack: A dictionary of function to be packed into modules as they are loaded :param list whitelist: A list of modules to whitelist :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules. :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality. If not true, the module will not load. :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values are function references themselves which are loaded on-demand. # TODO: - move modules_max_memory into here - singletons (per tag) ''' mod_dict_class = salt.utils.odict.OrderedDict def __init__(self, module_dirs, opts=None, tag='module', loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, proxy=None, virtual_funcs=None, ): # pylint: disable=W0231 ''' In pack, if any of the values are None they will be replaced with an empty context-specific dict ''' self.inject_globals = {} self.pack = {} if pack is None else pack if opts is None: opts = {} threadsafety = not opts.get('multiprocessing') self.context_dict = salt.utils.context.ContextDict(threadsafe=threadsafety) self.opts = self.__prep_mod_opts(opts) self.module_dirs = module_dirs self.tag = tag self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME self.mod_type_check = mod_type_check or _mod_type if '__context__' not in self.pack: self.pack['__context__'] = None for k, v in six.iteritems(self.pack): if v is None: # if the value of a pack is None, lets make an empty dict value = self.context_dict.get(k, {}) if isinstance(value, ThreadLocalProxy): value = ThreadLocalProxy.unproxy(value) self.context_dict[k] = value self.pack[k] = salt.utils.context.NamespacedDictWrapper(self.context_dict, k) self.whitelist = whitelist self.virtual_enable = virtual_enable self.initial_load = True # names of modules that we don't have (errors, __virtual__, etc.) self.missing_modules = {} # mapping of name -> error self.loaded_modules = {} # mapping of module_name -> dict_of_functions self.loaded_files = set() # TODO: just remove them from file_mapping? self.static_modules = static_modules if static_modules else [] if virtual_funcs is None: virtual_funcs = [] self.virtual_funcs = virtual_funcs self.disabled = set( self.opts.get( 'disable_{0}{1}'.format( self.tag, '' if self.tag[-1] == 's' else 's' ), [] ) ) # A map of suffix to description for imp self.suffix_map = {} # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [''] for (suffix, mode, kind) in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) self._lock = threading.RLock() self._refresh_file_mapping() super(LazyLoader, self).__init__() # late init the lazy loader # create all of the import namespaces _generate_module('{0}.int'.format(self.loaded_base_name)) _generate_module('{0}.int.{1}'.format(self.loaded_base_name, tag)) _generate_module('{0}.ext'.format(self.loaded_base_name)) _generate_module('{0}.ext.{1}'.format(self.loaded_base_name, tag)) def __getitem__(self, item): ''' Override the __getitem__ in order to decorate the returned function if we need to last-minute inject globals ''' func = super(LazyLoader, self).__getitem__(item) if self.inject_globals: return global_injector_decorator(self.inject_globals)(func) else: return func def __getattr__(self, mod_name): ''' Allow for "direct" attribute access-- this allows jinja templates to access things like `salt.test.ping()` ''' if mod_name in ('__getstate__', '__setstate__'): return object.__getattribute__(self, mod_name) # if we have an attribute named that, lets return it. try: return object.__getattr__(self, mod_name) # pylint: disable=no-member except AttributeError: pass # otherwise we assume its jinja template access if mod_name not in self.loaded_modules and not self.loaded: for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and mod_name in self.loaded_modules: break if mod_name in self.loaded_modules: return self.loaded_modules[mod_name] else: raise AttributeError(mod_name) def missing_fun_string(self, function_name): ''' Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ''' mod_name = function_name.split('.')[0] if mod_name in self.loaded_modules: return '\'{0}\' is not available.'.format(function_name) else: try: reason = self.missing_modules[mod_name] except KeyError: return '\'{0}\' is not available.'.format(function_name) else: if reason is not None: return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason) else: return '\'{0}\' __virtual__ returned False'.format(mod_name) def _refresh_file_mapping(self): ''' refresh the mapping of the FS on disk ''' # map of suffix to description for imp if self.opts.get('cython_enable', True) is True: try: global pyximport pyximport = __import__('pyximport') # pylint: disable=import-error pyximport.install() # add to suffix_map so file_mapping will pick it up self.suffix_map['.pyx'] = tuple() except ImportError: log.info('Cython is enabled in the options but not present ' 'in the system path. Skipping Cython modules.') # Allow for zipimport of modules if self.opts.get('enable_zip_modules', True) is True: self.suffix_map['.zip'] = tuple() # allow for module dirs if USE_IMPORTLIB: self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY) else: self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY) # create mapping of filename (without suffix) to (path, suffix) # The files are added in order of priority, so order *must* be retained. self.file_mapping = salt.utils.odict.OrderedDict() opt_match = [] def _replace_pre_ext(obj): ''' Hack so we can get the optimization level that we replaced (if any) out of the re.sub call below. We use a list here because it is a persistent data structure that we will be able to access after re.sub is called. ''' opt_match.append(obj) return '' for mod_dir in self.module_dirs: try: # Make sure we have a sorted listdir in order to have # expectable override results files = sorted( x for x in os.listdir(mod_dir) if x != '__pycache__' ) except OSError: continue # Next mod_dir if six.PY3: try: pycache_files = [ os.path.join('__pycache__', x) for x in sorted(os.listdir(os.path.join(mod_dir, '__pycache__'))) ] except OSError: pass else: files.extend(pycache_files) for filename in files: try: dirname, basename = os.path.split(filename) if basename.startswith('_'): # skip private modules # log messages omitted for obviousness continue # Next filename f_noext, ext = os.path.splitext(basename) if six.PY3: f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext) try: opt_level = int( opt_match.pop().group(1).rsplit('-', 1)[-1] ) except (AttributeError, IndexError, ValueError): # No regex match or no optimization level matched opt_level = 0 try: opt_index = self.opts['optimization_order'].index(opt_level) except KeyError: log.trace( 'Disallowed optimization level %d for module ' 'name \'%s\', skipping. Add %d to the ' '\'optimization_order\' config option if you ' 'do not want to ignore this optimization ' 'level.', opt_level, f_noext, opt_level ) continue else: # Optimization level not reflected in filename on PY2 opt_index = 0 # make sure it is a suffix we support if ext not in self.suffix_map: continue # Next filename if f_noext in self.disabled: log.trace( 'Skipping %s, it is disabled by configuration', filename ) continue # Next filename fpath = os.path.join(mod_dir, filename) # if its a directory, lets allow us to load that if ext == '': # is there something __init__? subfiles = os.listdir(fpath) for suffix in self.suffix_order: if '' == suffix: continue # Next suffix (__init__ must have a suffix) init_file = '__init__{0}'.format(suffix) if init_file in subfiles: break else: continue # Next filename try: curr_ext = self.file_mapping[f_noext][1] curr_opt_index = self.file_mapping[f_noext][2] except KeyError: pass else: if '' in (curr_ext, ext) and curr_ext != ext: log.error( 'Module/package collision: \'%s\' and \'%s\'', fpath, self.file_mapping[f_noext][0] ) if six.PY3 and ext == '.pyc' and curr_ext == '.pyc': # Check the optimization level if opt_index >= curr_opt_index: # Module name match, but a higher-priority # optimization level was already matched, skipping. continue elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext): # Match found but a higher-priorty match already # exists, so skip this. continue if six.PY3 and not dirname and ext == '.pyc': # On Python 3, we should only load .pyc files from the # __pycache__ subdirectory (i.e. when dirname is not an # empty string). continue # Made it this far - add it self.file_mapping[f_noext] = (fpath, ext, opt_index) except OSError: continue for smod in self.static_modules: f_noext = smod.split('.')[-1] self.file_mapping[f_noext] = (smod, '.o', 0) def clear(self): ''' Clear the dict ''' with self._lock: super(LazyLoader, self).clear() # clear the lazy loader self.loaded_files = set() self.missing_modules = {} self.loaded_modules = {} # if we have been loaded before, lets clear the file mapping since # we obviously want a re-do if hasattr(self, 'opts'): self._refresh_file_mapping() self.initial_load = False def __prep_mod_opts(self, opts): ''' Strip out of the opts any logger instance ''' if '__grains__' not in self.pack: grains = opts.get('grains', {}) if isinstance(grains, ThreadLocalProxy): grains = ThreadLocalProxy.unproxy(grains) self.context_dict['grains'] = grains self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains') if '__pillar__' not in self.pack: pillar = opts.get('pillar', {}) if isinstance(pillar, ThreadLocalProxy): pillar = ThreadLocalProxy.unproxy(pillar) self.context_dict['pillar'] = pillar self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar') mod_opts = {} for key, val in list(opts.items()): if key == 'logger': continue mod_opts[key] = val return mod_opts def _iter_files(self, mod_name): ''' Iterate over all file_mapping files in order of closeness to mod_name ''' # do we have an exact match? if mod_name in self.file_mapping: yield mod_name # do we have a partial match? for k in self.file_mapping: if mod_name in k: yield k # anyone else? Bueller? for k in self.file_mapping: if mod_name not in k: yield k def _reload_submodules(self, mod): submodules = ( getattr(mod, sname) for sname in dir(mod) if isinstance(getattr(mod, sname), mod.__class__) ) # reload only custom "sub"modules for submodule in submodules: # it is a submodule if the name is in a namespace under mod if submodule.__name__.startswith(mod.__name__ + '.'): reload_module(submodule) self._reload_submodules(submodule) def _load_module(self, name): mod = None fpath, suffix = self.file_mapping[name][:2] self.loaded_files.add(name) fpath_dirname = os.path.dirname(fpath) try: sys.path.append(fpath_dirname) if suffix == '.pyx': mod = pyximport.load_module(name, fpath, tempfile.gettempdir()) elif suffix == '.o': top_mod = __import__(fpath, globals(), locals(), []) comps = fpath.split('.') if len(comps) < 2: mod = top_mod else: mod = top_mod for subname in comps[1:]: mod = getattr(mod, subname) elif suffix == '.zip': mod = zipimporter(fpath).load_module(name) else: desc = self.suffix_map[suffix] # if it is a directory, we don't open a file try: mod_namespace = '.'.join(( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name)) except TypeError: mod_namespace = '{0}.{1}.{2}.{3}'.format( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name) if suffix == '': if USE_IMPORTLIB: # pylint: disable=no-member # Package directory, look for __init__ loader_details = [ (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES), (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES), (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), ] file_finder = importlib.machinery.FileFinder( fpath_dirname, *loader_details ) spec = file_finder.find_spec(mod_namespace) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: mod = imp.load_module(mod_namespace, None, fpath, desc) # reload all submodules if necessary if not self.initial_load: self._reload_submodules(mod) else: if USE_IMPORTLIB: # pylint: disable=no-member loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath) spec = importlib.util.spec_from_file_location( mod_namespace, fpath, loader=loader ) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() #mod = importlib.util.module_from_spec(spec) #spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: with salt.utils.files.fopen(fpath, desc[1]) as fn_: mod = imp.load_module(mod_namespace, fn_, fpath, desc) except IOError: raise except ImportError as exc: if 'magic number' in six.text_type(exc): error_msg = 'Failed to import {0} {1}. Bad magic number. If migrating from Python2 to Python3, remove all .pyc files and try again.'.format(self.tag, name) log.warning(error_msg) self.missing_modules[name] = error_msg log.debug( 'Failed to import %s %s:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = exc return False except Exception as error: log.error( 'Failed to import %s %s, this is due most likely to a ' 'syntax error:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False except SystemExit as error: try: fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1] except Exception: pass else: tgt_fn = os.path.join('salt', 'utils', 'process.py') if fn_.endswith(tgt_fn) and '_handle_signals' in caller: # Race conditon, SIGTERM or SIGINT received while loader # was in process of loading a module. Call sys.exit to # ensure that the process is killed. sys.exit(salt.defaults.exitcodes.EX_OK) log.error( 'Failed to import %s %s as the module called exit()\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False finally: sys.path.remove(fpath_dirname) if hasattr(mod, '__opts__'): mod.__opts__.update(self.opts) else: mod.__opts__ = self.opts # pack whatever other globals we were asked to for p_name, p_value in six.iteritems(self.pack): _inject_into_mod(mod, p_name, p_value) module_name = mod.__name__.rsplit('.', 1)[-1] # Call a module's initialization method if it exists module_init = getattr(mod, '__init__', None) if inspect.isfunction(module_init): try: module_init(self.opts) except TypeError as e: log.error(e) except Exception: err_string = '__init__ failed' log.debug( 'Error loading %s.%s: %s', self.tag, module_name, err_string, exc_info=True ) self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False # if virtual modules are enabled, we need to look for the # __virtual__() function inside that module and run it. if self.virtual_enable: virtual_funcs_to_process = ['__virtual__'] + self.virtual_funcs for virtual_func in virtual_funcs_to_process: virtual_ret, module_name, virtual_err, virtual_aliases = \ self._process_virtual(mod, module_name, virtual_func) if virtual_err is not None: log.trace( 'Error loading %s.%s: %s', self.tag, module_name, virtual_err ) # if _process_virtual returned a non-True value then we are # supposed to not process this module if virtual_ret is not True and module_name not in self.missing_modules: # If a module has information about why it could not be loaded, record it self.missing_modules[module_name] = virtual_err self.missing_modules[name] = virtual_err return False else: virtual_aliases = () # If this is a proxy minion then MOST modules cannot work. Therefore, require that # any module that does work with salt-proxy-minion define __proxyenabled__ as a list # containing the names of the proxy types that the module supports. # # Render modules and state modules are OK though if 'proxy' in self.opts: if self.tag in ['grains', 'proxy']: if not hasattr(mod, '__proxyenabled__') or \ (self.opts['proxy']['proxytype'] not in mod.__proxyenabled__ and '*' not in mod.__proxyenabled__): err_string = 'not a proxy_minion enabled module' self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False if getattr(mod, '__load__', False) is not False: log.info( 'The functions from module \'%s\' are being loaded from the ' 'provided __load__ attribute', module_name ) # If we had another module by the same virtual name, we should put any # new functions under the existing dictionary. mod_names = [module_name] + list(virtual_aliases) mod_dict = dict(( (x, self.loaded_modules.get(x, self.mod_dict_class())) for x in mod_names )) for attr in getattr(mod, '__load__', dir(mod)): if attr.startswith('_') and attr != '__call__': # private functions are skipped, # except __call__ which is default entrance # for multi-function batch-like state syntax continue func = getattr(mod, attr) if not inspect.isfunction(func) and not isinstance(func, functools.partial): # Not a function!? Skip it!!! continue # Let's get the function name. # If the module has the __func_alias__ attribute, it must be a # dictionary mapping in the form of(key -> value): # <real-func-name> -> <desired-func-name> # # It default's of course to the found callable attribute name # if no alias is defined. funcname = getattr(mod, '__func_alias__', {}).get(attr, attr) for tgt_mod in mod_names: try: full_funcname = '.'.join((tgt_mod, funcname)) except TypeError: full_funcname = '{0}.{1}'.format(tgt_mod, funcname) # Save many references for lookups # Careful not to overwrite existing (higher priority) functions if full_funcname not in self._dict: self._dict[full_funcname] = func if funcname not in mod_dict[tgt_mod]: setattr(mod_dict[tgt_mod], funcname, func) mod_dict[tgt_mod][funcname] = func self._apply_outputter(func, mod) # enforce depends try: Depends.enforce_dependencies(self._dict, self.tag) except RuntimeError as exc: log.info( 'Depends.enforce_dependencies() failed for the following ' 'reason: %s', exc ) for tgt_mod in mod_names: self.loaded_modules[tgt_mod] = mod_dict[tgt_mod] return True def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise KeyError('The key \'{0}\' should contain a \'.\''.format(key)) mod_name, _ = key.split('.', 1) with self._lock: # It is possible that the key is in the dictionary after # acquiring the lock due to another thread loading it. if mod_name in self.missing_modules or key in self._dict: return True # if the modulename isn't in the whitelist, don't bother if self.whitelist and mod_name not in self.whitelist: log.error( 'Failed to load function %s because its module (%s) is ' 'not in the whitelist: %s', key, mod_name, self.whitelist ) raise KeyError(key) def _inner_load(mod_name): for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and key in self._dict: return True return False # try to load the module ret = None reloaded = False # re-scan up to once, IOErrors or a failed load cause re-scans of the # filesystem while True: try: ret = _inner_load(mod_name) if not reloaded and ret is not True: self._refresh_file_mapping() reloaded = True continue break except IOError: if not reloaded: self._refresh_file_mapping() reloaded = True continue return ret def _load_all(self): ''' Load all of them ''' with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True def reload_modules(self): with self._lock: self.loaded_files = set() self._load_all() def _apply_outputter(self, func, mod): ''' Apply the __outputter__ variable to the functions ''' if hasattr(mod, '__outputter__'): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__] def _process_virtual(self, mod, module_name, virtual_func='__virtual__'): ''' Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1] ''' # The __virtual__ function will return either a True or False value. # If it returns a True value it can also set a module level attribute # named __virtualname__ with the name that the module should be # referred to as. # # This allows us to have things like the pkg module working on all # platforms under the name 'pkg'. It also allows for modules like # augeas_cfg to be referred to as 'augeas', which would otherwise have # namespace collisions. And finally it allows modules to return False # if they are not intended to run on the given platform or are missing # dependencies. virtual_aliases = getattr(mod, '__virtual_aliases__', tuple()) try: error_reason = None if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__): try: start = time.time() virtual = getattr(mod, virtual_func)() if isinstance(virtual, tuple): error_reason = virtual[1] virtual = virtual[0] if self.opts.get('virtual_timer', False): end = time.time() - start msg = 'Virtual function took {0} seconds for {1}'.format( end, module_name) log.warning(msg) except Exception as exc: error_reason = ( 'Exception raised when processing __virtual__ function' ' for {0}. Module will not be loaded: {1}'.format( mod.__name__, exc)) log.error(error_reason, exc_info_on_loglevel=logging.DEBUG) virtual = None # Get the module's virtual name virtualname = getattr(mod, '__virtualname__', virtual) if not virtual: # if __virtual__() evaluates to False then the module # wasn't meant for this platform or it's not supposed to # load for some other reason. # Some modules might accidentally return None and are # improperly loaded if virtual is None: log.warning( '%s.__virtual__() is wrongly returning `None`. ' 'It should either return `True`, `False` or a new ' 'name. If you\'re the developer of the module ' '\'%s\', please fix this.', mod.__name__, module_name ) return (False, module_name, error_reason, virtual_aliases) # At this point, __virtual__ did not return a # boolean value, let's check for deprecated usage # or module renames if virtual is not True and module_name != virtual: # The module is renaming itself. Updating the module name # with the new name log.trace('Loaded %s as virtual %s', module_name, virtual) if virtualname != virtual: # The __virtualname__ attribute does not match what's # being returned by the __virtual__() function. This # should be considered an error. log.error( 'The module \'%s\' is showing some bad usage. Its ' '__virtualname__ attribute is set to \'%s\' yet the ' '__virtual__() function is returning \'%s\'. These ' 'values should match!', mod.__name__, virtualname, virtual ) module_name = virtualname # If the __virtual__ function returns True and __virtualname__ # is set then use it elif virtual is True and virtualname != module_name: if virtualname is not True: module_name = virtualname except KeyError: # Key errors come out of the virtual function when passing # in incomplete grains sets, these can be safely ignored # and logged to debug, still, it includes the traceback to # help debugging. log.debug('KeyError when loading %s', module_name, exc_info=True) except Exception: # If the module throws an exception during __virtual__() # then log the information and continue to the next. log.error( 'Failed to read the virtual function for %s: %s', self.tag, module_name, exc_info=True ) return (False, module_name, error_reason, virtual_aliases) return (True, module_name, None, virtual_aliases) def global_injector_decorator(inject_globals): ''' Decorator used by the LazyLoader to inject globals into a function at execute time. globals Dictionary with global variables to inject ''' def inner_decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): with salt.utils.context.func_globals_inject(f, **inject_globals): return f(*args, **kwargs) return wrapper return inner_decorator
saltstack/salt
salt/loader.py
proxy
python
def proxy(opts, functions=None, returners=None, whitelist=None, utils=None): ''' Returns the proxy module for this salt-proxy-minion ''' ret = LazyLoader( _module_dirs(opts, 'proxy'), opts, tag='proxy', pack={'__salt__': functions, '__ret__': returners, '__utils__': utils}, ) ret.pack['__proxy__'] = ret return ret
Returns the proxy module for this salt-proxy-minion
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L357-L370
null
# -*- coding: utf-8 -*- ''' The Salt loader is the core to Salt's plugin system, the loader scans directories for python loadable code and organizes the code into the plugin interfaces used by Salt. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import sys import time import logging import inspect import tempfile import threading import functools import threading import traceback import types from zipimport import zipimporter # Import salt libs import salt.config import salt.defaults.events import salt.defaults.exitcodes import salt.syspaths import salt.utils.args import salt.utils.context import salt.utils.data import salt.utils.dictupdate import salt.utils.event import salt.utils.files import salt.utils.lazy import salt.utils.odict import salt.utils.platform import salt.utils.versions import salt.utils.stringutils from salt.exceptions import LoaderError from salt.template import check_render_pipe_str from salt.utils.decorators import Depends from salt.utils.thread_local_proxy import ThreadLocalProxy # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import reload_module if sys.version_info[:2] >= (3, 5): import importlib.machinery # pylint: disable=no-name-in-module,import-error import importlib.util # pylint: disable=no-name-in-module,import-error USE_IMPORTLIB = True else: import imp USE_IMPORTLIB = False try: from collections.abc import MutableMapping except ImportError: from collections import MutableMapping try: import pkg_resources HAS_PKG_RESOURCES = True except ImportError: HAS_PKG_RESOURCES = False log = logging.getLogger(__name__) SALT_BASE_PATH = os.path.abspath(salt.syspaths.INSTALL_DIR) LOADED_BASE_NAME = 'salt.loaded' if USE_IMPORTLIB: # pylint: disable=no-member MODULE_KIND_SOURCE = 1 MODULE_KIND_COMPILED = 2 MODULE_KIND_EXTENSION = 3 MODULE_KIND_PKG_DIRECTORY = 5 SUFFIXES = [] for suffix in importlib.machinery.EXTENSION_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_EXTENSION)) for suffix in importlib.machinery.SOURCE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_SOURCE)) for suffix in importlib.machinery.BYTECODE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_COMPILED)) MODULE_KIND_MAP = { MODULE_KIND_SOURCE: importlib.machinery.SourceFileLoader, MODULE_KIND_COMPILED: importlib.machinery.SourcelessFileLoader, MODULE_KIND_EXTENSION: importlib.machinery.ExtensionFileLoader } # pylint: enable=no-member else: SUFFIXES = imp.get_suffixes() PY3_PRE_EXT = \ re.compile(r'\.cpython-{0}{1}(\.opt-[1-9])?'.format(*sys.version_info[:2])) # Because on the cloud drivers we do `from salt.cloud.libcloudfuncs import *` # which simplifies code readability, it adds some unsupported functions into # the driver's module scope. # We list un-supported functions here. These will be removed from the loaded. # TODO: remove the need for this cross-module code. Maybe use NotImplemented LIBCLOUD_FUNCS_NOT_SUPPORTED = ( 'parallels.avail_sizes', 'parallels.avail_locations', 'proxmox.avail_sizes', ) # Will be set to pyximport module at runtime if cython is enabled in config. pyximport = None def static_loader( opts, ext_type, tag, pack=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, filter_name=None, ): funcs = LazyLoader( _module_dirs( opts, ext_type, tag, int_type, ext_dirs, ext_type_dirs, base_path, ), opts, tag=tag, pack=pack, ) ret = {} funcs._load_all() if filter_name: funcs = FilterDictWrapper(funcs, filter_name) for key in funcs: ret[key] = funcs[key] return ret def _format_entrypoint_target(ep): ''' Makes a string describing the target of an EntryPoint object. Base strongly on EntryPoint.__str__(). ''' s = ep.module_name if ep.attrs: s += ':' + '.'.join(ep.attrs) return s def _module_dirs( opts, ext_type, tag=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, ): if tag is None: tag = ext_type sys_types = os.path.join(base_path or SALT_BASE_PATH, int_type or ext_type) ext_types = os.path.join(opts['extension_modules'], ext_type) ext_type_types = [] if ext_dirs: if ext_type_dirs is None: ext_type_dirs = '{0}_dirs'.format(tag) if ext_type_dirs in opts: ext_type_types.extend(opts[ext_type_dirs]) if HAS_PKG_RESOURCES and ext_type_dirs: for entry_point in pkg_resources.iter_entry_points('salt.loader', ext_type_dirs): try: loaded_entry_point = entry_point.load() for path in loaded_entry_point(): ext_type_types.append(path) except Exception as exc: log.error("Error getting module directories from %s: %s", _format_entrypoint_target(entry_point), exc) log.debug("Full backtrace for module directories error", exc_info=True) cli_module_dirs = [] # The dirs can be any module dir, or a in-tree _{ext_type} dir for _dir in opts.get('module_dirs', []): # Prepend to the list to match cli argument ordering maybe_dir = os.path.join(_dir, ext_type) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) continue maybe_dir = os.path.join(_dir, '_{0}'.format(ext_type)) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) return cli_module_dirs + ext_type_types + [ext_types, sys_types] def minion_mods( opts, context=None, utils=None, whitelist=None, initial_load=False, loaded_base_name=None, notify=False, static_modules=None, proxy=None): ''' Load execution modules Returns a dictionary of execution modules appropriate for the current system by evaluating the __virtual__() function in each module. :param dict opts: The Salt options dictionary :param dict context: A Salt context that should be made present inside generated modules in __context__ :param dict utils: Utility functions which should be made available to Salt modules in __utils__. See `utils_dirs` in salt.config for additional information about configuration. :param list whitelist: A list of modules which should be whitelisted. :param bool initial_load: Deprecated flag! Unused. :param str loaded_base_name: A string marker for the loaded base name. :param bool notify: Flag indicating that an event should be fired upon completion of module loading. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) __opts__['grains'] = __grains__ __utils__ = salt.loader.utils(__opts__) __salt__ = salt.loader.minion_mods(__opts__, utils=__utils__) __salt__['test.ping']() ''' # TODO Publish documentation for module whitelisting if not whitelist: whitelist = opts.get('whitelist_modules', None) ret = LazyLoader( _module_dirs(opts, 'modules', 'module'), opts, tag='module', pack={'__context__': context, '__utils__': utils, '__proxy__': proxy}, whitelist=whitelist, loaded_base_name=loaded_base_name, static_modules=static_modules, ) ret.pack['__salt__'] = ret # Load any provider overrides from the configuration file providers option # Note: Providers can be pkg, service, user or group - not to be confused # with cloud providers. providers = opts.get('providers', False) if providers and isinstance(providers, dict): for mod in providers: # sometimes providers opts is not to diverge modules but # for other configuration try: funcs = raw_mod(opts, providers[mod], ret) except TypeError: break else: if funcs: for func in funcs: f_key = '{0}{1}'.format(mod, func[func.rindex('.'):]) ret[f_key] = funcs[func] if notify: evt = salt.utils.event.get_event('minion', opts=opts, listen=False) evt.fire_event({'complete': True}, tag=salt.defaults.events.MINION_MOD_COMPLETE) return ret def raw_mod(opts, name, functions, mod='modules'): ''' Returns a single module loaded raw and bypassing the __virtual__ function .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') testmod = salt.loader.raw_mod(__opts__, 'test', None) testmod['test.ping']() ''' loader = LazyLoader( _module_dirs(opts, mod, 'module'), opts, tag='rawmodule', virtual_enable=False, pack={'__salt__': functions}, ) # if we don't have the module, return an empty dict if name not in loader.file_mapping: return {} loader._load_module(name) # load a single module (the one passed in) return dict(loader._dict) # return a copy of *just* the funcs for `name` def metaproxy(opts): ''' Return functions used in the meta proxy ''' return LazyLoader( _module_dirs(opts, 'metaproxy'), opts, tag='metaproxy' ) def matchers(opts): ''' Return the matcher services plugins ''' return LazyLoader( _module_dirs(opts, 'matchers'), opts, tag='matchers' ) def engines(opts, functions, runners, utils, proxy=None): ''' Return the master services plugins ''' pack = {'__salt__': functions, '__runners__': runners, '__proxy__': proxy, '__utils__': utils} return LazyLoader( _module_dirs(opts, 'engines'), opts, tag='engines', pack=pack, ) def returners(opts, functions, whitelist=None, context=None, proxy=None): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'returners', 'returner'), opts, tag='returner', whitelist=whitelist, pack={'__salt__': functions, '__context__': context, '__proxy__': proxy or {}}, ) def utils(opts, whitelist=None, context=None, proxy=proxy): ''' Returns the utility modules ''' return LazyLoader( _module_dirs(opts, 'utils', ext_type_dirs='utils_dirs'), opts, tag='utils', whitelist=whitelist, pack={'__context__': context, '__proxy__': proxy or {}}, ) def pillars(opts, functions, context=None): ''' Returns the pillars modules ''' ret = LazyLoader(_module_dirs(opts, 'pillar'), opts, tag='pillar', pack={'__salt__': functions, '__context__': context, '__utils__': utils(opts)}) ret.pack['__ext_pillar__'] = ret return FilterDictWrapper(ret, '.ext_pillar') def tops(opts): ''' Returns the tops modules ''' if 'master_tops' not in opts: return {} whitelist = list(opts['master_tops'].keys()) ret = LazyLoader( _module_dirs(opts, 'tops', 'top'), opts, tag='top', whitelist=whitelist, ) return FilterDictWrapper(ret, '.top') def wheels(opts, whitelist=None, context=None): ''' Returns the wheels modules ''' if context is None: context = {} return LazyLoader( _module_dirs(opts, 'wheel'), opts, tag='wheel', whitelist=whitelist, pack={'__context__': context}, ) def outputters(opts): ''' Returns the outputters modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only outputters present in the keyspace ''' ret = LazyLoader( _module_dirs(opts, 'output', ext_type_dirs='outputter_dirs'), opts, tag='output', ) wrapped_ret = FilterDictWrapper(ret, '.output') # TODO: this name seems terrible... __salt__ should always be execution mods ret.pack['__salt__'] = wrapped_ret return wrapped_ret def serializers(opts): ''' Returns the serializers modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only serializers present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'serializers'), opts, tag='serializers', ) def eauth_tokens(opts): ''' Returns the tokens modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only token backends present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'tokens'), opts, tag='tokens', ) def auth(opts, whitelist=None): ''' Returns the auth modules :param dict opts: The Salt options dictionary :returns: LazyLoader ''' return LazyLoader( _module_dirs(opts, 'auth'), opts, tag='auth', whitelist=whitelist, pack={'__salt__': minion_mods(opts)}, ) def fileserver(opts, backends): ''' Returns the file server modules ''' return LazyLoader(_module_dirs(opts, 'fileserver'), opts, tag='fileserver', whitelist=backends, pack={'__utils__': utils(opts)}) def roster(opts, runner=None, utils=None, whitelist=None): ''' Returns the roster modules ''' return LazyLoader( _module_dirs(opts, 'roster'), opts, tag='roster', whitelist=whitelist, pack={ '__runner__': runner, '__utils__': utils, }, ) def thorium(opts, functions, runners): ''' Load the thorium runtime modules ''' pack = {'__salt__': functions, '__runner__': runners, '__context__': {}} ret = LazyLoader(_module_dirs(opts, 'thorium'), opts, tag='thorium', pack=pack) ret.pack['__thorium__'] = ret return ret def states(opts, functions, utils, serializers, whitelist=None, proxy=None, context=None): ''' Returns the state modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') statemods = salt.loader.states(__opts__, None, None) ''' if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'states'), opts, tag='states', pack={'__salt__': functions, '__proxy__': proxy or {}}, whitelist=whitelist, ) ret.pack['__states__'] = ret ret.pack['__utils__'] = utils ret.pack['__serializers__'] = serializers ret.pack['__context__'] = context return ret def beacons(opts, functions, context=None, proxy=None): ''' Load the beacon modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. ''' return LazyLoader( _module_dirs(opts, 'beacons'), opts, tag='beacons', pack={'__context__': context, '__salt__': functions, '__proxy__': proxy or {}}, virtual_funcs=[], ) def log_handlers(opts): ''' Returns the custom logging handler modules :param dict opts: The Salt options dictionary ''' ret = LazyLoader( _module_dirs( opts, 'log_handlers', int_type='handlers', base_path=os.path.join(SALT_BASE_PATH, 'log'), ), opts, tag='log_handlers', ) return FilterDictWrapper(ret, '.setup_handlers') def ssh_wrapper(opts, functions=None, context=None): ''' Returns the custom logging handler modules ''' return LazyLoader( _module_dirs( opts, 'wrapper', base_path=os.path.join(SALT_BASE_PATH, os.path.join('client', 'ssh')), ), opts, tag='wrapper', pack={ '__salt__': functions, '__grains__': opts.get('grains', {}), '__pillar__': opts.get('pillar', {}), '__context__': context, }, ) def render(opts, functions, states=None, proxy=None, context=None): ''' Returns the render modules ''' if context is None: context = {} pack = {'__salt__': functions, '__grains__': opts.get('grains', {}), '__context__': context} if states: pack['__states__'] = states pack['__proxy__'] = proxy or {} ret = LazyLoader( _module_dirs( opts, 'renderers', 'render', ext_type_dirs='render_dirs', ), opts, tag='render', pack=pack, ) rend = FilterDictWrapper(ret, '.render') if not check_render_pipe_str(opts['renderer'], rend, opts['renderer_blacklist'], opts['renderer_whitelist']): err = ('The renderer {0} is unavailable, this error is often because ' 'the needed software is unavailable'.format(opts['renderer'])) log.critical(err) raise LoaderError(err) return rend def grain_funcs(opts, proxy=None): ''' Returns the grain functions .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') grainfuncs = salt.loader.grain_funcs(__opts__) ''' ret = LazyLoader( _module_dirs( opts, 'grains', 'grain', ext_type_dirs='grains_dirs', ), opts, tag='grains', ) ret.pack['__utils__'] = utils(opts, proxy=proxy) return ret def _load_cached_grains(opts, cfn): ''' Returns the grains cached in cfn, or None if the cache is too old or is corrupted. ''' if not os.path.isfile(cfn): log.debug('Grains cache file does not exist.') return None grains_cache_age = int(time.time() - os.path.getmtime(cfn)) if grains_cache_age > opts.get('grains_cache_expiration', 300): log.debug( 'Grains cache last modified %s seconds ago and cache ' 'expiration is set to %s. Grains cache expired. ' 'Refreshing.', grains_cache_age, opts.get('grains_cache_expiration', 300) ) return None if opts.get('refresh_grains_cache', False): log.debug('refresh_grains_cache requested, Refreshing.') return None log.debug('Retrieving grains from cache') try: serial = salt.payload.Serial(opts) with salt.utils.files.fopen(cfn, 'rb') as fp_: cached_grains = salt.utils.data.decode(serial.load(fp_), preserve_tuples=True) if not cached_grains: log.debug('Cached grains are empty, cache might be corrupted. Refreshing.') return None return cached_grains except (IOError, OSError): return None def grains(opts, force_refresh=False, proxy=None): ''' Return the functions for the dynamic grains and the values for the static grains. Since grains are computed early in the startup process, grains functions do not have __salt__ or __proxy__ available. At proxy-minion startup, this function is called with the proxymodule LazyLoader object so grains functions can communicate with their controlled device. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) print __grains__['id'] ''' # Need to re-import salt.config, somehow it got lost when a minion is starting import salt.config # if we have no grains, lets try loading from disk (TODO: move to decorator?) cfn = os.path.join( opts['cachedir'], 'grains.cache.p' ) if not force_refresh and opts.get('grains_cache', False): cached_grains = _load_cached_grains(opts, cfn) if cached_grains: return cached_grains else: log.debug('Grains refresh requested. Refreshing grains.') if opts.get('skip_grains', False): return {} grains_deep_merge = opts.get('grains_deep_merge', False) is True if 'conf_file' in opts: pre_opts = {} pre_opts.update(salt.config.load_config( opts['conf_file'], 'SALT_MINION_CONFIG', salt.config.DEFAULT_MINION_OPTS['conf_file'] )) default_include = pre_opts.get( 'default_include', opts['default_include'] ) include = pre_opts.get('include', []) pre_opts.update(salt.config.include_config( default_include, opts['conf_file'], verbose=False )) pre_opts.update(salt.config.include_config( include, opts['conf_file'], verbose=True )) if 'grains' in pre_opts: opts['grains'] = pre_opts['grains'] else: opts['grains'] = {} else: opts['grains'] = {} grains_data = {} blist = opts.get('grains_blacklist', []) funcs = grain_funcs(opts, proxy=proxy) if force_refresh: # if we refresh, lets reload grain modules funcs.clear() # Run core grains for key in funcs: if not key.startswith('core.'): continue log.trace('Loading %s grain', key) ret = funcs[key]() if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) # Run the rest of the grains for key in funcs: if key.startswith('core.') or key == '_errors': continue try: # Grains are loaded too early to take advantage of the injected # __proxy__ variable. Pass an instance of that LazyLoader # here instead to grains functions if the grains functions take # one parameter. Then the grains can have access to the # proxymodule for retrieving information from the connected # device. log.trace('Loading %s grain', key) parameters = salt.utils.args.get_function_argspec(funcs[key]).args kwargs = {} if 'proxy' in parameters: kwargs['proxy'] = proxy if 'grains' in parameters: kwargs['grains'] = grains_data ret = funcs[key](**kwargs) except Exception: if salt.utils.platform.is_proxy(): log.info('The following CRITICAL message may not be an error; the proxy may not be completely established yet.') log.critical( 'Failed to load grains defined in grain file %s in ' 'function %s, error:\n', key, funcs[key], exc_info=True ) continue if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) if opts.get('proxy_merge_grains_in_module', True) and proxy: try: proxytype = proxy.opts['proxy']['proxytype'] if proxytype + '.grains' in proxy: if proxytype + '.initialized' in proxy and proxy[proxytype + '.initialized'](): try: proxytype = proxy.opts['proxy']['proxytype'] ret = proxy[proxytype + '.grains']() if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) except Exception: log.critical('Failed to run proxy\'s grains function!', exc_info=True ) except KeyError: pass grains_data.update(opts['grains']) # Write cache if enabled if opts.get('grains_cache', False): with salt.utils.files.set_umask(0o077): try: if salt.utils.platform.is_windows(): # Late import import salt.modules.cmdmod # Make sure cache file isn't read-only salt.modules.cmdmod._run_quiet('attrib -R "{0}"'.format(cfn)) with salt.utils.files.fopen(cfn, 'w+b') as fp_: try: serial = salt.payload.Serial(opts) serial.dump(grains_data, fp_) except TypeError as e: log.error('Failed to serialize grains cache: %s', e) raise # re-throw for cleanup except Exception as e: log.error('Unable to write to grains cache file %s: %s', cfn, e) # Based on the original exception, the file may or may not have been # created. If it was, we will remove it now, as the exception means # the serialized data is not to be trusted, no matter what the # exception is. if os.path.isfile(cfn): os.unlink(cfn) if grains_deep_merge: salt.utils.dictupdate.update(grains_data, opts['grains']) else: grains_data.update(opts['grains']) return salt.utils.data.decode(grains_data, preserve_tuples=True) # TODO: get rid of? Does anyone use this? You should use raw() instead def call(fun, **kwargs): ''' Directly call a function inside a loader directory ''' args = kwargs.get('args', []) dirs = kwargs.get('dirs', []) funcs = LazyLoader( [os.path.join(SALT_BASE_PATH, 'modules')] + dirs, None, tag='modules', virtual_enable=False, ) return funcs[fun](*args) def runner(opts, utils=None, context=None, whitelist=None): ''' Directly call a function inside a loader directory ''' if utils is None: utils = {} if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'runners', 'runner', ext_type_dirs='runner_dirs'), opts, tag='runners', pack={'__utils__': utils, '__context__': context}, whitelist=whitelist, ) # TODO: change from __salt__ to something else, we overload __salt__ too much ret.pack['__salt__'] = ret return ret def queues(opts): ''' Directly call a function inside a loader directory ''' return LazyLoader( _module_dirs(opts, 'queues', 'queue', ext_type_dirs='queue_dirs'), opts, tag='queues', ) def sdb(opts, functions=None, whitelist=None, utils=None): ''' Make a very small database call ''' if utils is None: utils = {} return LazyLoader( _module_dirs(opts, 'sdb'), opts, tag='sdb', pack={ '__sdb__': functions, '__opts__': opts, '__utils__': utils, '__salt__': minion_mods(opts, utils), }, whitelist=whitelist, ) def pkgdb(opts): ''' Return modules for SPM's package database .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgdb', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgdb' ) def pkgfiles(opts): ''' Return modules for SPM's file handling .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgfiles', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgfiles' ) def clouds(opts): ''' Return the cloud functions ''' # Let's bring __active_provider_name__, defaulting to None, to all cloud # drivers. This will get temporarily updated/overridden with a context # manager when needed. functions = LazyLoader( _module_dirs(opts, 'clouds', 'cloud', base_path=os.path.join(SALT_BASE_PATH, 'cloud'), int_type='clouds'), opts, tag='clouds', pack={'__utils__': salt.loader.utils(opts), '__active_provider_name__': None}, ) for funcname in LIBCLOUD_FUNCS_NOT_SUPPORTED: log.trace( '\'%s\' has been marked as not supported. Removing from the ' 'list of supported cloud functions', funcname ) functions.pop(funcname, None) return functions def netapi(opts): ''' Return the network api functions ''' return LazyLoader( _module_dirs(opts, 'netapi'), opts, tag='netapi', ) def executors(opts, functions=None, context=None, proxy=None): ''' Returns the executor modules ''' executors = LazyLoader( _module_dirs(opts, 'executors', 'executor'), opts, tag='executor', pack={'__salt__': functions, '__context__': context or {}, '__proxy__': proxy or {}}, ) executors.pack['__executors__'] = executors return executors def cache(opts, serial): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'cache', 'cache'), opts, tag='cache', pack={'__opts__': opts, '__context__': {'serial': serial}}, ) def _generate_module(name): if name in sys.modules: return code = "'''Salt loaded {0} parent module'''".format(name.split('.')[-1]) # ModuleType can't accept a unicode type on PY2 module = types.ModuleType(str(name)) # future lint: disable=blacklisted-function exec(code, module.__dict__) sys.modules[name] = module def _mod_type(module_path): if module_path.startswith(SALT_BASE_PATH): return 'int' return 'ext' def _inject_into_mod(mod, name, value, force_lock=False): ''' Inject a variable into a module. This is used to inject "globals" like ``__salt__``, ``__pillar``, or ``grains``. Instead of injecting the value directly, a ``ThreadLocalProxy`` is created. If such a proxy is already present under the specified name, it is updated with the new value. This update only affects the current thread, so that the same name can refer to different values depending on the thread of execution. This is important for data that is not truly global. For example, pillar data might be dynamically overriden through function parameters and thus the actual values available in pillar might depend on the thread that is calling a module. mod: module object into which the value is going to be injected. name: name of the variable that is injected into the module. value: value that is injected into the variable. The value is not injected directly, but instead set as the new reference of the proxy that has been created for the variable. force_lock: whether the lock should be acquired before checking whether a proxy object for the specified name has already been injected into the module. If ``False`` (the default), this function checks for the module's variable without acquiring the lock and only acquires the lock if a new proxy has to be created and injected. ''' old_value = getattr(mod, name, None) # We use a double-checked locking scheme in order to avoid taking the lock # when a proxy object has already been injected. # In most programming languages, double-checked locking is considered # unsafe when used without explicit memory barriers because one might read # an uninitialized value. In CPython it is safe due to the global # interpreter lock (GIL). In Python implementations that do not have the # GIL, it could be unsafe, but at least Jython also guarantees that (for # Python objects) memory is not corrupted when writing and reading without # explicit synchronization # (http://www.jython.org/jythonbook/en/1.0/Concurrency.html). # Please note that in order to make this code safe in a runtime environment # that does not make this guarantees, it is not sufficient. The # ThreadLocalProxy must also be created with fallback_to_shared set to # False or a lock must be added to the ThreadLocalProxy. if force_lock: with _inject_into_mod.lock: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: setattr(mod, name, ThreadLocalProxy(value, True)) else: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: _inject_into_mod(mod, name, value, True) # Lock used when injecting globals. This is needed to avoid a race condition # when two threads try to load the same module concurrently. This must be # outside the loader because there might be more than one loader for the same # namespace. _inject_into_mod.lock = threading.RLock() # TODO: move somewhere else? class FilterDictWrapper(MutableMapping): ''' Create a dict which wraps another dict with a specific key suffix on get This is to replace "filter_load" ''' def __init__(self, d, suffix): self._dict = d self.suffix = suffix def __setitem__(self, key, val): self._dict[key] = val def __delitem__(self, key): del self._dict[key] def __getitem__(self, key): return self._dict[key + self.suffix] def __len__(self): return len(self._dict) def __iter__(self): for key in self._dict: if key.endswith(self.suffix): yield key.replace(self.suffix, '') class LazyLoader(salt.utils.lazy.LazyDict): ''' A pseduo-dictionary which has a set of keys which are the name of the module and function, delimited by a dot. When the value of the key is accessed, the function is then loaded from disk and into memory. .. note:: Iterating over keys will cause all modules to be loaded. :param list module_dirs: A list of directories on disk to search for modules :param dict opts: The salt options dictionary. :param str tag: The tag for the type of module to load :param func mod_type_check: A function which can be used to verify files :param dict pack: A dictionary of function to be packed into modules as they are loaded :param list whitelist: A list of modules to whitelist :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules. :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality. If not true, the module will not load. :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values are function references themselves which are loaded on-demand. # TODO: - move modules_max_memory into here - singletons (per tag) ''' mod_dict_class = salt.utils.odict.OrderedDict def __init__(self, module_dirs, opts=None, tag='module', loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, proxy=None, virtual_funcs=None, ): # pylint: disable=W0231 ''' In pack, if any of the values are None they will be replaced with an empty context-specific dict ''' self.inject_globals = {} self.pack = {} if pack is None else pack if opts is None: opts = {} threadsafety = not opts.get('multiprocessing') self.context_dict = salt.utils.context.ContextDict(threadsafe=threadsafety) self.opts = self.__prep_mod_opts(opts) self.module_dirs = module_dirs self.tag = tag self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME self.mod_type_check = mod_type_check or _mod_type if '__context__' not in self.pack: self.pack['__context__'] = None for k, v in six.iteritems(self.pack): if v is None: # if the value of a pack is None, lets make an empty dict value = self.context_dict.get(k, {}) if isinstance(value, ThreadLocalProxy): value = ThreadLocalProxy.unproxy(value) self.context_dict[k] = value self.pack[k] = salt.utils.context.NamespacedDictWrapper(self.context_dict, k) self.whitelist = whitelist self.virtual_enable = virtual_enable self.initial_load = True # names of modules that we don't have (errors, __virtual__, etc.) self.missing_modules = {} # mapping of name -> error self.loaded_modules = {} # mapping of module_name -> dict_of_functions self.loaded_files = set() # TODO: just remove them from file_mapping? self.static_modules = static_modules if static_modules else [] if virtual_funcs is None: virtual_funcs = [] self.virtual_funcs = virtual_funcs self.disabled = set( self.opts.get( 'disable_{0}{1}'.format( self.tag, '' if self.tag[-1] == 's' else 's' ), [] ) ) # A map of suffix to description for imp self.suffix_map = {} # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [''] for (suffix, mode, kind) in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) self._lock = threading.RLock() self._refresh_file_mapping() super(LazyLoader, self).__init__() # late init the lazy loader # create all of the import namespaces _generate_module('{0}.int'.format(self.loaded_base_name)) _generate_module('{0}.int.{1}'.format(self.loaded_base_name, tag)) _generate_module('{0}.ext'.format(self.loaded_base_name)) _generate_module('{0}.ext.{1}'.format(self.loaded_base_name, tag)) def __getitem__(self, item): ''' Override the __getitem__ in order to decorate the returned function if we need to last-minute inject globals ''' func = super(LazyLoader, self).__getitem__(item) if self.inject_globals: return global_injector_decorator(self.inject_globals)(func) else: return func def __getattr__(self, mod_name): ''' Allow for "direct" attribute access-- this allows jinja templates to access things like `salt.test.ping()` ''' if mod_name in ('__getstate__', '__setstate__'): return object.__getattribute__(self, mod_name) # if we have an attribute named that, lets return it. try: return object.__getattr__(self, mod_name) # pylint: disable=no-member except AttributeError: pass # otherwise we assume its jinja template access if mod_name not in self.loaded_modules and not self.loaded: for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and mod_name in self.loaded_modules: break if mod_name in self.loaded_modules: return self.loaded_modules[mod_name] else: raise AttributeError(mod_name) def missing_fun_string(self, function_name): ''' Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ''' mod_name = function_name.split('.')[0] if mod_name in self.loaded_modules: return '\'{0}\' is not available.'.format(function_name) else: try: reason = self.missing_modules[mod_name] except KeyError: return '\'{0}\' is not available.'.format(function_name) else: if reason is not None: return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason) else: return '\'{0}\' __virtual__ returned False'.format(mod_name) def _refresh_file_mapping(self): ''' refresh the mapping of the FS on disk ''' # map of suffix to description for imp if self.opts.get('cython_enable', True) is True: try: global pyximport pyximport = __import__('pyximport') # pylint: disable=import-error pyximport.install() # add to suffix_map so file_mapping will pick it up self.suffix_map['.pyx'] = tuple() except ImportError: log.info('Cython is enabled in the options but not present ' 'in the system path. Skipping Cython modules.') # Allow for zipimport of modules if self.opts.get('enable_zip_modules', True) is True: self.suffix_map['.zip'] = tuple() # allow for module dirs if USE_IMPORTLIB: self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY) else: self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY) # create mapping of filename (without suffix) to (path, suffix) # The files are added in order of priority, so order *must* be retained. self.file_mapping = salt.utils.odict.OrderedDict() opt_match = [] def _replace_pre_ext(obj): ''' Hack so we can get the optimization level that we replaced (if any) out of the re.sub call below. We use a list here because it is a persistent data structure that we will be able to access after re.sub is called. ''' opt_match.append(obj) return '' for mod_dir in self.module_dirs: try: # Make sure we have a sorted listdir in order to have # expectable override results files = sorted( x for x in os.listdir(mod_dir) if x != '__pycache__' ) except OSError: continue # Next mod_dir if six.PY3: try: pycache_files = [ os.path.join('__pycache__', x) for x in sorted(os.listdir(os.path.join(mod_dir, '__pycache__'))) ] except OSError: pass else: files.extend(pycache_files) for filename in files: try: dirname, basename = os.path.split(filename) if basename.startswith('_'): # skip private modules # log messages omitted for obviousness continue # Next filename f_noext, ext = os.path.splitext(basename) if six.PY3: f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext) try: opt_level = int( opt_match.pop().group(1).rsplit('-', 1)[-1] ) except (AttributeError, IndexError, ValueError): # No regex match or no optimization level matched opt_level = 0 try: opt_index = self.opts['optimization_order'].index(opt_level) except KeyError: log.trace( 'Disallowed optimization level %d for module ' 'name \'%s\', skipping. Add %d to the ' '\'optimization_order\' config option if you ' 'do not want to ignore this optimization ' 'level.', opt_level, f_noext, opt_level ) continue else: # Optimization level not reflected in filename on PY2 opt_index = 0 # make sure it is a suffix we support if ext not in self.suffix_map: continue # Next filename if f_noext in self.disabled: log.trace( 'Skipping %s, it is disabled by configuration', filename ) continue # Next filename fpath = os.path.join(mod_dir, filename) # if its a directory, lets allow us to load that if ext == '': # is there something __init__? subfiles = os.listdir(fpath) for suffix in self.suffix_order: if '' == suffix: continue # Next suffix (__init__ must have a suffix) init_file = '__init__{0}'.format(suffix) if init_file in subfiles: break else: continue # Next filename try: curr_ext = self.file_mapping[f_noext][1] curr_opt_index = self.file_mapping[f_noext][2] except KeyError: pass else: if '' in (curr_ext, ext) and curr_ext != ext: log.error( 'Module/package collision: \'%s\' and \'%s\'', fpath, self.file_mapping[f_noext][0] ) if six.PY3 and ext == '.pyc' and curr_ext == '.pyc': # Check the optimization level if opt_index >= curr_opt_index: # Module name match, but a higher-priority # optimization level was already matched, skipping. continue elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext): # Match found but a higher-priorty match already # exists, so skip this. continue if six.PY3 and not dirname and ext == '.pyc': # On Python 3, we should only load .pyc files from the # __pycache__ subdirectory (i.e. when dirname is not an # empty string). continue # Made it this far - add it self.file_mapping[f_noext] = (fpath, ext, opt_index) except OSError: continue for smod in self.static_modules: f_noext = smod.split('.')[-1] self.file_mapping[f_noext] = (smod, '.o', 0) def clear(self): ''' Clear the dict ''' with self._lock: super(LazyLoader, self).clear() # clear the lazy loader self.loaded_files = set() self.missing_modules = {} self.loaded_modules = {} # if we have been loaded before, lets clear the file mapping since # we obviously want a re-do if hasattr(self, 'opts'): self._refresh_file_mapping() self.initial_load = False def __prep_mod_opts(self, opts): ''' Strip out of the opts any logger instance ''' if '__grains__' not in self.pack: grains = opts.get('grains', {}) if isinstance(grains, ThreadLocalProxy): grains = ThreadLocalProxy.unproxy(grains) self.context_dict['grains'] = grains self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains') if '__pillar__' not in self.pack: pillar = opts.get('pillar', {}) if isinstance(pillar, ThreadLocalProxy): pillar = ThreadLocalProxy.unproxy(pillar) self.context_dict['pillar'] = pillar self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar') mod_opts = {} for key, val in list(opts.items()): if key == 'logger': continue mod_opts[key] = val return mod_opts def _iter_files(self, mod_name): ''' Iterate over all file_mapping files in order of closeness to mod_name ''' # do we have an exact match? if mod_name in self.file_mapping: yield mod_name # do we have a partial match? for k in self.file_mapping: if mod_name in k: yield k # anyone else? Bueller? for k in self.file_mapping: if mod_name not in k: yield k def _reload_submodules(self, mod): submodules = ( getattr(mod, sname) for sname in dir(mod) if isinstance(getattr(mod, sname), mod.__class__) ) # reload only custom "sub"modules for submodule in submodules: # it is a submodule if the name is in a namespace under mod if submodule.__name__.startswith(mod.__name__ + '.'): reload_module(submodule) self._reload_submodules(submodule) def _load_module(self, name): mod = None fpath, suffix = self.file_mapping[name][:2] self.loaded_files.add(name) fpath_dirname = os.path.dirname(fpath) try: sys.path.append(fpath_dirname) if suffix == '.pyx': mod = pyximport.load_module(name, fpath, tempfile.gettempdir()) elif suffix == '.o': top_mod = __import__(fpath, globals(), locals(), []) comps = fpath.split('.') if len(comps) < 2: mod = top_mod else: mod = top_mod for subname in comps[1:]: mod = getattr(mod, subname) elif suffix == '.zip': mod = zipimporter(fpath).load_module(name) else: desc = self.suffix_map[suffix] # if it is a directory, we don't open a file try: mod_namespace = '.'.join(( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name)) except TypeError: mod_namespace = '{0}.{1}.{2}.{3}'.format( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name) if suffix == '': if USE_IMPORTLIB: # pylint: disable=no-member # Package directory, look for __init__ loader_details = [ (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES), (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES), (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), ] file_finder = importlib.machinery.FileFinder( fpath_dirname, *loader_details ) spec = file_finder.find_spec(mod_namespace) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: mod = imp.load_module(mod_namespace, None, fpath, desc) # reload all submodules if necessary if not self.initial_load: self._reload_submodules(mod) else: if USE_IMPORTLIB: # pylint: disable=no-member loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath) spec = importlib.util.spec_from_file_location( mod_namespace, fpath, loader=loader ) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() #mod = importlib.util.module_from_spec(spec) #spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: with salt.utils.files.fopen(fpath, desc[1]) as fn_: mod = imp.load_module(mod_namespace, fn_, fpath, desc) except IOError: raise except ImportError as exc: if 'magic number' in six.text_type(exc): error_msg = 'Failed to import {0} {1}. Bad magic number. If migrating from Python2 to Python3, remove all .pyc files and try again.'.format(self.tag, name) log.warning(error_msg) self.missing_modules[name] = error_msg log.debug( 'Failed to import %s %s:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = exc return False except Exception as error: log.error( 'Failed to import %s %s, this is due most likely to a ' 'syntax error:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False except SystemExit as error: try: fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1] except Exception: pass else: tgt_fn = os.path.join('salt', 'utils', 'process.py') if fn_.endswith(tgt_fn) and '_handle_signals' in caller: # Race conditon, SIGTERM or SIGINT received while loader # was in process of loading a module. Call sys.exit to # ensure that the process is killed. sys.exit(salt.defaults.exitcodes.EX_OK) log.error( 'Failed to import %s %s as the module called exit()\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False finally: sys.path.remove(fpath_dirname) if hasattr(mod, '__opts__'): mod.__opts__.update(self.opts) else: mod.__opts__ = self.opts # pack whatever other globals we were asked to for p_name, p_value in six.iteritems(self.pack): _inject_into_mod(mod, p_name, p_value) module_name = mod.__name__.rsplit('.', 1)[-1] # Call a module's initialization method if it exists module_init = getattr(mod, '__init__', None) if inspect.isfunction(module_init): try: module_init(self.opts) except TypeError as e: log.error(e) except Exception: err_string = '__init__ failed' log.debug( 'Error loading %s.%s: %s', self.tag, module_name, err_string, exc_info=True ) self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False # if virtual modules are enabled, we need to look for the # __virtual__() function inside that module and run it. if self.virtual_enable: virtual_funcs_to_process = ['__virtual__'] + self.virtual_funcs for virtual_func in virtual_funcs_to_process: virtual_ret, module_name, virtual_err, virtual_aliases = \ self._process_virtual(mod, module_name, virtual_func) if virtual_err is not None: log.trace( 'Error loading %s.%s: %s', self.tag, module_name, virtual_err ) # if _process_virtual returned a non-True value then we are # supposed to not process this module if virtual_ret is not True and module_name not in self.missing_modules: # If a module has information about why it could not be loaded, record it self.missing_modules[module_name] = virtual_err self.missing_modules[name] = virtual_err return False else: virtual_aliases = () # If this is a proxy minion then MOST modules cannot work. Therefore, require that # any module that does work with salt-proxy-minion define __proxyenabled__ as a list # containing the names of the proxy types that the module supports. # # Render modules and state modules are OK though if 'proxy' in self.opts: if self.tag in ['grains', 'proxy']: if not hasattr(mod, '__proxyenabled__') or \ (self.opts['proxy']['proxytype'] not in mod.__proxyenabled__ and '*' not in mod.__proxyenabled__): err_string = 'not a proxy_minion enabled module' self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False if getattr(mod, '__load__', False) is not False: log.info( 'The functions from module \'%s\' are being loaded from the ' 'provided __load__ attribute', module_name ) # If we had another module by the same virtual name, we should put any # new functions under the existing dictionary. mod_names = [module_name] + list(virtual_aliases) mod_dict = dict(( (x, self.loaded_modules.get(x, self.mod_dict_class())) for x in mod_names )) for attr in getattr(mod, '__load__', dir(mod)): if attr.startswith('_') and attr != '__call__': # private functions are skipped, # except __call__ which is default entrance # for multi-function batch-like state syntax continue func = getattr(mod, attr) if not inspect.isfunction(func) and not isinstance(func, functools.partial): # Not a function!? Skip it!!! continue # Let's get the function name. # If the module has the __func_alias__ attribute, it must be a # dictionary mapping in the form of(key -> value): # <real-func-name> -> <desired-func-name> # # It default's of course to the found callable attribute name # if no alias is defined. funcname = getattr(mod, '__func_alias__', {}).get(attr, attr) for tgt_mod in mod_names: try: full_funcname = '.'.join((tgt_mod, funcname)) except TypeError: full_funcname = '{0}.{1}'.format(tgt_mod, funcname) # Save many references for lookups # Careful not to overwrite existing (higher priority) functions if full_funcname not in self._dict: self._dict[full_funcname] = func if funcname not in mod_dict[tgt_mod]: setattr(mod_dict[tgt_mod], funcname, func) mod_dict[tgt_mod][funcname] = func self._apply_outputter(func, mod) # enforce depends try: Depends.enforce_dependencies(self._dict, self.tag) except RuntimeError as exc: log.info( 'Depends.enforce_dependencies() failed for the following ' 'reason: %s', exc ) for tgt_mod in mod_names: self.loaded_modules[tgt_mod] = mod_dict[tgt_mod] return True def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise KeyError('The key \'{0}\' should contain a \'.\''.format(key)) mod_name, _ = key.split('.', 1) with self._lock: # It is possible that the key is in the dictionary after # acquiring the lock due to another thread loading it. if mod_name in self.missing_modules or key in self._dict: return True # if the modulename isn't in the whitelist, don't bother if self.whitelist and mod_name not in self.whitelist: log.error( 'Failed to load function %s because its module (%s) is ' 'not in the whitelist: %s', key, mod_name, self.whitelist ) raise KeyError(key) def _inner_load(mod_name): for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and key in self._dict: return True return False # try to load the module ret = None reloaded = False # re-scan up to once, IOErrors or a failed load cause re-scans of the # filesystem while True: try: ret = _inner_load(mod_name) if not reloaded and ret is not True: self._refresh_file_mapping() reloaded = True continue break except IOError: if not reloaded: self._refresh_file_mapping() reloaded = True continue return ret def _load_all(self): ''' Load all of them ''' with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True def reload_modules(self): with self._lock: self.loaded_files = set() self._load_all() def _apply_outputter(self, func, mod): ''' Apply the __outputter__ variable to the functions ''' if hasattr(mod, '__outputter__'): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__] def _process_virtual(self, mod, module_name, virtual_func='__virtual__'): ''' Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1] ''' # The __virtual__ function will return either a True or False value. # If it returns a True value it can also set a module level attribute # named __virtualname__ with the name that the module should be # referred to as. # # This allows us to have things like the pkg module working on all # platforms under the name 'pkg'. It also allows for modules like # augeas_cfg to be referred to as 'augeas', which would otherwise have # namespace collisions. And finally it allows modules to return False # if they are not intended to run on the given platform or are missing # dependencies. virtual_aliases = getattr(mod, '__virtual_aliases__', tuple()) try: error_reason = None if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__): try: start = time.time() virtual = getattr(mod, virtual_func)() if isinstance(virtual, tuple): error_reason = virtual[1] virtual = virtual[0] if self.opts.get('virtual_timer', False): end = time.time() - start msg = 'Virtual function took {0} seconds for {1}'.format( end, module_name) log.warning(msg) except Exception as exc: error_reason = ( 'Exception raised when processing __virtual__ function' ' for {0}. Module will not be loaded: {1}'.format( mod.__name__, exc)) log.error(error_reason, exc_info_on_loglevel=logging.DEBUG) virtual = None # Get the module's virtual name virtualname = getattr(mod, '__virtualname__', virtual) if not virtual: # if __virtual__() evaluates to False then the module # wasn't meant for this platform or it's not supposed to # load for some other reason. # Some modules might accidentally return None and are # improperly loaded if virtual is None: log.warning( '%s.__virtual__() is wrongly returning `None`. ' 'It should either return `True`, `False` or a new ' 'name. If you\'re the developer of the module ' '\'%s\', please fix this.', mod.__name__, module_name ) return (False, module_name, error_reason, virtual_aliases) # At this point, __virtual__ did not return a # boolean value, let's check for deprecated usage # or module renames if virtual is not True and module_name != virtual: # The module is renaming itself. Updating the module name # with the new name log.trace('Loaded %s as virtual %s', module_name, virtual) if virtualname != virtual: # The __virtualname__ attribute does not match what's # being returned by the __virtual__() function. This # should be considered an error. log.error( 'The module \'%s\' is showing some bad usage. Its ' '__virtualname__ attribute is set to \'%s\' yet the ' '__virtual__() function is returning \'%s\'. These ' 'values should match!', mod.__name__, virtualname, virtual ) module_name = virtualname # If the __virtual__ function returns True and __virtualname__ # is set then use it elif virtual is True and virtualname != module_name: if virtualname is not True: module_name = virtualname except KeyError: # Key errors come out of the virtual function when passing # in incomplete grains sets, these can be safely ignored # and logged to debug, still, it includes the traceback to # help debugging. log.debug('KeyError when loading %s', module_name, exc_info=True) except Exception: # If the module throws an exception during __virtual__() # then log the information and continue to the next. log.error( 'Failed to read the virtual function for %s: %s', self.tag, module_name, exc_info=True ) return (False, module_name, error_reason, virtual_aliases) return (True, module_name, None, virtual_aliases) def global_injector_decorator(inject_globals): ''' Decorator used by the LazyLoader to inject globals into a function at execute time. globals Dictionary with global variables to inject ''' def inner_decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): with salt.utils.context.func_globals_inject(f, **inject_globals): return f(*args, **kwargs) return wrapper return inner_decorator
saltstack/salt
salt/loader.py
returners
python
def returners(opts, functions, whitelist=None, context=None, proxy=None): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'returners', 'returner'), opts, tag='returner', whitelist=whitelist, pack={'__salt__': functions, '__context__': context, '__proxy__': proxy or {}}, )
Returns the returner modules
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L373-L383
null
# -*- coding: utf-8 -*- ''' The Salt loader is the core to Salt's plugin system, the loader scans directories for python loadable code and organizes the code into the plugin interfaces used by Salt. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import sys import time import logging import inspect import tempfile import threading import functools import threading import traceback import types from zipimport import zipimporter # Import salt libs import salt.config import salt.defaults.events import salt.defaults.exitcodes import salt.syspaths import salt.utils.args import salt.utils.context import salt.utils.data import salt.utils.dictupdate import salt.utils.event import salt.utils.files import salt.utils.lazy import salt.utils.odict import salt.utils.platform import salt.utils.versions import salt.utils.stringutils from salt.exceptions import LoaderError from salt.template import check_render_pipe_str from salt.utils.decorators import Depends from salt.utils.thread_local_proxy import ThreadLocalProxy # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import reload_module if sys.version_info[:2] >= (3, 5): import importlib.machinery # pylint: disable=no-name-in-module,import-error import importlib.util # pylint: disable=no-name-in-module,import-error USE_IMPORTLIB = True else: import imp USE_IMPORTLIB = False try: from collections.abc import MutableMapping except ImportError: from collections import MutableMapping try: import pkg_resources HAS_PKG_RESOURCES = True except ImportError: HAS_PKG_RESOURCES = False log = logging.getLogger(__name__) SALT_BASE_PATH = os.path.abspath(salt.syspaths.INSTALL_DIR) LOADED_BASE_NAME = 'salt.loaded' if USE_IMPORTLIB: # pylint: disable=no-member MODULE_KIND_SOURCE = 1 MODULE_KIND_COMPILED = 2 MODULE_KIND_EXTENSION = 3 MODULE_KIND_PKG_DIRECTORY = 5 SUFFIXES = [] for suffix in importlib.machinery.EXTENSION_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_EXTENSION)) for suffix in importlib.machinery.SOURCE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_SOURCE)) for suffix in importlib.machinery.BYTECODE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_COMPILED)) MODULE_KIND_MAP = { MODULE_KIND_SOURCE: importlib.machinery.SourceFileLoader, MODULE_KIND_COMPILED: importlib.machinery.SourcelessFileLoader, MODULE_KIND_EXTENSION: importlib.machinery.ExtensionFileLoader } # pylint: enable=no-member else: SUFFIXES = imp.get_suffixes() PY3_PRE_EXT = \ re.compile(r'\.cpython-{0}{1}(\.opt-[1-9])?'.format(*sys.version_info[:2])) # Because on the cloud drivers we do `from salt.cloud.libcloudfuncs import *` # which simplifies code readability, it adds some unsupported functions into # the driver's module scope. # We list un-supported functions here. These will be removed from the loaded. # TODO: remove the need for this cross-module code. Maybe use NotImplemented LIBCLOUD_FUNCS_NOT_SUPPORTED = ( 'parallels.avail_sizes', 'parallels.avail_locations', 'proxmox.avail_sizes', ) # Will be set to pyximport module at runtime if cython is enabled in config. pyximport = None def static_loader( opts, ext_type, tag, pack=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, filter_name=None, ): funcs = LazyLoader( _module_dirs( opts, ext_type, tag, int_type, ext_dirs, ext_type_dirs, base_path, ), opts, tag=tag, pack=pack, ) ret = {} funcs._load_all() if filter_name: funcs = FilterDictWrapper(funcs, filter_name) for key in funcs: ret[key] = funcs[key] return ret def _format_entrypoint_target(ep): ''' Makes a string describing the target of an EntryPoint object. Base strongly on EntryPoint.__str__(). ''' s = ep.module_name if ep.attrs: s += ':' + '.'.join(ep.attrs) return s def _module_dirs( opts, ext_type, tag=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, ): if tag is None: tag = ext_type sys_types = os.path.join(base_path or SALT_BASE_PATH, int_type or ext_type) ext_types = os.path.join(opts['extension_modules'], ext_type) ext_type_types = [] if ext_dirs: if ext_type_dirs is None: ext_type_dirs = '{0}_dirs'.format(tag) if ext_type_dirs in opts: ext_type_types.extend(opts[ext_type_dirs]) if HAS_PKG_RESOURCES and ext_type_dirs: for entry_point in pkg_resources.iter_entry_points('salt.loader', ext_type_dirs): try: loaded_entry_point = entry_point.load() for path in loaded_entry_point(): ext_type_types.append(path) except Exception as exc: log.error("Error getting module directories from %s: %s", _format_entrypoint_target(entry_point), exc) log.debug("Full backtrace for module directories error", exc_info=True) cli_module_dirs = [] # The dirs can be any module dir, or a in-tree _{ext_type} dir for _dir in opts.get('module_dirs', []): # Prepend to the list to match cli argument ordering maybe_dir = os.path.join(_dir, ext_type) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) continue maybe_dir = os.path.join(_dir, '_{0}'.format(ext_type)) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) return cli_module_dirs + ext_type_types + [ext_types, sys_types] def minion_mods( opts, context=None, utils=None, whitelist=None, initial_load=False, loaded_base_name=None, notify=False, static_modules=None, proxy=None): ''' Load execution modules Returns a dictionary of execution modules appropriate for the current system by evaluating the __virtual__() function in each module. :param dict opts: The Salt options dictionary :param dict context: A Salt context that should be made present inside generated modules in __context__ :param dict utils: Utility functions which should be made available to Salt modules in __utils__. See `utils_dirs` in salt.config for additional information about configuration. :param list whitelist: A list of modules which should be whitelisted. :param bool initial_load: Deprecated flag! Unused. :param str loaded_base_name: A string marker for the loaded base name. :param bool notify: Flag indicating that an event should be fired upon completion of module loading. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) __opts__['grains'] = __grains__ __utils__ = salt.loader.utils(__opts__) __salt__ = salt.loader.minion_mods(__opts__, utils=__utils__) __salt__['test.ping']() ''' # TODO Publish documentation for module whitelisting if not whitelist: whitelist = opts.get('whitelist_modules', None) ret = LazyLoader( _module_dirs(opts, 'modules', 'module'), opts, tag='module', pack={'__context__': context, '__utils__': utils, '__proxy__': proxy}, whitelist=whitelist, loaded_base_name=loaded_base_name, static_modules=static_modules, ) ret.pack['__salt__'] = ret # Load any provider overrides from the configuration file providers option # Note: Providers can be pkg, service, user or group - not to be confused # with cloud providers. providers = opts.get('providers', False) if providers and isinstance(providers, dict): for mod in providers: # sometimes providers opts is not to diverge modules but # for other configuration try: funcs = raw_mod(opts, providers[mod], ret) except TypeError: break else: if funcs: for func in funcs: f_key = '{0}{1}'.format(mod, func[func.rindex('.'):]) ret[f_key] = funcs[func] if notify: evt = salt.utils.event.get_event('minion', opts=opts, listen=False) evt.fire_event({'complete': True}, tag=salt.defaults.events.MINION_MOD_COMPLETE) return ret def raw_mod(opts, name, functions, mod='modules'): ''' Returns a single module loaded raw and bypassing the __virtual__ function .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') testmod = salt.loader.raw_mod(__opts__, 'test', None) testmod['test.ping']() ''' loader = LazyLoader( _module_dirs(opts, mod, 'module'), opts, tag='rawmodule', virtual_enable=False, pack={'__salt__': functions}, ) # if we don't have the module, return an empty dict if name not in loader.file_mapping: return {} loader._load_module(name) # load a single module (the one passed in) return dict(loader._dict) # return a copy of *just* the funcs for `name` def metaproxy(opts): ''' Return functions used in the meta proxy ''' return LazyLoader( _module_dirs(opts, 'metaproxy'), opts, tag='metaproxy' ) def matchers(opts): ''' Return the matcher services plugins ''' return LazyLoader( _module_dirs(opts, 'matchers'), opts, tag='matchers' ) def engines(opts, functions, runners, utils, proxy=None): ''' Return the master services plugins ''' pack = {'__salt__': functions, '__runners__': runners, '__proxy__': proxy, '__utils__': utils} return LazyLoader( _module_dirs(opts, 'engines'), opts, tag='engines', pack=pack, ) def proxy(opts, functions=None, returners=None, whitelist=None, utils=None): ''' Returns the proxy module for this salt-proxy-minion ''' ret = LazyLoader( _module_dirs(opts, 'proxy'), opts, tag='proxy', pack={'__salt__': functions, '__ret__': returners, '__utils__': utils}, ) ret.pack['__proxy__'] = ret return ret def utils(opts, whitelist=None, context=None, proxy=proxy): ''' Returns the utility modules ''' return LazyLoader( _module_dirs(opts, 'utils', ext_type_dirs='utils_dirs'), opts, tag='utils', whitelist=whitelist, pack={'__context__': context, '__proxy__': proxy or {}}, ) def pillars(opts, functions, context=None): ''' Returns the pillars modules ''' ret = LazyLoader(_module_dirs(opts, 'pillar'), opts, tag='pillar', pack={'__salt__': functions, '__context__': context, '__utils__': utils(opts)}) ret.pack['__ext_pillar__'] = ret return FilterDictWrapper(ret, '.ext_pillar') def tops(opts): ''' Returns the tops modules ''' if 'master_tops' not in opts: return {} whitelist = list(opts['master_tops'].keys()) ret = LazyLoader( _module_dirs(opts, 'tops', 'top'), opts, tag='top', whitelist=whitelist, ) return FilterDictWrapper(ret, '.top') def wheels(opts, whitelist=None, context=None): ''' Returns the wheels modules ''' if context is None: context = {} return LazyLoader( _module_dirs(opts, 'wheel'), opts, tag='wheel', whitelist=whitelist, pack={'__context__': context}, ) def outputters(opts): ''' Returns the outputters modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only outputters present in the keyspace ''' ret = LazyLoader( _module_dirs(opts, 'output', ext_type_dirs='outputter_dirs'), opts, tag='output', ) wrapped_ret = FilterDictWrapper(ret, '.output') # TODO: this name seems terrible... __salt__ should always be execution mods ret.pack['__salt__'] = wrapped_ret return wrapped_ret def serializers(opts): ''' Returns the serializers modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only serializers present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'serializers'), opts, tag='serializers', ) def eauth_tokens(opts): ''' Returns the tokens modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only token backends present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'tokens'), opts, tag='tokens', ) def auth(opts, whitelist=None): ''' Returns the auth modules :param dict opts: The Salt options dictionary :returns: LazyLoader ''' return LazyLoader( _module_dirs(opts, 'auth'), opts, tag='auth', whitelist=whitelist, pack={'__salt__': minion_mods(opts)}, ) def fileserver(opts, backends): ''' Returns the file server modules ''' return LazyLoader(_module_dirs(opts, 'fileserver'), opts, tag='fileserver', whitelist=backends, pack={'__utils__': utils(opts)}) def roster(opts, runner=None, utils=None, whitelist=None): ''' Returns the roster modules ''' return LazyLoader( _module_dirs(opts, 'roster'), opts, tag='roster', whitelist=whitelist, pack={ '__runner__': runner, '__utils__': utils, }, ) def thorium(opts, functions, runners): ''' Load the thorium runtime modules ''' pack = {'__salt__': functions, '__runner__': runners, '__context__': {}} ret = LazyLoader(_module_dirs(opts, 'thorium'), opts, tag='thorium', pack=pack) ret.pack['__thorium__'] = ret return ret def states(opts, functions, utils, serializers, whitelist=None, proxy=None, context=None): ''' Returns the state modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') statemods = salt.loader.states(__opts__, None, None) ''' if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'states'), opts, tag='states', pack={'__salt__': functions, '__proxy__': proxy or {}}, whitelist=whitelist, ) ret.pack['__states__'] = ret ret.pack['__utils__'] = utils ret.pack['__serializers__'] = serializers ret.pack['__context__'] = context return ret def beacons(opts, functions, context=None, proxy=None): ''' Load the beacon modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. ''' return LazyLoader( _module_dirs(opts, 'beacons'), opts, tag='beacons', pack={'__context__': context, '__salt__': functions, '__proxy__': proxy or {}}, virtual_funcs=[], ) def log_handlers(opts): ''' Returns the custom logging handler modules :param dict opts: The Salt options dictionary ''' ret = LazyLoader( _module_dirs( opts, 'log_handlers', int_type='handlers', base_path=os.path.join(SALT_BASE_PATH, 'log'), ), opts, tag='log_handlers', ) return FilterDictWrapper(ret, '.setup_handlers') def ssh_wrapper(opts, functions=None, context=None): ''' Returns the custom logging handler modules ''' return LazyLoader( _module_dirs( opts, 'wrapper', base_path=os.path.join(SALT_BASE_PATH, os.path.join('client', 'ssh')), ), opts, tag='wrapper', pack={ '__salt__': functions, '__grains__': opts.get('grains', {}), '__pillar__': opts.get('pillar', {}), '__context__': context, }, ) def render(opts, functions, states=None, proxy=None, context=None): ''' Returns the render modules ''' if context is None: context = {} pack = {'__salt__': functions, '__grains__': opts.get('grains', {}), '__context__': context} if states: pack['__states__'] = states pack['__proxy__'] = proxy or {} ret = LazyLoader( _module_dirs( opts, 'renderers', 'render', ext_type_dirs='render_dirs', ), opts, tag='render', pack=pack, ) rend = FilterDictWrapper(ret, '.render') if not check_render_pipe_str(opts['renderer'], rend, opts['renderer_blacklist'], opts['renderer_whitelist']): err = ('The renderer {0} is unavailable, this error is often because ' 'the needed software is unavailable'.format(opts['renderer'])) log.critical(err) raise LoaderError(err) return rend def grain_funcs(opts, proxy=None): ''' Returns the grain functions .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') grainfuncs = salt.loader.grain_funcs(__opts__) ''' ret = LazyLoader( _module_dirs( opts, 'grains', 'grain', ext_type_dirs='grains_dirs', ), opts, tag='grains', ) ret.pack['__utils__'] = utils(opts, proxy=proxy) return ret def _load_cached_grains(opts, cfn): ''' Returns the grains cached in cfn, or None if the cache is too old or is corrupted. ''' if not os.path.isfile(cfn): log.debug('Grains cache file does not exist.') return None grains_cache_age = int(time.time() - os.path.getmtime(cfn)) if grains_cache_age > opts.get('grains_cache_expiration', 300): log.debug( 'Grains cache last modified %s seconds ago and cache ' 'expiration is set to %s. Grains cache expired. ' 'Refreshing.', grains_cache_age, opts.get('grains_cache_expiration', 300) ) return None if opts.get('refresh_grains_cache', False): log.debug('refresh_grains_cache requested, Refreshing.') return None log.debug('Retrieving grains from cache') try: serial = salt.payload.Serial(opts) with salt.utils.files.fopen(cfn, 'rb') as fp_: cached_grains = salt.utils.data.decode(serial.load(fp_), preserve_tuples=True) if not cached_grains: log.debug('Cached grains are empty, cache might be corrupted. Refreshing.') return None return cached_grains except (IOError, OSError): return None def grains(opts, force_refresh=False, proxy=None): ''' Return the functions for the dynamic grains and the values for the static grains. Since grains are computed early in the startup process, grains functions do not have __salt__ or __proxy__ available. At proxy-minion startup, this function is called with the proxymodule LazyLoader object so grains functions can communicate with their controlled device. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) print __grains__['id'] ''' # Need to re-import salt.config, somehow it got lost when a minion is starting import salt.config # if we have no grains, lets try loading from disk (TODO: move to decorator?) cfn = os.path.join( opts['cachedir'], 'grains.cache.p' ) if not force_refresh and opts.get('grains_cache', False): cached_grains = _load_cached_grains(opts, cfn) if cached_grains: return cached_grains else: log.debug('Grains refresh requested. Refreshing grains.') if opts.get('skip_grains', False): return {} grains_deep_merge = opts.get('grains_deep_merge', False) is True if 'conf_file' in opts: pre_opts = {} pre_opts.update(salt.config.load_config( opts['conf_file'], 'SALT_MINION_CONFIG', salt.config.DEFAULT_MINION_OPTS['conf_file'] )) default_include = pre_opts.get( 'default_include', opts['default_include'] ) include = pre_opts.get('include', []) pre_opts.update(salt.config.include_config( default_include, opts['conf_file'], verbose=False )) pre_opts.update(salt.config.include_config( include, opts['conf_file'], verbose=True )) if 'grains' in pre_opts: opts['grains'] = pre_opts['grains'] else: opts['grains'] = {} else: opts['grains'] = {} grains_data = {} blist = opts.get('grains_blacklist', []) funcs = grain_funcs(opts, proxy=proxy) if force_refresh: # if we refresh, lets reload grain modules funcs.clear() # Run core grains for key in funcs: if not key.startswith('core.'): continue log.trace('Loading %s grain', key) ret = funcs[key]() if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) # Run the rest of the grains for key in funcs: if key.startswith('core.') or key == '_errors': continue try: # Grains are loaded too early to take advantage of the injected # __proxy__ variable. Pass an instance of that LazyLoader # here instead to grains functions if the grains functions take # one parameter. Then the grains can have access to the # proxymodule for retrieving information from the connected # device. log.trace('Loading %s grain', key) parameters = salt.utils.args.get_function_argspec(funcs[key]).args kwargs = {} if 'proxy' in parameters: kwargs['proxy'] = proxy if 'grains' in parameters: kwargs['grains'] = grains_data ret = funcs[key](**kwargs) except Exception: if salt.utils.platform.is_proxy(): log.info('The following CRITICAL message may not be an error; the proxy may not be completely established yet.') log.critical( 'Failed to load grains defined in grain file %s in ' 'function %s, error:\n', key, funcs[key], exc_info=True ) continue if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) if opts.get('proxy_merge_grains_in_module', True) and proxy: try: proxytype = proxy.opts['proxy']['proxytype'] if proxytype + '.grains' in proxy: if proxytype + '.initialized' in proxy and proxy[proxytype + '.initialized'](): try: proxytype = proxy.opts['proxy']['proxytype'] ret = proxy[proxytype + '.grains']() if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) except Exception: log.critical('Failed to run proxy\'s grains function!', exc_info=True ) except KeyError: pass grains_data.update(opts['grains']) # Write cache if enabled if opts.get('grains_cache', False): with salt.utils.files.set_umask(0o077): try: if salt.utils.platform.is_windows(): # Late import import salt.modules.cmdmod # Make sure cache file isn't read-only salt.modules.cmdmod._run_quiet('attrib -R "{0}"'.format(cfn)) with salt.utils.files.fopen(cfn, 'w+b') as fp_: try: serial = salt.payload.Serial(opts) serial.dump(grains_data, fp_) except TypeError as e: log.error('Failed to serialize grains cache: %s', e) raise # re-throw for cleanup except Exception as e: log.error('Unable to write to grains cache file %s: %s', cfn, e) # Based on the original exception, the file may or may not have been # created. If it was, we will remove it now, as the exception means # the serialized data is not to be trusted, no matter what the # exception is. if os.path.isfile(cfn): os.unlink(cfn) if grains_deep_merge: salt.utils.dictupdate.update(grains_data, opts['grains']) else: grains_data.update(opts['grains']) return salt.utils.data.decode(grains_data, preserve_tuples=True) # TODO: get rid of? Does anyone use this? You should use raw() instead def call(fun, **kwargs): ''' Directly call a function inside a loader directory ''' args = kwargs.get('args', []) dirs = kwargs.get('dirs', []) funcs = LazyLoader( [os.path.join(SALT_BASE_PATH, 'modules')] + dirs, None, tag='modules', virtual_enable=False, ) return funcs[fun](*args) def runner(opts, utils=None, context=None, whitelist=None): ''' Directly call a function inside a loader directory ''' if utils is None: utils = {} if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'runners', 'runner', ext_type_dirs='runner_dirs'), opts, tag='runners', pack={'__utils__': utils, '__context__': context}, whitelist=whitelist, ) # TODO: change from __salt__ to something else, we overload __salt__ too much ret.pack['__salt__'] = ret return ret def queues(opts): ''' Directly call a function inside a loader directory ''' return LazyLoader( _module_dirs(opts, 'queues', 'queue', ext_type_dirs='queue_dirs'), opts, tag='queues', ) def sdb(opts, functions=None, whitelist=None, utils=None): ''' Make a very small database call ''' if utils is None: utils = {} return LazyLoader( _module_dirs(opts, 'sdb'), opts, tag='sdb', pack={ '__sdb__': functions, '__opts__': opts, '__utils__': utils, '__salt__': minion_mods(opts, utils), }, whitelist=whitelist, ) def pkgdb(opts): ''' Return modules for SPM's package database .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgdb', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgdb' ) def pkgfiles(opts): ''' Return modules for SPM's file handling .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgfiles', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgfiles' ) def clouds(opts): ''' Return the cloud functions ''' # Let's bring __active_provider_name__, defaulting to None, to all cloud # drivers. This will get temporarily updated/overridden with a context # manager when needed. functions = LazyLoader( _module_dirs(opts, 'clouds', 'cloud', base_path=os.path.join(SALT_BASE_PATH, 'cloud'), int_type='clouds'), opts, tag='clouds', pack={'__utils__': salt.loader.utils(opts), '__active_provider_name__': None}, ) for funcname in LIBCLOUD_FUNCS_NOT_SUPPORTED: log.trace( '\'%s\' has been marked as not supported. Removing from the ' 'list of supported cloud functions', funcname ) functions.pop(funcname, None) return functions def netapi(opts): ''' Return the network api functions ''' return LazyLoader( _module_dirs(opts, 'netapi'), opts, tag='netapi', ) def executors(opts, functions=None, context=None, proxy=None): ''' Returns the executor modules ''' executors = LazyLoader( _module_dirs(opts, 'executors', 'executor'), opts, tag='executor', pack={'__salt__': functions, '__context__': context or {}, '__proxy__': proxy or {}}, ) executors.pack['__executors__'] = executors return executors def cache(opts, serial): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'cache', 'cache'), opts, tag='cache', pack={'__opts__': opts, '__context__': {'serial': serial}}, ) def _generate_module(name): if name in sys.modules: return code = "'''Salt loaded {0} parent module'''".format(name.split('.')[-1]) # ModuleType can't accept a unicode type on PY2 module = types.ModuleType(str(name)) # future lint: disable=blacklisted-function exec(code, module.__dict__) sys.modules[name] = module def _mod_type(module_path): if module_path.startswith(SALT_BASE_PATH): return 'int' return 'ext' def _inject_into_mod(mod, name, value, force_lock=False): ''' Inject a variable into a module. This is used to inject "globals" like ``__salt__``, ``__pillar``, or ``grains``. Instead of injecting the value directly, a ``ThreadLocalProxy`` is created. If such a proxy is already present under the specified name, it is updated with the new value. This update only affects the current thread, so that the same name can refer to different values depending on the thread of execution. This is important for data that is not truly global. For example, pillar data might be dynamically overriden through function parameters and thus the actual values available in pillar might depend on the thread that is calling a module. mod: module object into which the value is going to be injected. name: name of the variable that is injected into the module. value: value that is injected into the variable. The value is not injected directly, but instead set as the new reference of the proxy that has been created for the variable. force_lock: whether the lock should be acquired before checking whether a proxy object for the specified name has already been injected into the module. If ``False`` (the default), this function checks for the module's variable without acquiring the lock and only acquires the lock if a new proxy has to be created and injected. ''' old_value = getattr(mod, name, None) # We use a double-checked locking scheme in order to avoid taking the lock # when a proxy object has already been injected. # In most programming languages, double-checked locking is considered # unsafe when used without explicit memory barriers because one might read # an uninitialized value. In CPython it is safe due to the global # interpreter lock (GIL). In Python implementations that do not have the # GIL, it could be unsafe, but at least Jython also guarantees that (for # Python objects) memory is not corrupted when writing and reading without # explicit synchronization # (http://www.jython.org/jythonbook/en/1.0/Concurrency.html). # Please note that in order to make this code safe in a runtime environment # that does not make this guarantees, it is not sufficient. The # ThreadLocalProxy must also be created with fallback_to_shared set to # False or a lock must be added to the ThreadLocalProxy. if force_lock: with _inject_into_mod.lock: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: setattr(mod, name, ThreadLocalProxy(value, True)) else: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: _inject_into_mod(mod, name, value, True) # Lock used when injecting globals. This is needed to avoid a race condition # when two threads try to load the same module concurrently. This must be # outside the loader because there might be more than one loader for the same # namespace. _inject_into_mod.lock = threading.RLock() # TODO: move somewhere else? class FilterDictWrapper(MutableMapping): ''' Create a dict which wraps another dict with a specific key suffix on get This is to replace "filter_load" ''' def __init__(self, d, suffix): self._dict = d self.suffix = suffix def __setitem__(self, key, val): self._dict[key] = val def __delitem__(self, key): del self._dict[key] def __getitem__(self, key): return self._dict[key + self.suffix] def __len__(self): return len(self._dict) def __iter__(self): for key in self._dict: if key.endswith(self.suffix): yield key.replace(self.suffix, '') class LazyLoader(salt.utils.lazy.LazyDict): ''' A pseduo-dictionary which has a set of keys which are the name of the module and function, delimited by a dot. When the value of the key is accessed, the function is then loaded from disk and into memory. .. note:: Iterating over keys will cause all modules to be loaded. :param list module_dirs: A list of directories on disk to search for modules :param dict opts: The salt options dictionary. :param str tag: The tag for the type of module to load :param func mod_type_check: A function which can be used to verify files :param dict pack: A dictionary of function to be packed into modules as they are loaded :param list whitelist: A list of modules to whitelist :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules. :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality. If not true, the module will not load. :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values are function references themselves which are loaded on-demand. # TODO: - move modules_max_memory into here - singletons (per tag) ''' mod_dict_class = salt.utils.odict.OrderedDict def __init__(self, module_dirs, opts=None, tag='module', loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, proxy=None, virtual_funcs=None, ): # pylint: disable=W0231 ''' In pack, if any of the values are None they will be replaced with an empty context-specific dict ''' self.inject_globals = {} self.pack = {} if pack is None else pack if opts is None: opts = {} threadsafety = not opts.get('multiprocessing') self.context_dict = salt.utils.context.ContextDict(threadsafe=threadsafety) self.opts = self.__prep_mod_opts(opts) self.module_dirs = module_dirs self.tag = tag self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME self.mod_type_check = mod_type_check or _mod_type if '__context__' not in self.pack: self.pack['__context__'] = None for k, v in six.iteritems(self.pack): if v is None: # if the value of a pack is None, lets make an empty dict value = self.context_dict.get(k, {}) if isinstance(value, ThreadLocalProxy): value = ThreadLocalProxy.unproxy(value) self.context_dict[k] = value self.pack[k] = salt.utils.context.NamespacedDictWrapper(self.context_dict, k) self.whitelist = whitelist self.virtual_enable = virtual_enable self.initial_load = True # names of modules that we don't have (errors, __virtual__, etc.) self.missing_modules = {} # mapping of name -> error self.loaded_modules = {} # mapping of module_name -> dict_of_functions self.loaded_files = set() # TODO: just remove them from file_mapping? self.static_modules = static_modules if static_modules else [] if virtual_funcs is None: virtual_funcs = [] self.virtual_funcs = virtual_funcs self.disabled = set( self.opts.get( 'disable_{0}{1}'.format( self.tag, '' if self.tag[-1] == 's' else 's' ), [] ) ) # A map of suffix to description for imp self.suffix_map = {} # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [''] for (suffix, mode, kind) in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) self._lock = threading.RLock() self._refresh_file_mapping() super(LazyLoader, self).__init__() # late init the lazy loader # create all of the import namespaces _generate_module('{0}.int'.format(self.loaded_base_name)) _generate_module('{0}.int.{1}'.format(self.loaded_base_name, tag)) _generate_module('{0}.ext'.format(self.loaded_base_name)) _generate_module('{0}.ext.{1}'.format(self.loaded_base_name, tag)) def __getitem__(self, item): ''' Override the __getitem__ in order to decorate the returned function if we need to last-minute inject globals ''' func = super(LazyLoader, self).__getitem__(item) if self.inject_globals: return global_injector_decorator(self.inject_globals)(func) else: return func def __getattr__(self, mod_name): ''' Allow for "direct" attribute access-- this allows jinja templates to access things like `salt.test.ping()` ''' if mod_name in ('__getstate__', '__setstate__'): return object.__getattribute__(self, mod_name) # if we have an attribute named that, lets return it. try: return object.__getattr__(self, mod_name) # pylint: disable=no-member except AttributeError: pass # otherwise we assume its jinja template access if mod_name not in self.loaded_modules and not self.loaded: for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and mod_name in self.loaded_modules: break if mod_name in self.loaded_modules: return self.loaded_modules[mod_name] else: raise AttributeError(mod_name) def missing_fun_string(self, function_name): ''' Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ''' mod_name = function_name.split('.')[0] if mod_name in self.loaded_modules: return '\'{0}\' is not available.'.format(function_name) else: try: reason = self.missing_modules[mod_name] except KeyError: return '\'{0}\' is not available.'.format(function_name) else: if reason is not None: return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason) else: return '\'{0}\' __virtual__ returned False'.format(mod_name) def _refresh_file_mapping(self): ''' refresh the mapping of the FS on disk ''' # map of suffix to description for imp if self.opts.get('cython_enable', True) is True: try: global pyximport pyximport = __import__('pyximport') # pylint: disable=import-error pyximport.install() # add to suffix_map so file_mapping will pick it up self.suffix_map['.pyx'] = tuple() except ImportError: log.info('Cython is enabled in the options but not present ' 'in the system path. Skipping Cython modules.') # Allow for zipimport of modules if self.opts.get('enable_zip_modules', True) is True: self.suffix_map['.zip'] = tuple() # allow for module dirs if USE_IMPORTLIB: self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY) else: self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY) # create mapping of filename (without suffix) to (path, suffix) # The files are added in order of priority, so order *must* be retained. self.file_mapping = salt.utils.odict.OrderedDict() opt_match = [] def _replace_pre_ext(obj): ''' Hack so we can get the optimization level that we replaced (if any) out of the re.sub call below. We use a list here because it is a persistent data structure that we will be able to access after re.sub is called. ''' opt_match.append(obj) return '' for mod_dir in self.module_dirs: try: # Make sure we have a sorted listdir in order to have # expectable override results files = sorted( x for x in os.listdir(mod_dir) if x != '__pycache__' ) except OSError: continue # Next mod_dir if six.PY3: try: pycache_files = [ os.path.join('__pycache__', x) for x in sorted(os.listdir(os.path.join(mod_dir, '__pycache__'))) ] except OSError: pass else: files.extend(pycache_files) for filename in files: try: dirname, basename = os.path.split(filename) if basename.startswith('_'): # skip private modules # log messages omitted for obviousness continue # Next filename f_noext, ext = os.path.splitext(basename) if six.PY3: f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext) try: opt_level = int( opt_match.pop().group(1).rsplit('-', 1)[-1] ) except (AttributeError, IndexError, ValueError): # No regex match or no optimization level matched opt_level = 0 try: opt_index = self.opts['optimization_order'].index(opt_level) except KeyError: log.trace( 'Disallowed optimization level %d for module ' 'name \'%s\', skipping. Add %d to the ' '\'optimization_order\' config option if you ' 'do not want to ignore this optimization ' 'level.', opt_level, f_noext, opt_level ) continue else: # Optimization level not reflected in filename on PY2 opt_index = 0 # make sure it is a suffix we support if ext not in self.suffix_map: continue # Next filename if f_noext in self.disabled: log.trace( 'Skipping %s, it is disabled by configuration', filename ) continue # Next filename fpath = os.path.join(mod_dir, filename) # if its a directory, lets allow us to load that if ext == '': # is there something __init__? subfiles = os.listdir(fpath) for suffix in self.suffix_order: if '' == suffix: continue # Next suffix (__init__ must have a suffix) init_file = '__init__{0}'.format(suffix) if init_file in subfiles: break else: continue # Next filename try: curr_ext = self.file_mapping[f_noext][1] curr_opt_index = self.file_mapping[f_noext][2] except KeyError: pass else: if '' in (curr_ext, ext) and curr_ext != ext: log.error( 'Module/package collision: \'%s\' and \'%s\'', fpath, self.file_mapping[f_noext][0] ) if six.PY3 and ext == '.pyc' and curr_ext == '.pyc': # Check the optimization level if opt_index >= curr_opt_index: # Module name match, but a higher-priority # optimization level was already matched, skipping. continue elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext): # Match found but a higher-priorty match already # exists, so skip this. continue if six.PY3 and not dirname and ext == '.pyc': # On Python 3, we should only load .pyc files from the # __pycache__ subdirectory (i.e. when dirname is not an # empty string). continue # Made it this far - add it self.file_mapping[f_noext] = (fpath, ext, opt_index) except OSError: continue for smod in self.static_modules: f_noext = smod.split('.')[-1] self.file_mapping[f_noext] = (smod, '.o', 0) def clear(self): ''' Clear the dict ''' with self._lock: super(LazyLoader, self).clear() # clear the lazy loader self.loaded_files = set() self.missing_modules = {} self.loaded_modules = {} # if we have been loaded before, lets clear the file mapping since # we obviously want a re-do if hasattr(self, 'opts'): self._refresh_file_mapping() self.initial_load = False def __prep_mod_opts(self, opts): ''' Strip out of the opts any logger instance ''' if '__grains__' not in self.pack: grains = opts.get('grains', {}) if isinstance(grains, ThreadLocalProxy): grains = ThreadLocalProxy.unproxy(grains) self.context_dict['grains'] = grains self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains') if '__pillar__' not in self.pack: pillar = opts.get('pillar', {}) if isinstance(pillar, ThreadLocalProxy): pillar = ThreadLocalProxy.unproxy(pillar) self.context_dict['pillar'] = pillar self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar') mod_opts = {} for key, val in list(opts.items()): if key == 'logger': continue mod_opts[key] = val return mod_opts def _iter_files(self, mod_name): ''' Iterate over all file_mapping files in order of closeness to mod_name ''' # do we have an exact match? if mod_name in self.file_mapping: yield mod_name # do we have a partial match? for k in self.file_mapping: if mod_name in k: yield k # anyone else? Bueller? for k in self.file_mapping: if mod_name not in k: yield k def _reload_submodules(self, mod): submodules = ( getattr(mod, sname) for sname in dir(mod) if isinstance(getattr(mod, sname), mod.__class__) ) # reload only custom "sub"modules for submodule in submodules: # it is a submodule if the name is in a namespace under mod if submodule.__name__.startswith(mod.__name__ + '.'): reload_module(submodule) self._reload_submodules(submodule) def _load_module(self, name): mod = None fpath, suffix = self.file_mapping[name][:2] self.loaded_files.add(name) fpath_dirname = os.path.dirname(fpath) try: sys.path.append(fpath_dirname) if suffix == '.pyx': mod = pyximport.load_module(name, fpath, tempfile.gettempdir()) elif suffix == '.o': top_mod = __import__(fpath, globals(), locals(), []) comps = fpath.split('.') if len(comps) < 2: mod = top_mod else: mod = top_mod for subname in comps[1:]: mod = getattr(mod, subname) elif suffix == '.zip': mod = zipimporter(fpath).load_module(name) else: desc = self.suffix_map[suffix] # if it is a directory, we don't open a file try: mod_namespace = '.'.join(( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name)) except TypeError: mod_namespace = '{0}.{1}.{2}.{3}'.format( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name) if suffix == '': if USE_IMPORTLIB: # pylint: disable=no-member # Package directory, look for __init__ loader_details = [ (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES), (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES), (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), ] file_finder = importlib.machinery.FileFinder( fpath_dirname, *loader_details ) spec = file_finder.find_spec(mod_namespace) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: mod = imp.load_module(mod_namespace, None, fpath, desc) # reload all submodules if necessary if not self.initial_load: self._reload_submodules(mod) else: if USE_IMPORTLIB: # pylint: disable=no-member loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath) spec = importlib.util.spec_from_file_location( mod_namespace, fpath, loader=loader ) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() #mod = importlib.util.module_from_spec(spec) #spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: with salt.utils.files.fopen(fpath, desc[1]) as fn_: mod = imp.load_module(mod_namespace, fn_, fpath, desc) except IOError: raise except ImportError as exc: if 'magic number' in six.text_type(exc): error_msg = 'Failed to import {0} {1}. Bad magic number. If migrating from Python2 to Python3, remove all .pyc files and try again.'.format(self.tag, name) log.warning(error_msg) self.missing_modules[name] = error_msg log.debug( 'Failed to import %s %s:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = exc return False except Exception as error: log.error( 'Failed to import %s %s, this is due most likely to a ' 'syntax error:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False except SystemExit as error: try: fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1] except Exception: pass else: tgt_fn = os.path.join('salt', 'utils', 'process.py') if fn_.endswith(tgt_fn) and '_handle_signals' in caller: # Race conditon, SIGTERM or SIGINT received while loader # was in process of loading a module. Call sys.exit to # ensure that the process is killed. sys.exit(salt.defaults.exitcodes.EX_OK) log.error( 'Failed to import %s %s as the module called exit()\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False finally: sys.path.remove(fpath_dirname) if hasattr(mod, '__opts__'): mod.__opts__.update(self.opts) else: mod.__opts__ = self.opts # pack whatever other globals we were asked to for p_name, p_value in six.iteritems(self.pack): _inject_into_mod(mod, p_name, p_value) module_name = mod.__name__.rsplit('.', 1)[-1] # Call a module's initialization method if it exists module_init = getattr(mod, '__init__', None) if inspect.isfunction(module_init): try: module_init(self.opts) except TypeError as e: log.error(e) except Exception: err_string = '__init__ failed' log.debug( 'Error loading %s.%s: %s', self.tag, module_name, err_string, exc_info=True ) self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False # if virtual modules are enabled, we need to look for the # __virtual__() function inside that module and run it. if self.virtual_enable: virtual_funcs_to_process = ['__virtual__'] + self.virtual_funcs for virtual_func in virtual_funcs_to_process: virtual_ret, module_name, virtual_err, virtual_aliases = \ self._process_virtual(mod, module_name, virtual_func) if virtual_err is not None: log.trace( 'Error loading %s.%s: %s', self.tag, module_name, virtual_err ) # if _process_virtual returned a non-True value then we are # supposed to not process this module if virtual_ret is not True and module_name not in self.missing_modules: # If a module has information about why it could not be loaded, record it self.missing_modules[module_name] = virtual_err self.missing_modules[name] = virtual_err return False else: virtual_aliases = () # If this is a proxy minion then MOST modules cannot work. Therefore, require that # any module that does work with salt-proxy-minion define __proxyenabled__ as a list # containing the names of the proxy types that the module supports. # # Render modules and state modules are OK though if 'proxy' in self.opts: if self.tag in ['grains', 'proxy']: if not hasattr(mod, '__proxyenabled__') or \ (self.opts['proxy']['proxytype'] not in mod.__proxyenabled__ and '*' not in mod.__proxyenabled__): err_string = 'not a proxy_minion enabled module' self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False if getattr(mod, '__load__', False) is not False: log.info( 'The functions from module \'%s\' are being loaded from the ' 'provided __load__ attribute', module_name ) # If we had another module by the same virtual name, we should put any # new functions under the existing dictionary. mod_names = [module_name] + list(virtual_aliases) mod_dict = dict(( (x, self.loaded_modules.get(x, self.mod_dict_class())) for x in mod_names )) for attr in getattr(mod, '__load__', dir(mod)): if attr.startswith('_') and attr != '__call__': # private functions are skipped, # except __call__ which is default entrance # for multi-function batch-like state syntax continue func = getattr(mod, attr) if not inspect.isfunction(func) and not isinstance(func, functools.partial): # Not a function!? Skip it!!! continue # Let's get the function name. # If the module has the __func_alias__ attribute, it must be a # dictionary mapping in the form of(key -> value): # <real-func-name> -> <desired-func-name> # # It default's of course to the found callable attribute name # if no alias is defined. funcname = getattr(mod, '__func_alias__', {}).get(attr, attr) for tgt_mod in mod_names: try: full_funcname = '.'.join((tgt_mod, funcname)) except TypeError: full_funcname = '{0}.{1}'.format(tgt_mod, funcname) # Save many references for lookups # Careful not to overwrite existing (higher priority) functions if full_funcname not in self._dict: self._dict[full_funcname] = func if funcname not in mod_dict[tgt_mod]: setattr(mod_dict[tgt_mod], funcname, func) mod_dict[tgt_mod][funcname] = func self._apply_outputter(func, mod) # enforce depends try: Depends.enforce_dependencies(self._dict, self.tag) except RuntimeError as exc: log.info( 'Depends.enforce_dependencies() failed for the following ' 'reason: %s', exc ) for tgt_mod in mod_names: self.loaded_modules[tgt_mod] = mod_dict[tgt_mod] return True def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise KeyError('The key \'{0}\' should contain a \'.\''.format(key)) mod_name, _ = key.split('.', 1) with self._lock: # It is possible that the key is in the dictionary after # acquiring the lock due to another thread loading it. if mod_name in self.missing_modules or key in self._dict: return True # if the modulename isn't in the whitelist, don't bother if self.whitelist and mod_name not in self.whitelist: log.error( 'Failed to load function %s because its module (%s) is ' 'not in the whitelist: %s', key, mod_name, self.whitelist ) raise KeyError(key) def _inner_load(mod_name): for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and key in self._dict: return True return False # try to load the module ret = None reloaded = False # re-scan up to once, IOErrors or a failed load cause re-scans of the # filesystem while True: try: ret = _inner_load(mod_name) if not reloaded and ret is not True: self._refresh_file_mapping() reloaded = True continue break except IOError: if not reloaded: self._refresh_file_mapping() reloaded = True continue return ret def _load_all(self): ''' Load all of them ''' with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True def reload_modules(self): with self._lock: self.loaded_files = set() self._load_all() def _apply_outputter(self, func, mod): ''' Apply the __outputter__ variable to the functions ''' if hasattr(mod, '__outputter__'): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__] def _process_virtual(self, mod, module_name, virtual_func='__virtual__'): ''' Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1] ''' # The __virtual__ function will return either a True or False value. # If it returns a True value it can also set a module level attribute # named __virtualname__ with the name that the module should be # referred to as. # # This allows us to have things like the pkg module working on all # platforms under the name 'pkg'. It also allows for modules like # augeas_cfg to be referred to as 'augeas', which would otherwise have # namespace collisions. And finally it allows modules to return False # if they are not intended to run on the given platform or are missing # dependencies. virtual_aliases = getattr(mod, '__virtual_aliases__', tuple()) try: error_reason = None if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__): try: start = time.time() virtual = getattr(mod, virtual_func)() if isinstance(virtual, tuple): error_reason = virtual[1] virtual = virtual[0] if self.opts.get('virtual_timer', False): end = time.time() - start msg = 'Virtual function took {0} seconds for {1}'.format( end, module_name) log.warning(msg) except Exception as exc: error_reason = ( 'Exception raised when processing __virtual__ function' ' for {0}. Module will not be loaded: {1}'.format( mod.__name__, exc)) log.error(error_reason, exc_info_on_loglevel=logging.DEBUG) virtual = None # Get the module's virtual name virtualname = getattr(mod, '__virtualname__', virtual) if not virtual: # if __virtual__() evaluates to False then the module # wasn't meant for this platform or it's not supposed to # load for some other reason. # Some modules might accidentally return None and are # improperly loaded if virtual is None: log.warning( '%s.__virtual__() is wrongly returning `None`. ' 'It should either return `True`, `False` or a new ' 'name. If you\'re the developer of the module ' '\'%s\', please fix this.', mod.__name__, module_name ) return (False, module_name, error_reason, virtual_aliases) # At this point, __virtual__ did not return a # boolean value, let's check for deprecated usage # or module renames if virtual is not True and module_name != virtual: # The module is renaming itself. Updating the module name # with the new name log.trace('Loaded %s as virtual %s', module_name, virtual) if virtualname != virtual: # The __virtualname__ attribute does not match what's # being returned by the __virtual__() function. This # should be considered an error. log.error( 'The module \'%s\' is showing some bad usage. Its ' '__virtualname__ attribute is set to \'%s\' yet the ' '__virtual__() function is returning \'%s\'. These ' 'values should match!', mod.__name__, virtualname, virtual ) module_name = virtualname # If the __virtual__ function returns True and __virtualname__ # is set then use it elif virtual is True and virtualname != module_name: if virtualname is not True: module_name = virtualname except KeyError: # Key errors come out of the virtual function when passing # in incomplete grains sets, these can be safely ignored # and logged to debug, still, it includes the traceback to # help debugging. log.debug('KeyError when loading %s', module_name, exc_info=True) except Exception: # If the module throws an exception during __virtual__() # then log the information and continue to the next. log.error( 'Failed to read the virtual function for %s: %s', self.tag, module_name, exc_info=True ) return (False, module_name, error_reason, virtual_aliases) return (True, module_name, None, virtual_aliases) def global_injector_decorator(inject_globals): ''' Decorator used by the LazyLoader to inject globals into a function at execute time. globals Dictionary with global variables to inject ''' def inner_decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): with salt.utils.context.func_globals_inject(f, **inject_globals): return f(*args, **kwargs) return wrapper return inner_decorator
saltstack/salt
salt/loader.py
utils
python
def utils(opts, whitelist=None, context=None, proxy=proxy): ''' Returns the utility modules ''' return LazyLoader( _module_dirs(opts, 'utils', ext_type_dirs='utils_dirs'), opts, tag='utils', whitelist=whitelist, pack={'__context__': context, '__proxy__': proxy or {}}, )
Returns the utility modules
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L386-L396
null
# -*- coding: utf-8 -*- ''' The Salt loader is the core to Salt's plugin system, the loader scans directories for python loadable code and organizes the code into the plugin interfaces used by Salt. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import sys import time import logging import inspect import tempfile import threading import functools import threading import traceback import types from zipimport import zipimporter # Import salt libs import salt.config import salt.defaults.events import salt.defaults.exitcodes import salt.syspaths import salt.utils.args import salt.utils.context import salt.utils.data import salt.utils.dictupdate import salt.utils.event import salt.utils.files import salt.utils.lazy import salt.utils.odict import salt.utils.platform import salt.utils.versions import salt.utils.stringutils from salt.exceptions import LoaderError from salt.template import check_render_pipe_str from salt.utils.decorators import Depends from salt.utils.thread_local_proxy import ThreadLocalProxy # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import reload_module if sys.version_info[:2] >= (3, 5): import importlib.machinery # pylint: disable=no-name-in-module,import-error import importlib.util # pylint: disable=no-name-in-module,import-error USE_IMPORTLIB = True else: import imp USE_IMPORTLIB = False try: from collections.abc import MutableMapping except ImportError: from collections import MutableMapping try: import pkg_resources HAS_PKG_RESOURCES = True except ImportError: HAS_PKG_RESOURCES = False log = logging.getLogger(__name__) SALT_BASE_PATH = os.path.abspath(salt.syspaths.INSTALL_DIR) LOADED_BASE_NAME = 'salt.loaded' if USE_IMPORTLIB: # pylint: disable=no-member MODULE_KIND_SOURCE = 1 MODULE_KIND_COMPILED = 2 MODULE_KIND_EXTENSION = 3 MODULE_KIND_PKG_DIRECTORY = 5 SUFFIXES = [] for suffix in importlib.machinery.EXTENSION_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_EXTENSION)) for suffix in importlib.machinery.SOURCE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_SOURCE)) for suffix in importlib.machinery.BYTECODE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_COMPILED)) MODULE_KIND_MAP = { MODULE_KIND_SOURCE: importlib.machinery.SourceFileLoader, MODULE_KIND_COMPILED: importlib.machinery.SourcelessFileLoader, MODULE_KIND_EXTENSION: importlib.machinery.ExtensionFileLoader } # pylint: enable=no-member else: SUFFIXES = imp.get_suffixes() PY3_PRE_EXT = \ re.compile(r'\.cpython-{0}{1}(\.opt-[1-9])?'.format(*sys.version_info[:2])) # Because on the cloud drivers we do `from salt.cloud.libcloudfuncs import *` # which simplifies code readability, it adds some unsupported functions into # the driver's module scope. # We list un-supported functions here. These will be removed from the loaded. # TODO: remove the need for this cross-module code. Maybe use NotImplemented LIBCLOUD_FUNCS_NOT_SUPPORTED = ( 'parallels.avail_sizes', 'parallels.avail_locations', 'proxmox.avail_sizes', ) # Will be set to pyximport module at runtime if cython is enabled in config. pyximport = None def static_loader( opts, ext_type, tag, pack=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, filter_name=None, ): funcs = LazyLoader( _module_dirs( opts, ext_type, tag, int_type, ext_dirs, ext_type_dirs, base_path, ), opts, tag=tag, pack=pack, ) ret = {} funcs._load_all() if filter_name: funcs = FilterDictWrapper(funcs, filter_name) for key in funcs: ret[key] = funcs[key] return ret def _format_entrypoint_target(ep): ''' Makes a string describing the target of an EntryPoint object. Base strongly on EntryPoint.__str__(). ''' s = ep.module_name if ep.attrs: s += ':' + '.'.join(ep.attrs) return s def _module_dirs( opts, ext_type, tag=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, ): if tag is None: tag = ext_type sys_types = os.path.join(base_path or SALT_BASE_PATH, int_type or ext_type) ext_types = os.path.join(opts['extension_modules'], ext_type) ext_type_types = [] if ext_dirs: if ext_type_dirs is None: ext_type_dirs = '{0}_dirs'.format(tag) if ext_type_dirs in opts: ext_type_types.extend(opts[ext_type_dirs]) if HAS_PKG_RESOURCES and ext_type_dirs: for entry_point in pkg_resources.iter_entry_points('salt.loader', ext_type_dirs): try: loaded_entry_point = entry_point.load() for path in loaded_entry_point(): ext_type_types.append(path) except Exception as exc: log.error("Error getting module directories from %s: %s", _format_entrypoint_target(entry_point), exc) log.debug("Full backtrace for module directories error", exc_info=True) cli_module_dirs = [] # The dirs can be any module dir, or a in-tree _{ext_type} dir for _dir in opts.get('module_dirs', []): # Prepend to the list to match cli argument ordering maybe_dir = os.path.join(_dir, ext_type) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) continue maybe_dir = os.path.join(_dir, '_{0}'.format(ext_type)) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) return cli_module_dirs + ext_type_types + [ext_types, sys_types] def minion_mods( opts, context=None, utils=None, whitelist=None, initial_load=False, loaded_base_name=None, notify=False, static_modules=None, proxy=None): ''' Load execution modules Returns a dictionary of execution modules appropriate for the current system by evaluating the __virtual__() function in each module. :param dict opts: The Salt options dictionary :param dict context: A Salt context that should be made present inside generated modules in __context__ :param dict utils: Utility functions which should be made available to Salt modules in __utils__. See `utils_dirs` in salt.config for additional information about configuration. :param list whitelist: A list of modules which should be whitelisted. :param bool initial_load: Deprecated flag! Unused. :param str loaded_base_name: A string marker for the loaded base name. :param bool notify: Flag indicating that an event should be fired upon completion of module loading. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) __opts__['grains'] = __grains__ __utils__ = salt.loader.utils(__opts__) __salt__ = salt.loader.minion_mods(__opts__, utils=__utils__) __salt__['test.ping']() ''' # TODO Publish documentation for module whitelisting if not whitelist: whitelist = opts.get('whitelist_modules', None) ret = LazyLoader( _module_dirs(opts, 'modules', 'module'), opts, tag='module', pack={'__context__': context, '__utils__': utils, '__proxy__': proxy}, whitelist=whitelist, loaded_base_name=loaded_base_name, static_modules=static_modules, ) ret.pack['__salt__'] = ret # Load any provider overrides from the configuration file providers option # Note: Providers can be pkg, service, user or group - not to be confused # with cloud providers. providers = opts.get('providers', False) if providers and isinstance(providers, dict): for mod in providers: # sometimes providers opts is not to diverge modules but # for other configuration try: funcs = raw_mod(opts, providers[mod], ret) except TypeError: break else: if funcs: for func in funcs: f_key = '{0}{1}'.format(mod, func[func.rindex('.'):]) ret[f_key] = funcs[func] if notify: evt = salt.utils.event.get_event('minion', opts=opts, listen=False) evt.fire_event({'complete': True}, tag=salt.defaults.events.MINION_MOD_COMPLETE) return ret def raw_mod(opts, name, functions, mod='modules'): ''' Returns a single module loaded raw and bypassing the __virtual__ function .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') testmod = salt.loader.raw_mod(__opts__, 'test', None) testmod['test.ping']() ''' loader = LazyLoader( _module_dirs(opts, mod, 'module'), opts, tag='rawmodule', virtual_enable=False, pack={'__salt__': functions}, ) # if we don't have the module, return an empty dict if name not in loader.file_mapping: return {} loader._load_module(name) # load a single module (the one passed in) return dict(loader._dict) # return a copy of *just* the funcs for `name` def metaproxy(opts): ''' Return functions used in the meta proxy ''' return LazyLoader( _module_dirs(opts, 'metaproxy'), opts, tag='metaproxy' ) def matchers(opts): ''' Return the matcher services plugins ''' return LazyLoader( _module_dirs(opts, 'matchers'), opts, tag='matchers' ) def engines(opts, functions, runners, utils, proxy=None): ''' Return the master services plugins ''' pack = {'__salt__': functions, '__runners__': runners, '__proxy__': proxy, '__utils__': utils} return LazyLoader( _module_dirs(opts, 'engines'), opts, tag='engines', pack=pack, ) def proxy(opts, functions=None, returners=None, whitelist=None, utils=None): ''' Returns the proxy module for this salt-proxy-minion ''' ret = LazyLoader( _module_dirs(opts, 'proxy'), opts, tag='proxy', pack={'__salt__': functions, '__ret__': returners, '__utils__': utils}, ) ret.pack['__proxy__'] = ret return ret def returners(opts, functions, whitelist=None, context=None, proxy=None): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'returners', 'returner'), opts, tag='returner', whitelist=whitelist, pack={'__salt__': functions, '__context__': context, '__proxy__': proxy or {}}, ) def pillars(opts, functions, context=None): ''' Returns the pillars modules ''' ret = LazyLoader(_module_dirs(opts, 'pillar'), opts, tag='pillar', pack={'__salt__': functions, '__context__': context, '__utils__': utils(opts)}) ret.pack['__ext_pillar__'] = ret return FilterDictWrapper(ret, '.ext_pillar') def tops(opts): ''' Returns the tops modules ''' if 'master_tops' not in opts: return {} whitelist = list(opts['master_tops'].keys()) ret = LazyLoader( _module_dirs(opts, 'tops', 'top'), opts, tag='top', whitelist=whitelist, ) return FilterDictWrapper(ret, '.top') def wheels(opts, whitelist=None, context=None): ''' Returns the wheels modules ''' if context is None: context = {} return LazyLoader( _module_dirs(opts, 'wheel'), opts, tag='wheel', whitelist=whitelist, pack={'__context__': context}, ) def outputters(opts): ''' Returns the outputters modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only outputters present in the keyspace ''' ret = LazyLoader( _module_dirs(opts, 'output', ext_type_dirs='outputter_dirs'), opts, tag='output', ) wrapped_ret = FilterDictWrapper(ret, '.output') # TODO: this name seems terrible... __salt__ should always be execution mods ret.pack['__salt__'] = wrapped_ret return wrapped_ret def serializers(opts): ''' Returns the serializers modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only serializers present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'serializers'), opts, tag='serializers', ) def eauth_tokens(opts): ''' Returns the tokens modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only token backends present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'tokens'), opts, tag='tokens', ) def auth(opts, whitelist=None): ''' Returns the auth modules :param dict opts: The Salt options dictionary :returns: LazyLoader ''' return LazyLoader( _module_dirs(opts, 'auth'), opts, tag='auth', whitelist=whitelist, pack={'__salt__': minion_mods(opts)}, ) def fileserver(opts, backends): ''' Returns the file server modules ''' return LazyLoader(_module_dirs(opts, 'fileserver'), opts, tag='fileserver', whitelist=backends, pack={'__utils__': utils(opts)}) def roster(opts, runner=None, utils=None, whitelist=None): ''' Returns the roster modules ''' return LazyLoader( _module_dirs(opts, 'roster'), opts, tag='roster', whitelist=whitelist, pack={ '__runner__': runner, '__utils__': utils, }, ) def thorium(opts, functions, runners): ''' Load the thorium runtime modules ''' pack = {'__salt__': functions, '__runner__': runners, '__context__': {}} ret = LazyLoader(_module_dirs(opts, 'thorium'), opts, tag='thorium', pack=pack) ret.pack['__thorium__'] = ret return ret def states(opts, functions, utils, serializers, whitelist=None, proxy=None, context=None): ''' Returns the state modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') statemods = salt.loader.states(__opts__, None, None) ''' if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'states'), opts, tag='states', pack={'__salt__': functions, '__proxy__': proxy or {}}, whitelist=whitelist, ) ret.pack['__states__'] = ret ret.pack['__utils__'] = utils ret.pack['__serializers__'] = serializers ret.pack['__context__'] = context return ret def beacons(opts, functions, context=None, proxy=None): ''' Load the beacon modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. ''' return LazyLoader( _module_dirs(opts, 'beacons'), opts, tag='beacons', pack={'__context__': context, '__salt__': functions, '__proxy__': proxy or {}}, virtual_funcs=[], ) def log_handlers(opts): ''' Returns the custom logging handler modules :param dict opts: The Salt options dictionary ''' ret = LazyLoader( _module_dirs( opts, 'log_handlers', int_type='handlers', base_path=os.path.join(SALT_BASE_PATH, 'log'), ), opts, tag='log_handlers', ) return FilterDictWrapper(ret, '.setup_handlers') def ssh_wrapper(opts, functions=None, context=None): ''' Returns the custom logging handler modules ''' return LazyLoader( _module_dirs( opts, 'wrapper', base_path=os.path.join(SALT_BASE_PATH, os.path.join('client', 'ssh')), ), opts, tag='wrapper', pack={ '__salt__': functions, '__grains__': opts.get('grains', {}), '__pillar__': opts.get('pillar', {}), '__context__': context, }, ) def render(opts, functions, states=None, proxy=None, context=None): ''' Returns the render modules ''' if context is None: context = {} pack = {'__salt__': functions, '__grains__': opts.get('grains', {}), '__context__': context} if states: pack['__states__'] = states pack['__proxy__'] = proxy or {} ret = LazyLoader( _module_dirs( opts, 'renderers', 'render', ext_type_dirs='render_dirs', ), opts, tag='render', pack=pack, ) rend = FilterDictWrapper(ret, '.render') if not check_render_pipe_str(opts['renderer'], rend, opts['renderer_blacklist'], opts['renderer_whitelist']): err = ('The renderer {0} is unavailable, this error is often because ' 'the needed software is unavailable'.format(opts['renderer'])) log.critical(err) raise LoaderError(err) return rend def grain_funcs(opts, proxy=None): ''' Returns the grain functions .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') grainfuncs = salt.loader.grain_funcs(__opts__) ''' ret = LazyLoader( _module_dirs( opts, 'grains', 'grain', ext_type_dirs='grains_dirs', ), opts, tag='grains', ) ret.pack['__utils__'] = utils(opts, proxy=proxy) return ret def _load_cached_grains(opts, cfn): ''' Returns the grains cached in cfn, or None if the cache is too old or is corrupted. ''' if not os.path.isfile(cfn): log.debug('Grains cache file does not exist.') return None grains_cache_age = int(time.time() - os.path.getmtime(cfn)) if grains_cache_age > opts.get('grains_cache_expiration', 300): log.debug( 'Grains cache last modified %s seconds ago and cache ' 'expiration is set to %s. Grains cache expired. ' 'Refreshing.', grains_cache_age, opts.get('grains_cache_expiration', 300) ) return None if opts.get('refresh_grains_cache', False): log.debug('refresh_grains_cache requested, Refreshing.') return None log.debug('Retrieving grains from cache') try: serial = salt.payload.Serial(opts) with salt.utils.files.fopen(cfn, 'rb') as fp_: cached_grains = salt.utils.data.decode(serial.load(fp_), preserve_tuples=True) if not cached_grains: log.debug('Cached grains are empty, cache might be corrupted. Refreshing.') return None return cached_grains except (IOError, OSError): return None def grains(opts, force_refresh=False, proxy=None): ''' Return the functions for the dynamic grains and the values for the static grains. Since grains are computed early in the startup process, grains functions do not have __salt__ or __proxy__ available. At proxy-minion startup, this function is called with the proxymodule LazyLoader object so grains functions can communicate with their controlled device. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) print __grains__['id'] ''' # Need to re-import salt.config, somehow it got lost when a minion is starting import salt.config # if we have no grains, lets try loading from disk (TODO: move to decorator?) cfn = os.path.join( opts['cachedir'], 'grains.cache.p' ) if not force_refresh and opts.get('grains_cache', False): cached_grains = _load_cached_grains(opts, cfn) if cached_grains: return cached_grains else: log.debug('Grains refresh requested. Refreshing grains.') if opts.get('skip_grains', False): return {} grains_deep_merge = opts.get('grains_deep_merge', False) is True if 'conf_file' in opts: pre_opts = {} pre_opts.update(salt.config.load_config( opts['conf_file'], 'SALT_MINION_CONFIG', salt.config.DEFAULT_MINION_OPTS['conf_file'] )) default_include = pre_opts.get( 'default_include', opts['default_include'] ) include = pre_opts.get('include', []) pre_opts.update(salt.config.include_config( default_include, opts['conf_file'], verbose=False )) pre_opts.update(salt.config.include_config( include, opts['conf_file'], verbose=True )) if 'grains' in pre_opts: opts['grains'] = pre_opts['grains'] else: opts['grains'] = {} else: opts['grains'] = {} grains_data = {} blist = opts.get('grains_blacklist', []) funcs = grain_funcs(opts, proxy=proxy) if force_refresh: # if we refresh, lets reload grain modules funcs.clear() # Run core grains for key in funcs: if not key.startswith('core.'): continue log.trace('Loading %s grain', key) ret = funcs[key]() if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) # Run the rest of the grains for key in funcs: if key.startswith('core.') or key == '_errors': continue try: # Grains are loaded too early to take advantage of the injected # __proxy__ variable. Pass an instance of that LazyLoader # here instead to grains functions if the grains functions take # one parameter. Then the grains can have access to the # proxymodule for retrieving information from the connected # device. log.trace('Loading %s grain', key) parameters = salt.utils.args.get_function_argspec(funcs[key]).args kwargs = {} if 'proxy' in parameters: kwargs['proxy'] = proxy if 'grains' in parameters: kwargs['grains'] = grains_data ret = funcs[key](**kwargs) except Exception: if salt.utils.platform.is_proxy(): log.info('The following CRITICAL message may not be an error; the proxy may not be completely established yet.') log.critical( 'Failed to load grains defined in grain file %s in ' 'function %s, error:\n', key, funcs[key], exc_info=True ) continue if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) if opts.get('proxy_merge_grains_in_module', True) and proxy: try: proxytype = proxy.opts['proxy']['proxytype'] if proxytype + '.grains' in proxy: if proxytype + '.initialized' in proxy and proxy[proxytype + '.initialized'](): try: proxytype = proxy.opts['proxy']['proxytype'] ret = proxy[proxytype + '.grains']() if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) except Exception: log.critical('Failed to run proxy\'s grains function!', exc_info=True ) except KeyError: pass grains_data.update(opts['grains']) # Write cache if enabled if opts.get('grains_cache', False): with salt.utils.files.set_umask(0o077): try: if salt.utils.platform.is_windows(): # Late import import salt.modules.cmdmod # Make sure cache file isn't read-only salt.modules.cmdmod._run_quiet('attrib -R "{0}"'.format(cfn)) with salt.utils.files.fopen(cfn, 'w+b') as fp_: try: serial = salt.payload.Serial(opts) serial.dump(grains_data, fp_) except TypeError as e: log.error('Failed to serialize grains cache: %s', e) raise # re-throw for cleanup except Exception as e: log.error('Unable to write to grains cache file %s: %s', cfn, e) # Based on the original exception, the file may or may not have been # created. If it was, we will remove it now, as the exception means # the serialized data is not to be trusted, no matter what the # exception is. if os.path.isfile(cfn): os.unlink(cfn) if grains_deep_merge: salt.utils.dictupdate.update(grains_data, opts['grains']) else: grains_data.update(opts['grains']) return salt.utils.data.decode(grains_data, preserve_tuples=True) # TODO: get rid of? Does anyone use this? You should use raw() instead def call(fun, **kwargs): ''' Directly call a function inside a loader directory ''' args = kwargs.get('args', []) dirs = kwargs.get('dirs', []) funcs = LazyLoader( [os.path.join(SALT_BASE_PATH, 'modules')] + dirs, None, tag='modules', virtual_enable=False, ) return funcs[fun](*args) def runner(opts, utils=None, context=None, whitelist=None): ''' Directly call a function inside a loader directory ''' if utils is None: utils = {} if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'runners', 'runner', ext_type_dirs='runner_dirs'), opts, tag='runners', pack={'__utils__': utils, '__context__': context}, whitelist=whitelist, ) # TODO: change from __salt__ to something else, we overload __salt__ too much ret.pack['__salt__'] = ret return ret def queues(opts): ''' Directly call a function inside a loader directory ''' return LazyLoader( _module_dirs(opts, 'queues', 'queue', ext_type_dirs='queue_dirs'), opts, tag='queues', ) def sdb(opts, functions=None, whitelist=None, utils=None): ''' Make a very small database call ''' if utils is None: utils = {} return LazyLoader( _module_dirs(opts, 'sdb'), opts, tag='sdb', pack={ '__sdb__': functions, '__opts__': opts, '__utils__': utils, '__salt__': minion_mods(opts, utils), }, whitelist=whitelist, ) def pkgdb(opts): ''' Return modules for SPM's package database .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgdb', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgdb' ) def pkgfiles(opts): ''' Return modules for SPM's file handling .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgfiles', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgfiles' ) def clouds(opts): ''' Return the cloud functions ''' # Let's bring __active_provider_name__, defaulting to None, to all cloud # drivers. This will get temporarily updated/overridden with a context # manager when needed. functions = LazyLoader( _module_dirs(opts, 'clouds', 'cloud', base_path=os.path.join(SALT_BASE_PATH, 'cloud'), int_type='clouds'), opts, tag='clouds', pack={'__utils__': salt.loader.utils(opts), '__active_provider_name__': None}, ) for funcname in LIBCLOUD_FUNCS_NOT_SUPPORTED: log.trace( '\'%s\' has been marked as not supported. Removing from the ' 'list of supported cloud functions', funcname ) functions.pop(funcname, None) return functions def netapi(opts): ''' Return the network api functions ''' return LazyLoader( _module_dirs(opts, 'netapi'), opts, tag='netapi', ) def executors(opts, functions=None, context=None, proxy=None): ''' Returns the executor modules ''' executors = LazyLoader( _module_dirs(opts, 'executors', 'executor'), opts, tag='executor', pack={'__salt__': functions, '__context__': context or {}, '__proxy__': proxy or {}}, ) executors.pack['__executors__'] = executors return executors def cache(opts, serial): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'cache', 'cache'), opts, tag='cache', pack={'__opts__': opts, '__context__': {'serial': serial}}, ) def _generate_module(name): if name in sys.modules: return code = "'''Salt loaded {0} parent module'''".format(name.split('.')[-1]) # ModuleType can't accept a unicode type on PY2 module = types.ModuleType(str(name)) # future lint: disable=blacklisted-function exec(code, module.__dict__) sys.modules[name] = module def _mod_type(module_path): if module_path.startswith(SALT_BASE_PATH): return 'int' return 'ext' def _inject_into_mod(mod, name, value, force_lock=False): ''' Inject a variable into a module. This is used to inject "globals" like ``__salt__``, ``__pillar``, or ``grains``. Instead of injecting the value directly, a ``ThreadLocalProxy`` is created. If such a proxy is already present under the specified name, it is updated with the new value. This update only affects the current thread, so that the same name can refer to different values depending on the thread of execution. This is important for data that is not truly global. For example, pillar data might be dynamically overriden through function parameters and thus the actual values available in pillar might depend on the thread that is calling a module. mod: module object into which the value is going to be injected. name: name of the variable that is injected into the module. value: value that is injected into the variable. The value is not injected directly, but instead set as the new reference of the proxy that has been created for the variable. force_lock: whether the lock should be acquired before checking whether a proxy object for the specified name has already been injected into the module. If ``False`` (the default), this function checks for the module's variable without acquiring the lock and only acquires the lock if a new proxy has to be created and injected. ''' old_value = getattr(mod, name, None) # We use a double-checked locking scheme in order to avoid taking the lock # when a proxy object has already been injected. # In most programming languages, double-checked locking is considered # unsafe when used without explicit memory barriers because one might read # an uninitialized value. In CPython it is safe due to the global # interpreter lock (GIL). In Python implementations that do not have the # GIL, it could be unsafe, but at least Jython also guarantees that (for # Python objects) memory is not corrupted when writing and reading without # explicit synchronization # (http://www.jython.org/jythonbook/en/1.0/Concurrency.html). # Please note that in order to make this code safe in a runtime environment # that does not make this guarantees, it is not sufficient. The # ThreadLocalProxy must also be created with fallback_to_shared set to # False or a lock must be added to the ThreadLocalProxy. if force_lock: with _inject_into_mod.lock: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: setattr(mod, name, ThreadLocalProxy(value, True)) else: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: _inject_into_mod(mod, name, value, True) # Lock used when injecting globals. This is needed to avoid a race condition # when two threads try to load the same module concurrently. This must be # outside the loader because there might be more than one loader for the same # namespace. _inject_into_mod.lock = threading.RLock() # TODO: move somewhere else? class FilterDictWrapper(MutableMapping): ''' Create a dict which wraps another dict with a specific key suffix on get This is to replace "filter_load" ''' def __init__(self, d, suffix): self._dict = d self.suffix = suffix def __setitem__(self, key, val): self._dict[key] = val def __delitem__(self, key): del self._dict[key] def __getitem__(self, key): return self._dict[key + self.suffix] def __len__(self): return len(self._dict) def __iter__(self): for key in self._dict: if key.endswith(self.suffix): yield key.replace(self.suffix, '') class LazyLoader(salt.utils.lazy.LazyDict): ''' A pseduo-dictionary which has a set of keys which are the name of the module and function, delimited by a dot. When the value of the key is accessed, the function is then loaded from disk and into memory. .. note:: Iterating over keys will cause all modules to be loaded. :param list module_dirs: A list of directories on disk to search for modules :param dict opts: The salt options dictionary. :param str tag: The tag for the type of module to load :param func mod_type_check: A function which can be used to verify files :param dict pack: A dictionary of function to be packed into modules as they are loaded :param list whitelist: A list of modules to whitelist :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules. :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality. If not true, the module will not load. :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values are function references themselves which are loaded on-demand. # TODO: - move modules_max_memory into here - singletons (per tag) ''' mod_dict_class = salt.utils.odict.OrderedDict def __init__(self, module_dirs, opts=None, tag='module', loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, proxy=None, virtual_funcs=None, ): # pylint: disable=W0231 ''' In pack, if any of the values are None they will be replaced with an empty context-specific dict ''' self.inject_globals = {} self.pack = {} if pack is None else pack if opts is None: opts = {} threadsafety = not opts.get('multiprocessing') self.context_dict = salt.utils.context.ContextDict(threadsafe=threadsafety) self.opts = self.__prep_mod_opts(opts) self.module_dirs = module_dirs self.tag = tag self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME self.mod_type_check = mod_type_check or _mod_type if '__context__' not in self.pack: self.pack['__context__'] = None for k, v in six.iteritems(self.pack): if v is None: # if the value of a pack is None, lets make an empty dict value = self.context_dict.get(k, {}) if isinstance(value, ThreadLocalProxy): value = ThreadLocalProxy.unproxy(value) self.context_dict[k] = value self.pack[k] = salt.utils.context.NamespacedDictWrapper(self.context_dict, k) self.whitelist = whitelist self.virtual_enable = virtual_enable self.initial_load = True # names of modules that we don't have (errors, __virtual__, etc.) self.missing_modules = {} # mapping of name -> error self.loaded_modules = {} # mapping of module_name -> dict_of_functions self.loaded_files = set() # TODO: just remove them from file_mapping? self.static_modules = static_modules if static_modules else [] if virtual_funcs is None: virtual_funcs = [] self.virtual_funcs = virtual_funcs self.disabled = set( self.opts.get( 'disable_{0}{1}'.format( self.tag, '' if self.tag[-1] == 's' else 's' ), [] ) ) # A map of suffix to description for imp self.suffix_map = {} # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [''] for (suffix, mode, kind) in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) self._lock = threading.RLock() self._refresh_file_mapping() super(LazyLoader, self).__init__() # late init the lazy loader # create all of the import namespaces _generate_module('{0}.int'.format(self.loaded_base_name)) _generate_module('{0}.int.{1}'.format(self.loaded_base_name, tag)) _generate_module('{0}.ext'.format(self.loaded_base_name)) _generate_module('{0}.ext.{1}'.format(self.loaded_base_name, tag)) def __getitem__(self, item): ''' Override the __getitem__ in order to decorate the returned function if we need to last-minute inject globals ''' func = super(LazyLoader, self).__getitem__(item) if self.inject_globals: return global_injector_decorator(self.inject_globals)(func) else: return func def __getattr__(self, mod_name): ''' Allow for "direct" attribute access-- this allows jinja templates to access things like `salt.test.ping()` ''' if mod_name in ('__getstate__', '__setstate__'): return object.__getattribute__(self, mod_name) # if we have an attribute named that, lets return it. try: return object.__getattr__(self, mod_name) # pylint: disable=no-member except AttributeError: pass # otherwise we assume its jinja template access if mod_name not in self.loaded_modules and not self.loaded: for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and mod_name in self.loaded_modules: break if mod_name in self.loaded_modules: return self.loaded_modules[mod_name] else: raise AttributeError(mod_name) def missing_fun_string(self, function_name): ''' Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ''' mod_name = function_name.split('.')[0] if mod_name in self.loaded_modules: return '\'{0}\' is not available.'.format(function_name) else: try: reason = self.missing_modules[mod_name] except KeyError: return '\'{0}\' is not available.'.format(function_name) else: if reason is not None: return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason) else: return '\'{0}\' __virtual__ returned False'.format(mod_name) def _refresh_file_mapping(self): ''' refresh the mapping of the FS on disk ''' # map of suffix to description for imp if self.opts.get('cython_enable', True) is True: try: global pyximport pyximport = __import__('pyximport') # pylint: disable=import-error pyximport.install() # add to suffix_map so file_mapping will pick it up self.suffix_map['.pyx'] = tuple() except ImportError: log.info('Cython is enabled in the options but not present ' 'in the system path. Skipping Cython modules.') # Allow for zipimport of modules if self.opts.get('enable_zip_modules', True) is True: self.suffix_map['.zip'] = tuple() # allow for module dirs if USE_IMPORTLIB: self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY) else: self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY) # create mapping of filename (without suffix) to (path, suffix) # The files are added in order of priority, so order *must* be retained. self.file_mapping = salt.utils.odict.OrderedDict() opt_match = [] def _replace_pre_ext(obj): ''' Hack so we can get the optimization level that we replaced (if any) out of the re.sub call below. We use a list here because it is a persistent data structure that we will be able to access after re.sub is called. ''' opt_match.append(obj) return '' for mod_dir in self.module_dirs: try: # Make sure we have a sorted listdir in order to have # expectable override results files = sorted( x for x in os.listdir(mod_dir) if x != '__pycache__' ) except OSError: continue # Next mod_dir if six.PY3: try: pycache_files = [ os.path.join('__pycache__', x) for x in sorted(os.listdir(os.path.join(mod_dir, '__pycache__'))) ] except OSError: pass else: files.extend(pycache_files) for filename in files: try: dirname, basename = os.path.split(filename) if basename.startswith('_'): # skip private modules # log messages omitted for obviousness continue # Next filename f_noext, ext = os.path.splitext(basename) if six.PY3: f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext) try: opt_level = int( opt_match.pop().group(1).rsplit('-', 1)[-1] ) except (AttributeError, IndexError, ValueError): # No regex match or no optimization level matched opt_level = 0 try: opt_index = self.opts['optimization_order'].index(opt_level) except KeyError: log.trace( 'Disallowed optimization level %d for module ' 'name \'%s\', skipping. Add %d to the ' '\'optimization_order\' config option if you ' 'do not want to ignore this optimization ' 'level.', opt_level, f_noext, opt_level ) continue else: # Optimization level not reflected in filename on PY2 opt_index = 0 # make sure it is a suffix we support if ext not in self.suffix_map: continue # Next filename if f_noext in self.disabled: log.trace( 'Skipping %s, it is disabled by configuration', filename ) continue # Next filename fpath = os.path.join(mod_dir, filename) # if its a directory, lets allow us to load that if ext == '': # is there something __init__? subfiles = os.listdir(fpath) for suffix in self.suffix_order: if '' == suffix: continue # Next suffix (__init__ must have a suffix) init_file = '__init__{0}'.format(suffix) if init_file in subfiles: break else: continue # Next filename try: curr_ext = self.file_mapping[f_noext][1] curr_opt_index = self.file_mapping[f_noext][2] except KeyError: pass else: if '' in (curr_ext, ext) and curr_ext != ext: log.error( 'Module/package collision: \'%s\' and \'%s\'', fpath, self.file_mapping[f_noext][0] ) if six.PY3 and ext == '.pyc' and curr_ext == '.pyc': # Check the optimization level if opt_index >= curr_opt_index: # Module name match, but a higher-priority # optimization level was already matched, skipping. continue elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext): # Match found but a higher-priorty match already # exists, so skip this. continue if six.PY3 and not dirname and ext == '.pyc': # On Python 3, we should only load .pyc files from the # __pycache__ subdirectory (i.e. when dirname is not an # empty string). continue # Made it this far - add it self.file_mapping[f_noext] = (fpath, ext, opt_index) except OSError: continue for smod in self.static_modules: f_noext = smod.split('.')[-1] self.file_mapping[f_noext] = (smod, '.o', 0) def clear(self): ''' Clear the dict ''' with self._lock: super(LazyLoader, self).clear() # clear the lazy loader self.loaded_files = set() self.missing_modules = {} self.loaded_modules = {} # if we have been loaded before, lets clear the file mapping since # we obviously want a re-do if hasattr(self, 'opts'): self._refresh_file_mapping() self.initial_load = False def __prep_mod_opts(self, opts): ''' Strip out of the opts any logger instance ''' if '__grains__' not in self.pack: grains = opts.get('grains', {}) if isinstance(grains, ThreadLocalProxy): grains = ThreadLocalProxy.unproxy(grains) self.context_dict['grains'] = grains self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains') if '__pillar__' not in self.pack: pillar = opts.get('pillar', {}) if isinstance(pillar, ThreadLocalProxy): pillar = ThreadLocalProxy.unproxy(pillar) self.context_dict['pillar'] = pillar self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar') mod_opts = {} for key, val in list(opts.items()): if key == 'logger': continue mod_opts[key] = val return mod_opts def _iter_files(self, mod_name): ''' Iterate over all file_mapping files in order of closeness to mod_name ''' # do we have an exact match? if mod_name in self.file_mapping: yield mod_name # do we have a partial match? for k in self.file_mapping: if mod_name in k: yield k # anyone else? Bueller? for k in self.file_mapping: if mod_name not in k: yield k def _reload_submodules(self, mod): submodules = ( getattr(mod, sname) for sname in dir(mod) if isinstance(getattr(mod, sname), mod.__class__) ) # reload only custom "sub"modules for submodule in submodules: # it is a submodule if the name is in a namespace under mod if submodule.__name__.startswith(mod.__name__ + '.'): reload_module(submodule) self._reload_submodules(submodule) def _load_module(self, name): mod = None fpath, suffix = self.file_mapping[name][:2] self.loaded_files.add(name) fpath_dirname = os.path.dirname(fpath) try: sys.path.append(fpath_dirname) if suffix == '.pyx': mod = pyximport.load_module(name, fpath, tempfile.gettempdir()) elif suffix == '.o': top_mod = __import__(fpath, globals(), locals(), []) comps = fpath.split('.') if len(comps) < 2: mod = top_mod else: mod = top_mod for subname in comps[1:]: mod = getattr(mod, subname) elif suffix == '.zip': mod = zipimporter(fpath).load_module(name) else: desc = self.suffix_map[suffix] # if it is a directory, we don't open a file try: mod_namespace = '.'.join(( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name)) except TypeError: mod_namespace = '{0}.{1}.{2}.{3}'.format( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name) if suffix == '': if USE_IMPORTLIB: # pylint: disable=no-member # Package directory, look for __init__ loader_details = [ (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES), (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES), (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), ] file_finder = importlib.machinery.FileFinder( fpath_dirname, *loader_details ) spec = file_finder.find_spec(mod_namespace) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: mod = imp.load_module(mod_namespace, None, fpath, desc) # reload all submodules if necessary if not self.initial_load: self._reload_submodules(mod) else: if USE_IMPORTLIB: # pylint: disable=no-member loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath) spec = importlib.util.spec_from_file_location( mod_namespace, fpath, loader=loader ) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() #mod = importlib.util.module_from_spec(spec) #spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: with salt.utils.files.fopen(fpath, desc[1]) as fn_: mod = imp.load_module(mod_namespace, fn_, fpath, desc) except IOError: raise except ImportError as exc: if 'magic number' in six.text_type(exc): error_msg = 'Failed to import {0} {1}. Bad magic number. If migrating from Python2 to Python3, remove all .pyc files and try again.'.format(self.tag, name) log.warning(error_msg) self.missing_modules[name] = error_msg log.debug( 'Failed to import %s %s:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = exc return False except Exception as error: log.error( 'Failed to import %s %s, this is due most likely to a ' 'syntax error:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False except SystemExit as error: try: fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1] except Exception: pass else: tgt_fn = os.path.join('salt', 'utils', 'process.py') if fn_.endswith(tgt_fn) and '_handle_signals' in caller: # Race conditon, SIGTERM or SIGINT received while loader # was in process of loading a module. Call sys.exit to # ensure that the process is killed. sys.exit(salt.defaults.exitcodes.EX_OK) log.error( 'Failed to import %s %s as the module called exit()\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False finally: sys.path.remove(fpath_dirname) if hasattr(mod, '__opts__'): mod.__opts__.update(self.opts) else: mod.__opts__ = self.opts # pack whatever other globals we were asked to for p_name, p_value in six.iteritems(self.pack): _inject_into_mod(mod, p_name, p_value) module_name = mod.__name__.rsplit('.', 1)[-1] # Call a module's initialization method if it exists module_init = getattr(mod, '__init__', None) if inspect.isfunction(module_init): try: module_init(self.opts) except TypeError as e: log.error(e) except Exception: err_string = '__init__ failed' log.debug( 'Error loading %s.%s: %s', self.tag, module_name, err_string, exc_info=True ) self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False # if virtual modules are enabled, we need to look for the # __virtual__() function inside that module and run it. if self.virtual_enable: virtual_funcs_to_process = ['__virtual__'] + self.virtual_funcs for virtual_func in virtual_funcs_to_process: virtual_ret, module_name, virtual_err, virtual_aliases = \ self._process_virtual(mod, module_name, virtual_func) if virtual_err is not None: log.trace( 'Error loading %s.%s: %s', self.tag, module_name, virtual_err ) # if _process_virtual returned a non-True value then we are # supposed to not process this module if virtual_ret is not True and module_name not in self.missing_modules: # If a module has information about why it could not be loaded, record it self.missing_modules[module_name] = virtual_err self.missing_modules[name] = virtual_err return False else: virtual_aliases = () # If this is a proxy minion then MOST modules cannot work. Therefore, require that # any module that does work with salt-proxy-minion define __proxyenabled__ as a list # containing the names of the proxy types that the module supports. # # Render modules and state modules are OK though if 'proxy' in self.opts: if self.tag in ['grains', 'proxy']: if not hasattr(mod, '__proxyenabled__') or \ (self.opts['proxy']['proxytype'] not in mod.__proxyenabled__ and '*' not in mod.__proxyenabled__): err_string = 'not a proxy_minion enabled module' self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False if getattr(mod, '__load__', False) is not False: log.info( 'The functions from module \'%s\' are being loaded from the ' 'provided __load__ attribute', module_name ) # If we had another module by the same virtual name, we should put any # new functions under the existing dictionary. mod_names = [module_name] + list(virtual_aliases) mod_dict = dict(( (x, self.loaded_modules.get(x, self.mod_dict_class())) for x in mod_names )) for attr in getattr(mod, '__load__', dir(mod)): if attr.startswith('_') and attr != '__call__': # private functions are skipped, # except __call__ which is default entrance # for multi-function batch-like state syntax continue func = getattr(mod, attr) if not inspect.isfunction(func) and not isinstance(func, functools.partial): # Not a function!? Skip it!!! continue # Let's get the function name. # If the module has the __func_alias__ attribute, it must be a # dictionary mapping in the form of(key -> value): # <real-func-name> -> <desired-func-name> # # It default's of course to the found callable attribute name # if no alias is defined. funcname = getattr(mod, '__func_alias__', {}).get(attr, attr) for tgt_mod in mod_names: try: full_funcname = '.'.join((tgt_mod, funcname)) except TypeError: full_funcname = '{0}.{1}'.format(tgt_mod, funcname) # Save many references for lookups # Careful not to overwrite existing (higher priority) functions if full_funcname not in self._dict: self._dict[full_funcname] = func if funcname not in mod_dict[tgt_mod]: setattr(mod_dict[tgt_mod], funcname, func) mod_dict[tgt_mod][funcname] = func self._apply_outputter(func, mod) # enforce depends try: Depends.enforce_dependencies(self._dict, self.tag) except RuntimeError as exc: log.info( 'Depends.enforce_dependencies() failed for the following ' 'reason: %s', exc ) for tgt_mod in mod_names: self.loaded_modules[tgt_mod] = mod_dict[tgt_mod] return True def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise KeyError('The key \'{0}\' should contain a \'.\''.format(key)) mod_name, _ = key.split('.', 1) with self._lock: # It is possible that the key is in the dictionary after # acquiring the lock due to another thread loading it. if mod_name in self.missing_modules or key in self._dict: return True # if the modulename isn't in the whitelist, don't bother if self.whitelist and mod_name not in self.whitelist: log.error( 'Failed to load function %s because its module (%s) is ' 'not in the whitelist: %s', key, mod_name, self.whitelist ) raise KeyError(key) def _inner_load(mod_name): for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and key in self._dict: return True return False # try to load the module ret = None reloaded = False # re-scan up to once, IOErrors or a failed load cause re-scans of the # filesystem while True: try: ret = _inner_load(mod_name) if not reloaded and ret is not True: self._refresh_file_mapping() reloaded = True continue break except IOError: if not reloaded: self._refresh_file_mapping() reloaded = True continue return ret def _load_all(self): ''' Load all of them ''' with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True def reload_modules(self): with self._lock: self.loaded_files = set() self._load_all() def _apply_outputter(self, func, mod): ''' Apply the __outputter__ variable to the functions ''' if hasattr(mod, '__outputter__'): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__] def _process_virtual(self, mod, module_name, virtual_func='__virtual__'): ''' Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1] ''' # The __virtual__ function will return either a True or False value. # If it returns a True value it can also set a module level attribute # named __virtualname__ with the name that the module should be # referred to as. # # This allows us to have things like the pkg module working on all # platforms under the name 'pkg'. It also allows for modules like # augeas_cfg to be referred to as 'augeas', which would otherwise have # namespace collisions. And finally it allows modules to return False # if they are not intended to run on the given platform or are missing # dependencies. virtual_aliases = getattr(mod, '__virtual_aliases__', tuple()) try: error_reason = None if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__): try: start = time.time() virtual = getattr(mod, virtual_func)() if isinstance(virtual, tuple): error_reason = virtual[1] virtual = virtual[0] if self.opts.get('virtual_timer', False): end = time.time() - start msg = 'Virtual function took {0} seconds for {1}'.format( end, module_name) log.warning(msg) except Exception as exc: error_reason = ( 'Exception raised when processing __virtual__ function' ' for {0}. Module will not be loaded: {1}'.format( mod.__name__, exc)) log.error(error_reason, exc_info_on_loglevel=logging.DEBUG) virtual = None # Get the module's virtual name virtualname = getattr(mod, '__virtualname__', virtual) if not virtual: # if __virtual__() evaluates to False then the module # wasn't meant for this platform or it's not supposed to # load for some other reason. # Some modules might accidentally return None and are # improperly loaded if virtual is None: log.warning( '%s.__virtual__() is wrongly returning `None`. ' 'It should either return `True`, `False` or a new ' 'name. If you\'re the developer of the module ' '\'%s\', please fix this.', mod.__name__, module_name ) return (False, module_name, error_reason, virtual_aliases) # At this point, __virtual__ did not return a # boolean value, let's check for deprecated usage # or module renames if virtual is not True and module_name != virtual: # The module is renaming itself. Updating the module name # with the new name log.trace('Loaded %s as virtual %s', module_name, virtual) if virtualname != virtual: # The __virtualname__ attribute does not match what's # being returned by the __virtual__() function. This # should be considered an error. log.error( 'The module \'%s\' is showing some bad usage. Its ' '__virtualname__ attribute is set to \'%s\' yet the ' '__virtual__() function is returning \'%s\'. These ' 'values should match!', mod.__name__, virtualname, virtual ) module_name = virtualname # If the __virtual__ function returns True and __virtualname__ # is set then use it elif virtual is True and virtualname != module_name: if virtualname is not True: module_name = virtualname except KeyError: # Key errors come out of the virtual function when passing # in incomplete grains sets, these can be safely ignored # and logged to debug, still, it includes the traceback to # help debugging. log.debug('KeyError when loading %s', module_name, exc_info=True) except Exception: # If the module throws an exception during __virtual__() # then log the information and continue to the next. log.error( 'Failed to read the virtual function for %s: %s', self.tag, module_name, exc_info=True ) return (False, module_name, error_reason, virtual_aliases) return (True, module_name, None, virtual_aliases) def global_injector_decorator(inject_globals): ''' Decorator used by the LazyLoader to inject globals into a function at execute time. globals Dictionary with global variables to inject ''' def inner_decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): with salt.utils.context.func_globals_inject(f, **inject_globals): return f(*args, **kwargs) return wrapper return inner_decorator
saltstack/salt
salt/loader.py
pillars
python
def pillars(opts, functions, context=None): ''' Returns the pillars modules ''' ret = LazyLoader(_module_dirs(opts, 'pillar'), opts, tag='pillar', pack={'__salt__': functions, '__context__': context, '__utils__': utils(opts)}) ret.pack['__ext_pillar__'] = ret return FilterDictWrapper(ret, '.ext_pillar')
Returns the pillars modules
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L399-L410
null
# -*- coding: utf-8 -*- ''' The Salt loader is the core to Salt's plugin system, the loader scans directories for python loadable code and organizes the code into the plugin interfaces used by Salt. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import sys import time import logging import inspect import tempfile import threading import functools import threading import traceback import types from zipimport import zipimporter # Import salt libs import salt.config import salt.defaults.events import salt.defaults.exitcodes import salt.syspaths import salt.utils.args import salt.utils.context import salt.utils.data import salt.utils.dictupdate import salt.utils.event import salt.utils.files import salt.utils.lazy import salt.utils.odict import salt.utils.platform import salt.utils.versions import salt.utils.stringutils from salt.exceptions import LoaderError from salt.template import check_render_pipe_str from salt.utils.decorators import Depends from salt.utils.thread_local_proxy import ThreadLocalProxy # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import reload_module if sys.version_info[:2] >= (3, 5): import importlib.machinery # pylint: disable=no-name-in-module,import-error import importlib.util # pylint: disable=no-name-in-module,import-error USE_IMPORTLIB = True else: import imp USE_IMPORTLIB = False try: from collections.abc import MutableMapping except ImportError: from collections import MutableMapping try: import pkg_resources HAS_PKG_RESOURCES = True except ImportError: HAS_PKG_RESOURCES = False log = logging.getLogger(__name__) SALT_BASE_PATH = os.path.abspath(salt.syspaths.INSTALL_DIR) LOADED_BASE_NAME = 'salt.loaded' if USE_IMPORTLIB: # pylint: disable=no-member MODULE_KIND_SOURCE = 1 MODULE_KIND_COMPILED = 2 MODULE_KIND_EXTENSION = 3 MODULE_KIND_PKG_DIRECTORY = 5 SUFFIXES = [] for suffix in importlib.machinery.EXTENSION_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_EXTENSION)) for suffix in importlib.machinery.SOURCE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_SOURCE)) for suffix in importlib.machinery.BYTECODE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_COMPILED)) MODULE_KIND_MAP = { MODULE_KIND_SOURCE: importlib.machinery.SourceFileLoader, MODULE_KIND_COMPILED: importlib.machinery.SourcelessFileLoader, MODULE_KIND_EXTENSION: importlib.machinery.ExtensionFileLoader } # pylint: enable=no-member else: SUFFIXES = imp.get_suffixes() PY3_PRE_EXT = \ re.compile(r'\.cpython-{0}{1}(\.opt-[1-9])?'.format(*sys.version_info[:2])) # Because on the cloud drivers we do `from salt.cloud.libcloudfuncs import *` # which simplifies code readability, it adds some unsupported functions into # the driver's module scope. # We list un-supported functions here. These will be removed from the loaded. # TODO: remove the need for this cross-module code. Maybe use NotImplemented LIBCLOUD_FUNCS_NOT_SUPPORTED = ( 'parallels.avail_sizes', 'parallels.avail_locations', 'proxmox.avail_sizes', ) # Will be set to pyximport module at runtime if cython is enabled in config. pyximport = None def static_loader( opts, ext_type, tag, pack=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, filter_name=None, ): funcs = LazyLoader( _module_dirs( opts, ext_type, tag, int_type, ext_dirs, ext_type_dirs, base_path, ), opts, tag=tag, pack=pack, ) ret = {} funcs._load_all() if filter_name: funcs = FilterDictWrapper(funcs, filter_name) for key in funcs: ret[key] = funcs[key] return ret def _format_entrypoint_target(ep): ''' Makes a string describing the target of an EntryPoint object. Base strongly on EntryPoint.__str__(). ''' s = ep.module_name if ep.attrs: s += ':' + '.'.join(ep.attrs) return s def _module_dirs( opts, ext_type, tag=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, ): if tag is None: tag = ext_type sys_types = os.path.join(base_path or SALT_BASE_PATH, int_type or ext_type) ext_types = os.path.join(opts['extension_modules'], ext_type) ext_type_types = [] if ext_dirs: if ext_type_dirs is None: ext_type_dirs = '{0}_dirs'.format(tag) if ext_type_dirs in opts: ext_type_types.extend(opts[ext_type_dirs]) if HAS_PKG_RESOURCES and ext_type_dirs: for entry_point in pkg_resources.iter_entry_points('salt.loader', ext_type_dirs): try: loaded_entry_point = entry_point.load() for path in loaded_entry_point(): ext_type_types.append(path) except Exception as exc: log.error("Error getting module directories from %s: %s", _format_entrypoint_target(entry_point), exc) log.debug("Full backtrace for module directories error", exc_info=True) cli_module_dirs = [] # The dirs can be any module dir, or a in-tree _{ext_type} dir for _dir in opts.get('module_dirs', []): # Prepend to the list to match cli argument ordering maybe_dir = os.path.join(_dir, ext_type) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) continue maybe_dir = os.path.join(_dir, '_{0}'.format(ext_type)) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) return cli_module_dirs + ext_type_types + [ext_types, sys_types] def minion_mods( opts, context=None, utils=None, whitelist=None, initial_load=False, loaded_base_name=None, notify=False, static_modules=None, proxy=None): ''' Load execution modules Returns a dictionary of execution modules appropriate for the current system by evaluating the __virtual__() function in each module. :param dict opts: The Salt options dictionary :param dict context: A Salt context that should be made present inside generated modules in __context__ :param dict utils: Utility functions which should be made available to Salt modules in __utils__. See `utils_dirs` in salt.config for additional information about configuration. :param list whitelist: A list of modules which should be whitelisted. :param bool initial_load: Deprecated flag! Unused. :param str loaded_base_name: A string marker for the loaded base name. :param bool notify: Flag indicating that an event should be fired upon completion of module loading. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) __opts__['grains'] = __grains__ __utils__ = salt.loader.utils(__opts__) __salt__ = salt.loader.minion_mods(__opts__, utils=__utils__) __salt__['test.ping']() ''' # TODO Publish documentation for module whitelisting if not whitelist: whitelist = opts.get('whitelist_modules', None) ret = LazyLoader( _module_dirs(opts, 'modules', 'module'), opts, tag='module', pack={'__context__': context, '__utils__': utils, '__proxy__': proxy}, whitelist=whitelist, loaded_base_name=loaded_base_name, static_modules=static_modules, ) ret.pack['__salt__'] = ret # Load any provider overrides from the configuration file providers option # Note: Providers can be pkg, service, user or group - not to be confused # with cloud providers. providers = opts.get('providers', False) if providers and isinstance(providers, dict): for mod in providers: # sometimes providers opts is not to diverge modules but # for other configuration try: funcs = raw_mod(opts, providers[mod], ret) except TypeError: break else: if funcs: for func in funcs: f_key = '{0}{1}'.format(mod, func[func.rindex('.'):]) ret[f_key] = funcs[func] if notify: evt = salt.utils.event.get_event('minion', opts=opts, listen=False) evt.fire_event({'complete': True}, tag=salt.defaults.events.MINION_MOD_COMPLETE) return ret def raw_mod(opts, name, functions, mod='modules'): ''' Returns a single module loaded raw and bypassing the __virtual__ function .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') testmod = salt.loader.raw_mod(__opts__, 'test', None) testmod['test.ping']() ''' loader = LazyLoader( _module_dirs(opts, mod, 'module'), opts, tag='rawmodule', virtual_enable=False, pack={'__salt__': functions}, ) # if we don't have the module, return an empty dict if name not in loader.file_mapping: return {} loader._load_module(name) # load a single module (the one passed in) return dict(loader._dict) # return a copy of *just* the funcs for `name` def metaproxy(opts): ''' Return functions used in the meta proxy ''' return LazyLoader( _module_dirs(opts, 'metaproxy'), opts, tag='metaproxy' ) def matchers(opts): ''' Return the matcher services plugins ''' return LazyLoader( _module_dirs(opts, 'matchers'), opts, tag='matchers' ) def engines(opts, functions, runners, utils, proxy=None): ''' Return the master services plugins ''' pack = {'__salt__': functions, '__runners__': runners, '__proxy__': proxy, '__utils__': utils} return LazyLoader( _module_dirs(opts, 'engines'), opts, tag='engines', pack=pack, ) def proxy(opts, functions=None, returners=None, whitelist=None, utils=None): ''' Returns the proxy module for this salt-proxy-minion ''' ret = LazyLoader( _module_dirs(opts, 'proxy'), opts, tag='proxy', pack={'__salt__': functions, '__ret__': returners, '__utils__': utils}, ) ret.pack['__proxy__'] = ret return ret def returners(opts, functions, whitelist=None, context=None, proxy=None): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'returners', 'returner'), opts, tag='returner', whitelist=whitelist, pack={'__salt__': functions, '__context__': context, '__proxy__': proxy or {}}, ) def utils(opts, whitelist=None, context=None, proxy=proxy): ''' Returns the utility modules ''' return LazyLoader( _module_dirs(opts, 'utils', ext_type_dirs='utils_dirs'), opts, tag='utils', whitelist=whitelist, pack={'__context__': context, '__proxy__': proxy or {}}, ) def tops(opts): ''' Returns the tops modules ''' if 'master_tops' not in opts: return {} whitelist = list(opts['master_tops'].keys()) ret = LazyLoader( _module_dirs(opts, 'tops', 'top'), opts, tag='top', whitelist=whitelist, ) return FilterDictWrapper(ret, '.top') def wheels(opts, whitelist=None, context=None): ''' Returns the wheels modules ''' if context is None: context = {} return LazyLoader( _module_dirs(opts, 'wheel'), opts, tag='wheel', whitelist=whitelist, pack={'__context__': context}, ) def outputters(opts): ''' Returns the outputters modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only outputters present in the keyspace ''' ret = LazyLoader( _module_dirs(opts, 'output', ext_type_dirs='outputter_dirs'), opts, tag='output', ) wrapped_ret = FilterDictWrapper(ret, '.output') # TODO: this name seems terrible... __salt__ should always be execution mods ret.pack['__salt__'] = wrapped_ret return wrapped_ret def serializers(opts): ''' Returns the serializers modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only serializers present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'serializers'), opts, tag='serializers', ) def eauth_tokens(opts): ''' Returns the tokens modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only token backends present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'tokens'), opts, tag='tokens', ) def auth(opts, whitelist=None): ''' Returns the auth modules :param dict opts: The Salt options dictionary :returns: LazyLoader ''' return LazyLoader( _module_dirs(opts, 'auth'), opts, tag='auth', whitelist=whitelist, pack={'__salt__': minion_mods(opts)}, ) def fileserver(opts, backends): ''' Returns the file server modules ''' return LazyLoader(_module_dirs(opts, 'fileserver'), opts, tag='fileserver', whitelist=backends, pack={'__utils__': utils(opts)}) def roster(opts, runner=None, utils=None, whitelist=None): ''' Returns the roster modules ''' return LazyLoader( _module_dirs(opts, 'roster'), opts, tag='roster', whitelist=whitelist, pack={ '__runner__': runner, '__utils__': utils, }, ) def thorium(opts, functions, runners): ''' Load the thorium runtime modules ''' pack = {'__salt__': functions, '__runner__': runners, '__context__': {}} ret = LazyLoader(_module_dirs(opts, 'thorium'), opts, tag='thorium', pack=pack) ret.pack['__thorium__'] = ret return ret def states(opts, functions, utils, serializers, whitelist=None, proxy=None, context=None): ''' Returns the state modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') statemods = salt.loader.states(__opts__, None, None) ''' if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'states'), opts, tag='states', pack={'__salt__': functions, '__proxy__': proxy or {}}, whitelist=whitelist, ) ret.pack['__states__'] = ret ret.pack['__utils__'] = utils ret.pack['__serializers__'] = serializers ret.pack['__context__'] = context return ret def beacons(opts, functions, context=None, proxy=None): ''' Load the beacon modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. ''' return LazyLoader( _module_dirs(opts, 'beacons'), opts, tag='beacons', pack={'__context__': context, '__salt__': functions, '__proxy__': proxy or {}}, virtual_funcs=[], ) def log_handlers(opts): ''' Returns the custom logging handler modules :param dict opts: The Salt options dictionary ''' ret = LazyLoader( _module_dirs( opts, 'log_handlers', int_type='handlers', base_path=os.path.join(SALT_BASE_PATH, 'log'), ), opts, tag='log_handlers', ) return FilterDictWrapper(ret, '.setup_handlers') def ssh_wrapper(opts, functions=None, context=None): ''' Returns the custom logging handler modules ''' return LazyLoader( _module_dirs( opts, 'wrapper', base_path=os.path.join(SALT_BASE_PATH, os.path.join('client', 'ssh')), ), opts, tag='wrapper', pack={ '__salt__': functions, '__grains__': opts.get('grains', {}), '__pillar__': opts.get('pillar', {}), '__context__': context, }, ) def render(opts, functions, states=None, proxy=None, context=None): ''' Returns the render modules ''' if context is None: context = {} pack = {'__salt__': functions, '__grains__': opts.get('grains', {}), '__context__': context} if states: pack['__states__'] = states pack['__proxy__'] = proxy or {} ret = LazyLoader( _module_dirs( opts, 'renderers', 'render', ext_type_dirs='render_dirs', ), opts, tag='render', pack=pack, ) rend = FilterDictWrapper(ret, '.render') if not check_render_pipe_str(opts['renderer'], rend, opts['renderer_blacklist'], opts['renderer_whitelist']): err = ('The renderer {0} is unavailable, this error is often because ' 'the needed software is unavailable'.format(opts['renderer'])) log.critical(err) raise LoaderError(err) return rend def grain_funcs(opts, proxy=None): ''' Returns the grain functions .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') grainfuncs = salt.loader.grain_funcs(__opts__) ''' ret = LazyLoader( _module_dirs( opts, 'grains', 'grain', ext_type_dirs='grains_dirs', ), opts, tag='grains', ) ret.pack['__utils__'] = utils(opts, proxy=proxy) return ret def _load_cached_grains(opts, cfn): ''' Returns the grains cached in cfn, or None if the cache is too old or is corrupted. ''' if not os.path.isfile(cfn): log.debug('Grains cache file does not exist.') return None grains_cache_age = int(time.time() - os.path.getmtime(cfn)) if grains_cache_age > opts.get('grains_cache_expiration', 300): log.debug( 'Grains cache last modified %s seconds ago and cache ' 'expiration is set to %s. Grains cache expired. ' 'Refreshing.', grains_cache_age, opts.get('grains_cache_expiration', 300) ) return None if opts.get('refresh_grains_cache', False): log.debug('refresh_grains_cache requested, Refreshing.') return None log.debug('Retrieving grains from cache') try: serial = salt.payload.Serial(opts) with salt.utils.files.fopen(cfn, 'rb') as fp_: cached_grains = salt.utils.data.decode(serial.load(fp_), preserve_tuples=True) if not cached_grains: log.debug('Cached grains are empty, cache might be corrupted. Refreshing.') return None return cached_grains except (IOError, OSError): return None def grains(opts, force_refresh=False, proxy=None): ''' Return the functions for the dynamic grains and the values for the static grains. Since grains are computed early in the startup process, grains functions do not have __salt__ or __proxy__ available. At proxy-minion startup, this function is called with the proxymodule LazyLoader object so grains functions can communicate with their controlled device. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) print __grains__['id'] ''' # Need to re-import salt.config, somehow it got lost when a minion is starting import salt.config # if we have no grains, lets try loading from disk (TODO: move to decorator?) cfn = os.path.join( opts['cachedir'], 'grains.cache.p' ) if not force_refresh and opts.get('grains_cache', False): cached_grains = _load_cached_grains(opts, cfn) if cached_grains: return cached_grains else: log.debug('Grains refresh requested. Refreshing grains.') if opts.get('skip_grains', False): return {} grains_deep_merge = opts.get('grains_deep_merge', False) is True if 'conf_file' in opts: pre_opts = {} pre_opts.update(salt.config.load_config( opts['conf_file'], 'SALT_MINION_CONFIG', salt.config.DEFAULT_MINION_OPTS['conf_file'] )) default_include = pre_opts.get( 'default_include', opts['default_include'] ) include = pre_opts.get('include', []) pre_opts.update(salt.config.include_config( default_include, opts['conf_file'], verbose=False )) pre_opts.update(salt.config.include_config( include, opts['conf_file'], verbose=True )) if 'grains' in pre_opts: opts['grains'] = pre_opts['grains'] else: opts['grains'] = {} else: opts['grains'] = {} grains_data = {} blist = opts.get('grains_blacklist', []) funcs = grain_funcs(opts, proxy=proxy) if force_refresh: # if we refresh, lets reload grain modules funcs.clear() # Run core grains for key in funcs: if not key.startswith('core.'): continue log.trace('Loading %s grain', key) ret = funcs[key]() if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) # Run the rest of the grains for key in funcs: if key.startswith('core.') or key == '_errors': continue try: # Grains are loaded too early to take advantage of the injected # __proxy__ variable. Pass an instance of that LazyLoader # here instead to grains functions if the grains functions take # one parameter. Then the grains can have access to the # proxymodule for retrieving information from the connected # device. log.trace('Loading %s grain', key) parameters = salt.utils.args.get_function_argspec(funcs[key]).args kwargs = {} if 'proxy' in parameters: kwargs['proxy'] = proxy if 'grains' in parameters: kwargs['grains'] = grains_data ret = funcs[key](**kwargs) except Exception: if salt.utils.platform.is_proxy(): log.info('The following CRITICAL message may not be an error; the proxy may not be completely established yet.') log.critical( 'Failed to load grains defined in grain file %s in ' 'function %s, error:\n', key, funcs[key], exc_info=True ) continue if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) if opts.get('proxy_merge_grains_in_module', True) and proxy: try: proxytype = proxy.opts['proxy']['proxytype'] if proxytype + '.grains' in proxy: if proxytype + '.initialized' in proxy and proxy[proxytype + '.initialized'](): try: proxytype = proxy.opts['proxy']['proxytype'] ret = proxy[proxytype + '.grains']() if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) except Exception: log.critical('Failed to run proxy\'s grains function!', exc_info=True ) except KeyError: pass grains_data.update(opts['grains']) # Write cache if enabled if opts.get('grains_cache', False): with salt.utils.files.set_umask(0o077): try: if salt.utils.platform.is_windows(): # Late import import salt.modules.cmdmod # Make sure cache file isn't read-only salt.modules.cmdmod._run_quiet('attrib -R "{0}"'.format(cfn)) with salt.utils.files.fopen(cfn, 'w+b') as fp_: try: serial = salt.payload.Serial(opts) serial.dump(grains_data, fp_) except TypeError as e: log.error('Failed to serialize grains cache: %s', e) raise # re-throw for cleanup except Exception as e: log.error('Unable to write to grains cache file %s: %s', cfn, e) # Based on the original exception, the file may or may not have been # created. If it was, we will remove it now, as the exception means # the serialized data is not to be trusted, no matter what the # exception is. if os.path.isfile(cfn): os.unlink(cfn) if grains_deep_merge: salt.utils.dictupdate.update(grains_data, opts['grains']) else: grains_data.update(opts['grains']) return salt.utils.data.decode(grains_data, preserve_tuples=True) # TODO: get rid of? Does anyone use this? You should use raw() instead def call(fun, **kwargs): ''' Directly call a function inside a loader directory ''' args = kwargs.get('args', []) dirs = kwargs.get('dirs', []) funcs = LazyLoader( [os.path.join(SALT_BASE_PATH, 'modules')] + dirs, None, tag='modules', virtual_enable=False, ) return funcs[fun](*args) def runner(opts, utils=None, context=None, whitelist=None): ''' Directly call a function inside a loader directory ''' if utils is None: utils = {} if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'runners', 'runner', ext_type_dirs='runner_dirs'), opts, tag='runners', pack={'__utils__': utils, '__context__': context}, whitelist=whitelist, ) # TODO: change from __salt__ to something else, we overload __salt__ too much ret.pack['__salt__'] = ret return ret def queues(opts): ''' Directly call a function inside a loader directory ''' return LazyLoader( _module_dirs(opts, 'queues', 'queue', ext_type_dirs='queue_dirs'), opts, tag='queues', ) def sdb(opts, functions=None, whitelist=None, utils=None): ''' Make a very small database call ''' if utils is None: utils = {} return LazyLoader( _module_dirs(opts, 'sdb'), opts, tag='sdb', pack={ '__sdb__': functions, '__opts__': opts, '__utils__': utils, '__salt__': minion_mods(opts, utils), }, whitelist=whitelist, ) def pkgdb(opts): ''' Return modules for SPM's package database .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgdb', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgdb' ) def pkgfiles(opts): ''' Return modules for SPM's file handling .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgfiles', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgfiles' ) def clouds(opts): ''' Return the cloud functions ''' # Let's bring __active_provider_name__, defaulting to None, to all cloud # drivers. This will get temporarily updated/overridden with a context # manager when needed. functions = LazyLoader( _module_dirs(opts, 'clouds', 'cloud', base_path=os.path.join(SALT_BASE_PATH, 'cloud'), int_type='clouds'), opts, tag='clouds', pack={'__utils__': salt.loader.utils(opts), '__active_provider_name__': None}, ) for funcname in LIBCLOUD_FUNCS_NOT_SUPPORTED: log.trace( '\'%s\' has been marked as not supported. Removing from the ' 'list of supported cloud functions', funcname ) functions.pop(funcname, None) return functions def netapi(opts): ''' Return the network api functions ''' return LazyLoader( _module_dirs(opts, 'netapi'), opts, tag='netapi', ) def executors(opts, functions=None, context=None, proxy=None): ''' Returns the executor modules ''' executors = LazyLoader( _module_dirs(opts, 'executors', 'executor'), opts, tag='executor', pack={'__salt__': functions, '__context__': context or {}, '__proxy__': proxy or {}}, ) executors.pack['__executors__'] = executors return executors def cache(opts, serial): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'cache', 'cache'), opts, tag='cache', pack={'__opts__': opts, '__context__': {'serial': serial}}, ) def _generate_module(name): if name in sys.modules: return code = "'''Salt loaded {0} parent module'''".format(name.split('.')[-1]) # ModuleType can't accept a unicode type on PY2 module = types.ModuleType(str(name)) # future lint: disable=blacklisted-function exec(code, module.__dict__) sys.modules[name] = module def _mod_type(module_path): if module_path.startswith(SALT_BASE_PATH): return 'int' return 'ext' def _inject_into_mod(mod, name, value, force_lock=False): ''' Inject a variable into a module. This is used to inject "globals" like ``__salt__``, ``__pillar``, or ``grains``. Instead of injecting the value directly, a ``ThreadLocalProxy`` is created. If such a proxy is already present under the specified name, it is updated with the new value. This update only affects the current thread, so that the same name can refer to different values depending on the thread of execution. This is important for data that is not truly global. For example, pillar data might be dynamically overriden through function parameters and thus the actual values available in pillar might depend on the thread that is calling a module. mod: module object into which the value is going to be injected. name: name of the variable that is injected into the module. value: value that is injected into the variable. The value is not injected directly, but instead set as the new reference of the proxy that has been created for the variable. force_lock: whether the lock should be acquired before checking whether a proxy object for the specified name has already been injected into the module. If ``False`` (the default), this function checks for the module's variable without acquiring the lock and only acquires the lock if a new proxy has to be created and injected. ''' old_value = getattr(mod, name, None) # We use a double-checked locking scheme in order to avoid taking the lock # when a proxy object has already been injected. # In most programming languages, double-checked locking is considered # unsafe when used without explicit memory barriers because one might read # an uninitialized value. In CPython it is safe due to the global # interpreter lock (GIL). In Python implementations that do not have the # GIL, it could be unsafe, but at least Jython also guarantees that (for # Python objects) memory is not corrupted when writing and reading without # explicit synchronization # (http://www.jython.org/jythonbook/en/1.0/Concurrency.html). # Please note that in order to make this code safe in a runtime environment # that does not make this guarantees, it is not sufficient. The # ThreadLocalProxy must also be created with fallback_to_shared set to # False or a lock must be added to the ThreadLocalProxy. if force_lock: with _inject_into_mod.lock: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: setattr(mod, name, ThreadLocalProxy(value, True)) else: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: _inject_into_mod(mod, name, value, True) # Lock used when injecting globals. This is needed to avoid a race condition # when two threads try to load the same module concurrently. This must be # outside the loader because there might be more than one loader for the same # namespace. _inject_into_mod.lock = threading.RLock() # TODO: move somewhere else? class FilterDictWrapper(MutableMapping): ''' Create a dict which wraps another dict with a specific key suffix on get This is to replace "filter_load" ''' def __init__(self, d, suffix): self._dict = d self.suffix = suffix def __setitem__(self, key, val): self._dict[key] = val def __delitem__(self, key): del self._dict[key] def __getitem__(self, key): return self._dict[key + self.suffix] def __len__(self): return len(self._dict) def __iter__(self): for key in self._dict: if key.endswith(self.suffix): yield key.replace(self.suffix, '') class LazyLoader(salt.utils.lazy.LazyDict): ''' A pseduo-dictionary which has a set of keys which are the name of the module and function, delimited by a dot. When the value of the key is accessed, the function is then loaded from disk and into memory. .. note:: Iterating over keys will cause all modules to be loaded. :param list module_dirs: A list of directories on disk to search for modules :param dict opts: The salt options dictionary. :param str tag: The tag for the type of module to load :param func mod_type_check: A function which can be used to verify files :param dict pack: A dictionary of function to be packed into modules as they are loaded :param list whitelist: A list of modules to whitelist :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules. :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality. If not true, the module will not load. :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values are function references themselves which are loaded on-demand. # TODO: - move modules_max_memory into here - singletons (per tag) ''' mod_dict_class = salt.utils.odict.OrderedDict def __init__(self, module_dirs, opts=None, tag='module', loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, proxy=None, virtual_funcs=None, ): # pylint: disable=W0231 ''' In pack, if any of the values are None they will be replaced with an empty context-specific dict ''' self.inject_globals = {} self.pack = {} if pack is None else pack if opts is None: opts = {} threadsafety = not opts.get('multiprocessing') self.context_dict = salt.utils.context.ContextDict(threadsafe=threadsafety) self.opts = self.__prep_mod_opts(opts) self.module_dirs = module_dirs self.tag = tag self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME self.mod_type_check = mod_type_check or _mod_type if '__context__' not in self.pack: self.pack['__context__'] = None for k, v in six.iteritems(self.pack): if v is None: # if the value of a pack is None, lets make an empty dict value = self.context_dict.get(k, {}) if isinstance(value, ThreadLocalProxy): value = ThreadLocalProxy.unproxy(value) self.context_dict[k] = value self.pack[k] = salt.utils.context.NamespacedDictWrapper(self.context_dict, k) self.whitelist = whitelist self.virtual_enable = virtual_enable self.initial_load = True # names of modules that we don't have (errors, __virtual__, etc.) self.missing_modules = {} # mapping of name -> error self.loaded_modules = {} # mapping of module_name -> dict_of_functions self.loaded_files = set() # TODO: just remove them from file_mapping? self.static_modules = static_modules if static_modules else [] if virtual_funcs is None: virtual_funcs = [] self.virtual_funcs = virtual_funcs self.disabled = set( self.opts.get( 'disable_{0}{1}'.format( self.tag, '' if self.tag[-1] == 's' else 's' ), [] ) ) # A map of suffix to description for imp self.suffix_map = {} # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [''] for (suffix, mode, kind) in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) self._lock = threading.RLock() self._refresh_file_mapping() super(LazyLoader, self).__init__() # late init the lazy loader # create all of the import namespaces _generate_module('{0}.int'.format(self.loaded_base_name)) _generate_module('{0}.int.{1}'.format(self.loaded_base_name, tag)) _generate_module('{0}.ext'.format(self.loaded_base_name)) _generate_module('{0}.ext.{1}'.format(self.loaded_base_name, tag)) def __getitem__(self, item): ''' Override the __getitem__ in order to decorate the returned function if we need to last-minute inject globals ''' func = super(LazyLoader, self).__getitem__(item) if self.inject_globals: return global_injector_decorator(self.inject_globals)(func) else: return func def __getattr__(self, mod_name): ''' Allow for "direct" attribute access-- this allows jinja templates to access things like `salt.test.ping()` ''' if mod_name in ('__getstate__', '__setstate__'): return object.__getattribute__(self, mod_name) # if we have an attribute named that, lets return it. try: return object.__getattr__(self, mod_name) # pylint: disable=no-member except AttributeError: pass # otherwise we assume its jinja template access if mod_name not in self.loaded_modules and not self.loaded: for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and mod_name in self.loaded_modules: break if mod_name in self.loaded_modules: return self.loaded_modules[mod_name] else: raise AttributeError(mod_name) def missing_fun_string(self, function_name): ''' Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ''' mod_name = function_name.split('.')[0] if mod_name in self.loaded_modules: return '\'{0}\' is not available.'.format(function_name) else: try: reason = self.missing_modules[mod_name] except KeyError: return '\'{0}\' is not available.'.format(function_name) else: if reason is not None: return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason) else: return '\'{0}\' __virtual__ returned False'.format(mod_name) def _refresh_file_mapping(self): ''' refresh the mapping of the FS on disk ''' # map of suffix to description for imp if self.opts.get('cython_enable', True) is True: try: global pyximport pyximport = __import__('pyximport') # pylint: disable=import-error pyximport.install() # add to suffix_map so file_mapping will pick it up self.suffix_map['.pyx'] = tuple() except ImportError: log.info('Cython is enabled in the options but not present ' 'in the system path. Skipping Cython modules.') # Allow for zipimport of modules if self.opts.get('enable_zip_modules', True) is True: self.suffix_map['.zip'] = tuple() # allow for module dirs if USE_IMPORTLIB: self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY) else: self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY) # create mapping of filename (without suffix) to (path, suffix) # The files are added in order of priority, so order *must* be retained. self.file_mapping = salt.utils.odict.OrderedDict() opt_match = [] def _replace_pre_ext(obj): ''' Hack so we can get the optimization level that we replaced (if any) out of the re.sub call below. We use a list here because it is a persistent data structure that we will be able to access after re.sub is called. ''' opt_match.append(obj) return '' for mod_dir in self.module_dirs: try: # Make sure we have a sorted listdir in order to have # expectable override results files = sorted( x for x in os.listdir(mod_dir) if x != '__pycache__' ) except OSError: continue # Next mod_dir if six.PY3: try: pycache_files = [ os.path.join('__pycache__', x) for x in sorted(os.listdir(os.path.join(mod_dir, '__pycache__'))) ] except OSError: pass else: files.extend(pycache_files) for filename in files: try: dirname, basename = os.path.split(filename) if basename.startswith('_'): # skip private modules # log messages omitted for obviousness continue # Next filename f_noext, ext = os.path.splitext(basename) if six.PY3: f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext) try: opt_level = int( opt_match.pop().group(1).rsplit('-', 1)[-1] ) except (AttributeError, IndexError, ValueError): # No regex match or no optimization level matched opt_level = 0 try: opt_index = self.opts['optimization_order'].index(opt_level) except KeyError: log.trace( 'Disallowed optimization level %d for module ' 'name \'%s\', skipping. Add %d to the ' '\'optimization_order\' config option if you ' 'do not want to ignore this optimization ' 'level.', opt_level, f_noext, opt_level ) continue else: # Optimization level not reflected in filename on PY2 opt_index = 0 # make sure it is a suffix we support if ext not in self.suffix_map: continue # Next filename if f_noext in self.disabled: log.trace( 'Skipping %s, it is disabled by configuration', filename ) continue # Next filename fpath = os.path.join(mod_dir, filename) # if its a directory, lets allow us to load that if ext == '': # is there something __init__? subfiles = os.listdir(fpath) for suffix in self.suffix_order: if '' == suffix: continue # Next suffix (__init__ must have a suffix) init_file = '__init__{0}'.format(suffix) if init_file in subfiles: break else: continue # Next filename try: curr_ext = self.file_mapping[f_noext][1] curr_opt_index = self.file_mapping[f_noext][2] except KeyError: pass else: if '' in (curr_ext, ext) and curr_ext != ext: log.error( 'Module/package collision: \'%s\' and \'%s\'', fpath, self.file_mapping[f_noext][0] ) if six.PY3 and ext == '.pyc' and curr_ext == '.pyc': # Check the optimization level if opt_index >= curr_opt_index: # Module name match, but a higher-priority # optimization level was already matched, skipping. continue elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext): # Match found but a higher-priorty match already # exists, so skip this. continue if six.PY3 and not dirname and ext == '.pyc': # On Python 3, we should only load .pyc files from the # __pycache__ subdirectory (i.e. when dirname is not an # empty string). continue # Made it this far - add it self.file_mapping[f_noext] = (fpath, ext, opt_index) except OSError: continue for smod in self.static_modules: f_noext = smod.split('.')[-1] self.file_mapping[f_noext] = (smod, '.o', 0) def clear(self): ''' Clear the dict ''' with self._lock: super(LazyLoader, self).clear() # clear the lazy loader self.loaded_files = set() self.missing_modules = {} self.loaded_modules = {} # if we have been loaded before, lets clear the file mapping since # we obviously want a re-do if hasattr(self, 'opts'): self._refresh_file_mapping() self.initial_load = False def __prep_mod_opts(self, opts): ''' Strip out of the opts any logger instance ''' if '__grains__' not in self.pack: grains = opts.get('grains', {}) if isinstance(grains, ThreadLocalProxy): grains = ThreadLocalProxy.unproxy(grains) self.context_dict['grains'] = grains self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains') if '__pillar__' not in self.pack: pillar = opts.get('pillar', {}) if isinstance(pillar, ThreadLocalProxy): pillar = ThreadLocalProxy.unproxy(pillar) self.context_dict['pillar'] = pillar self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar') mod_opts = {} for key, val in list(opts.items()): if key == 'logger': continue mod_opts[key] = val return mod_opts def _iter_files(self, mod_name): ''' Iterate over all file_mapping files in order of closeness to mod_name ''' # do we have an exact match? if mod_name in self.file_mapping: yield mod_name # do we have a partial match? for k in self.file_mapping: if mod_name in k: yield k # anyone else? Bueller? for k in self.file_mapping: if mod_name not in k: yield k def _reload_submodules(self, mod): submodules = ( getattr(mod, sname) for sname in dir(mod) if isinstance(getattr(mod, sname), mod.__class__) ) # reload only custom "sub"modules for submodule in submodules: # it is a submodule if the name is in a namespace under mod if submodule.__name__.startswith(mod.__name__ + '.'): reload_module(submodule) self._reload_submodules(submodule) def _load_module(self, name): mod = None fpath, suffix = self.file_mapping[name][:2] self.loaded_files.add(name) fpath_dirname = os.path.dirname(fpath) try: sys.path.append(fpath_dirname) if suffix == '.pyx': mod = pyximport.load_module(name, fpath, tempfile.gettempdir()) elif suffix == '.o': top_mod = __import__(fpath, globals(), locals(), []) comps = fpath.split('.') if len(comps) < 2: mod = top_mod else: mod = top_mod for subname in comps[1:]: mod = getattr(mod, subname) elif suffix == '.zip': mod = zipimporter(fpath).load_module(name) else: desc = self.suffix_map[suffix] # if it is a directory, we don't open a file try: mod_namespace = '.'.join(( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name)) except TypeError: mod_namespace = '{0}.{1}.{2}.{3}'.format( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name) if suffix == '': if USE_IMPORTLIB: # pylint: disable=no-member # Package directory, look for __init__ loader_details = [ (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES), (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES), (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), ] file_finder = importlib.machinery.FileFinder( fpath_dirname, *loader_details ) spec = file_finder.find_spec(mod_namespace) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: mod = imp.load_module(mod_namespace, None, fpath, desc) # reload all submodules if necessary if not self.initial_load: self._reload_submodules(mod) else: if USE_IMPORTLIB: # pylint: disable=no-member loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath) spec = importlib.util.spec_from_file_location( mod_namespace, fpath, loader=loader ) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() #mod = importlib.util.module_from_spec(spec) #spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: with salt.utils.files.fopen(fpath, desc[1]) as fn_: mod = imp.load_module(mod_namespace, fn_, fpath, desc) except IOError: raise except ImportError as exc: if 'magic number' in six.text_type(exc): error_msg = 'Failed to import {0} {1}. Bad magic number. If migrating from Python2 to Python3, remove all .pyc files and try again.'.format(self.tag, name) log.warning(error_msg) self.missing_modules[name] = error_msg log.debug( 'Failed to import %s %s:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = exc return False except Exception as error: log.error( 'Failed to import %s %s, this is due most likely to a ' 'syntax error:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False except SystemExit as error: try: fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1] except Exception: pass else: tgt_fn = os.path.join('salt', 'utils', 'process.py') if fn_.endswith(tgt_fn) and '_handle_signals' in caller: # Race conditon, SIGTERM or SIGINT received while loader # was in process of loading a module. Call sys.exit to # ensure that the process is killed. sys.exit(salt.defaults.exitcodes.EX_OK) log.error( 'Failed to import %s %s as the module called exit()\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False finally: sys.path.remove(fpath_dirname) if hasattr(mod, '__opts__'): mod.__opts__.update(self.opts) else: mod.__opts__ = self.opts # pack whatever other globals we were asked to for p_name, p_value in six.iteritems(self.pack): _inject_into_mod(mod, p_name, p_value) module_name = mod.__name__.rsplit('.', 1)[-1] # Call a module's initialization method if it exists module_init = getattr(mod, '__init__', None) if inspect.isfunction(module_init): try: module_init(self.opts) except TypeError as e: log.error(e) except Exception: err_string = '__init__ failed' log.debug( 'Error loading %s.%s: %s', self.tag, module_name, err_string, exc_info=True ) self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False # if virtual modules are enabled, we need to look for the # __virtual__() function inside that module and run it. if self.virtual_enable: virtual_funcs_to_process = ['__virtual__'] + self.virtual_funcs for virtual_func in virtual_funcs_to_process: virtual_ret, module_name, virtual_err, virtual_aliases = \ self._process_virtual(mod, module_name, virtual_func) if virtual_err is not None: log.trace( 'Error loading %s.%s: %s', self.tag, module_name, virtual_err ) # if _process_virtual returned a non-True value then we are # supposed to not process this module if virtual_ret is not True and module_name not in self.missing_modules: # If a module has information about why it could not be loaded, record it self.missing_modules[module_name] = virtual_err self.missing_modules[name] = virtual_err return False else: virtual_aliases = () # If this is a proxy minion then MOST modules cannot work. Therefore, require that # any module that does work with salt-proxy-minion define __proxyenabled__ as a list # containing the names of the proxy types that the module supports. # # Render modules and state modules are OK though if 'proxy' in self.opts: if self.tag in ['grains', 'proxy']: if not hasattr(mod, '__proxyenabled__') or \ (self.opts['proxy']['proxytype'] not in mod.__proxyenabled__ and '*' not in mod.__proxyenabled__): err_string = 'not a proxy_minion enabled module' self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False if getattr(mod, '__load__', False) is not False: log.info( 'The functions from module \'%s\' are being loaded from the ' 'provided __load__ attribute', module_name ) # If we had another module by the same virtual name, we should put any # new functions under the existing dictionary. mod_names = [module_name] + list(virtual_aliases) mod_dict = dict(( (x, self.loaded_modules.get(x, self.mod_dict_class())) for x in mod_names )) for attr in getattr(mod, '__load__', dir(mod)): if attr.startswith('_') and attr != '__call__': # private functions are skipped, # except __call__ which is default entrance # for multi-function batch-like state syntax continue func = getattr(mod, attr) if not inspect.isfunction(func) and not isinstance(func, functools.partial): # Not a function!? Skip it!!! continue # Let's get the function name. # If the module has the __func_alias__ attribute, it must be a # dictionary mapping in the form of(key -> value): # <real-func-name> -> <desired-func-name> # # It default's of course to the found callable attribute name # if no alias is defined. funcname = getattr(mod, '__func_alias__', {}).get(attr, attr) for tgt_mod in mod_names: try: full_funcname = '.'.join((tgt_mod, funcname)) except TypeError: full_funcname = '{0}.{1}'.format(tgt_mod, funcname) # Save many references for lookups # Careful not to overwrite existing (higher priority) functions if full_funcname not in self._dict: self._dict[full_funcname] = func if funcname not in mod_dict[tgt_mod]: setattr(mod_dict[tgt_mod], funcname, func) mod_dict[tgt_mod][funcname] = func self._apply_outputter(func, mod) # enforce depends try: Depends.enforce_dependencies(self._dict, self.tag) except RuntimeError as exc: log.info( 'Depends.enforce_dependencies() failed for the following ' 'reason: %s', exc ) for tgt_mod in mod_names: self.loaded_modules[tgt_mod] = mod_dict[tgt_mod] return True def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise KeyError('The key \'{0}\' should contain a \'.\''.format(key)) mod_name, _ = key.split('.', 1) with self._lock: # It is possible that the key is in the dictionary after # acquiring the lock due to another thread loading it. if mod_name in self.missing_modules or key in self._dict: return True # if the modulename isn't in the whitelist, don't bother if self.whitelist and mod_name not in self.whitelist: log.error( 'Failed to load function %s because its module (%s) is ' 'not in the whitelist: %s', key, mod_name, self.whitelist ) raise KeyError(key) def _inner_load(mod_name): for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and key in self._dict: return True return False # try to load the module ret = None reloaded = False # re-scan up to once, IOErrors or a failed load cause re-scans of the # filesystem while True: try: ret = _inner_load(mod_name) if not reloaded and ret is not True: self._refresh_file_mapping() reloaded = True continue break except IOError: if not reloaded: self._refresh_file_mapping() reloaded = True continue return ret def _load_all(self): ''' Load all of them ''' with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True def reload_modules(self): with self._lock: self.loaded_files = set() self._load_all() def _apply_outputter(self, func, mod): ''' Apply the __outputter__ variable to the functions ''' if hasattr(mod, '__outputter__'): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__] def _process_virtual(self, mod, module_name, virtual_func='__virtual__'): ''' Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1] ''' # The __virtual__ function will return either a True or False value. # If it returns a True value it can also set a module level attribute # named __virtualname__ with the name that the module should be # referred to as. # # This allows us to have things like the pkg module working on all # platforms under the name 'pkg'. It also allows for modules like # augeas_cfg to be referred to as 'augeas', which would otherwise have # namespace collisions. And finally it allows modules to return False # if they are not intended to run on the given platform or are missing # dependencies. virtual_aliases = getattr(mod, '__virtual_aliases__', tuple()) try: error_reason = None if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__): try: start = time.time() virtual = getattr(mod, virtual_func)() if isinstance(virtual, tuple): error_reason = virtual[1] virtual = virtual[0] if self.opts.get('virtual_timer', False): end = time.time() - start msg = 'Virtual function took {0} seconds for {1}'.format( end, module_name) log.warning(msg) except Exception as exc: error_reason = ( 'Exception raised when processing __virtual__ function' ' for {0}. Module will not be loaded: {1}'.format( mod.__name__, exc)) log.error(error_reason, exc_info_on_loglevel=logging.DEBUG) virtual = None # Get the module's virtual name virtualname = getattr(mod, '__virtualname__', virtual) if not virtual: # if __virtual__() evaluates to False then the module # wasn't meant for this platform or it's not supposed to # load for some other reason. # Some modules might accidentally return None and are # improperly loaded if virtual is None: log.warning( '%s.__virtual__() is wrongly returning `None`. ' 'It should either return `True`, `False` or a new ' 'name. If you\'re the developer of the module ' '\'%s\', please fix this.', mod.__name__, module_name ) return (False, module_name, error_reason, virtual_aliases) # At this point, __virtual__ did not return a # boolean value, let's check for deprecated usage # or module renames if virtual is not True and module_name != virtual: # The module is renaming itself. Updating the module name # with the new name log.trace('Loaded %s as virtual %s', module_name, virtual) if virtualname != virtual: # The __virtualname__ attribute does not match what's # being returned by the __virtual__() function. This # should be considered an error. log.error( 'The module \'%s\' is showing some bad usage. Its ' '__virtualname__ attribute is set to \'%s\' yet the ' '__virtual__() function is returning \'%s\'. These ' 'values should match!', mod.__name__, virtualname, virtual ) module_name = virtualname # If the __virtual__ function returns True and __virtualname__ # is set then use it elif virtual is True and virtualname != module_name: if virtualname is not True: module_name = virtualname except KeyError: # Key errors come out of the virtual function when passing # in incomplete grains sets, these can be safely ignored # and logged to debug, still, it includes the traceback to # help debugging. log.debug('KeyError when loading %s', module_name, exc_info=True) except Exception: # If the module throws an exception during __virtual__() # then log the information and continue to the next. log.error( 'Failed to read the virtual function for %s: %s', self.tag, module_name, exc_info=True ) return (False, module_name, error_reason, virtual_aliases) return (True, module_name, None, virtual_aliases) def global_injector_decorator(inject_globals): ''' Decorator used by the LazyLoader to inject globals into a function at execute time. globals Dictionary with global variables to inject ''' def inner_decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): with salt.utils.context.func_globals_inject(f, **inject_globals): return f(*args, **kwargs) return wrapper return inner_decorator
saltstack/salt
salt/loader.py
tops
python
def tops(opts): ''' Returns the tops modules ''' if 'master_tops' not in opts: return {} whitelist = list(opts['master_tops'].keys()) ret = LazyLoader( _module_dirs(opts, 'tops', 'top'), opts, tag='top', whitelist=whitelist, ) return FilterDictWrapper(ret, '.top')
Returns the tops modules
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L413-L426
null
# -*- coding: utf-8 -*- ''' The Salt loader is the core to Salt's plugin system, the loader scans directories for python loadable code and organizes the code into the plugin interfaces used by Salt. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import sys import time import logging import inspect import tempfile import threading import functools import threading import traceback import types from zipimport import zipimporter # Import salt libs import salt.config import salt.defaults.events import salt.defaults.exitcodes import salt.syspaths import salt.utils.args import salt.utils.context import salt.utils.data import salt.utils.dictupdate import salt.utils.event import salt.utils.files import salt.utils.lazy import salt.utils.odict import salt.utils.platform import salt.utils.versions import salt.utils.stringutils from salt.exceptions import LoaderError from salt.template import check_render_pipe_str from salt.utils.decorators import Depends from salt.utils.thread_local_proxy import ThreadLocalProxy # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import reload_module if sys.version_info[:2] >= (3, 5): import importlib.machinery # pylint: disable=no-name-in-module,import-error import importlib.util # pylint: disable=no-name-in-module,import-error USE_IMPORTLIB = True else: import imp USE_IMPORTLIB = False try: from collections.abc import MutableMapping except ImportError: from collections import MutableMapping try: import pkg_resources HAS_PKG_RESOURCES = True except ImportError: HAS_PKG_RESOURCES = False log = logging.getLogger(__name__) SALT_BASE_PATH = os.path.abspath(salt.syspaths.INSTALL_DIR) LOADED_BASE_NAME = 'salt.loaded' if USE_IMPORTLIB: # pylint: disable=no-member MODULE_KIND_SOURCE = 1 MODULE_KIND_COMPILED = 2 MODULE_KIND_EXTENSION = 3 MODULE_KIND_PKG_DIRECTORY = 5 SUFFIXES = [] for suffix in importlib.machinery.EXTENSION_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_EXTENSION)) for suffix in importlib.machinery.SOURCE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_SOURCE)) for suffix in importlib.machinery.BYTECODE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_COMPILED)) MODULE_KIND_MAP = { MODULE_KIND_SOURCE: importlib.machinery.SourceFileLoader, MODULE_KIND_COMPILED: importlib.machinery.SourcelessFileLoader, MODULE_KIND_EXTENSION: importlib.machinery.ExtensionFileLoader } # pylint: enable=no-member else: SUFFIXES = imp.get_suffixes() PY3_PRE_EXT = \ re.compile(r'\.cpython-{0}{1}(\.opt-[1-9])?'.format(*sys.version_info[:2])) # Because on the cloud drivers we do `from salt.cloud.libcloudfuncs import *` # which simplifies code readability, it adds some unsupported functions into # the driver's module scope. # We list un-supported functions here. These will be removed from the loaded. # TODO: remove the need for this cross-module code. Maybe use NotImplemented LIBCLOUD_FUNCS_NOT_SUPPORTED = ( 'parallels.avail_sizes', 'parallels.avail_locations', 'proxmox.avail_sizes', ) # Will be set to pyximport module at runtime if cython is enabled in config. pyximport = None def static_loader( opts, ext_type, tag, pack=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, filter_name=None, ): funcs = LazyLoader( _module_dirs( opts, ext_type, tag, int_type, ext_dirs, ext_type_dirs, base_path, ), opts, tag=tag, pack=pack, ) ret = {} funcs._load_all() if filter_name: funcs = FilterDictWrapper(funcs, filter_name) for key in funcs: ret[key] = funcs[key] return ret def _format_entrypoint_target(ep): ''' Makes a string describing the target of an EntryPoint object. Base strongly on EntryPoint.__str__(). ''' s = ep.module_name if ep.attrs: s += ':' + '.'.join(ep.attrs) return s def _module_dirs( opts, ext_type, tag=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, ): if tag is None: tag = ext_type sys_types = os.path.join(base_path or SALT_BASE_PATH, int_type or ext_type) ext_types = os.path.join(opts['extension_modules'], ext_type) ext_type_types = [] if ext_dirs: if ext_type_dirs is None: ext_type_dirs = '{0}_dirs'.format(tag) if ext_type_dirs in opts: ext_type_types.extend(opts[ext_type_dirs]) if HAS_PKG_RESOURCES and ext_type_dirs: for entry_point in pkg_resources.iter_entry_points('salt.loader', ext_type_dirs): try: loaded_entry_point = entry_point.load() for path in loaded_entry_point(): ext_type_types.append(path) except Exception as exc: log.error("Error getting module directories from %s: %s", _format_entrypoint_target(entry_point), exc) log.debug("Full backtrace for module directories error", exc_info=True) cli_module_dirs = [] # The dirs can be any module dir, or a in-tree _{ext_type} dir for _dir in opts.get('module_dirs', []): # Prepend to the list to match cli argument ordering maybe_dir = os.path.join(_dir, ext_type) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) continue maybe_dir = os.path.join(_dir, '_{0}'.format(ext_type)) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) return cli_module_dirs + ext_type_types + [ext_types, sys_types] def minion_mods( opts, context=None, utils=None, whitelist=None, initial_load=False, loaded_base_name=None, notify=False, static_modules=None, proxy=None): ''' Load execution modules Returns a dictionary of execution modules appropriate for the current system by evaluating the __virtual__() function in each module. :param dict opts: The Salt options dictionary :param dict context: A Salt context that should be made present inside generated modules in __context__ :param dict utils: Utility functions which should be made available to Salt modules in __utils__. See `utils_dirs` in salt.config for additional information about configuration. :param list whitelist: A list of modules which should be whitelisted. :param bool initial_load: Deprecated flag! Unused. :param str loaded_base_name: A string marker for the loaded base name. :param bool notify: Flag indicating that an event should be fired upon completion of module loading. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) __opts__['grains'] = __grains__ __utils__ = salt.loader.utils(__opts__) __salt__ = salt.loader.minion_mods(__opts__, utils=__utils__) __salt__['test.ping']() ''' # TODO Publish documentation for module whitelisting if not whitelist: whitelist = opts.get('whitelist_modules', None) ret = LazyLoader( _module_dirs(opts, 'modules', 'module'), opts, tag='module', pack={'__context__': context, '__utils__': utils, '__proxy__': proxy}, whitelist=whitelist, loaded_base_name=loaded_base_name, static_modules=static_modules, ) ret.pack['__salt__'] = ret # Load any provider overrides from the configuration file providers option # Note: Providers can be pkg, service, user or group - not to be confused # with cloud providers. providers = opts.get('providers', False) if providers and isinstance(providers, dict): for mod in providers: # sometimes providers opts is not to diverge modules but # for other configuration try: funcs = raw_mod(opts, providers[mod], ret) except TypeError: break else: if funcs: for func in funcs: f_key = '{0}{1}'.format(mod, func[func.rindex('.'):]) ret[f_key] = funcs[func] if notify: evt = salt.utils.event.get_event('minion', opts=opts, listen=False) evt.fire_event({'complete': True}, tag=salt.defaults.events.MINION_MOD_COMPLETE) return ret def raw_mod(opts, name, functions, mod='modules'): ''' Returns a single module loaded raw and bypassing the __virtual__ function .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') testmod = salt.loader.raw_mod(__opts__, 'test', None) testmod['test.ping']() ''' loader = LazyLoader( _module_dirs(opts, mod, 'module'), opts, tag='rawmodule', virtual_enable=False, pack={'__salt__': functions}, ) # if we don't have the module, return an empty dict if name not in loader.file_mapping: return {} loader._load_module(name) # load a single module (the one passed in) return dict(loader._dict) # return a copy of *just* the funcs for `name` def metaproxy(opts): ''' Return functions used in the meta proxy ''' return LazyLoader( _module_dirs(opts, 'metaproxy'), opts, tag='metaproxy' ) def matchers(opts): ''' Return the matcher services plugins ''' return LazyLoader( _module_dirs(opts, 'matchers'), opts, tag='matchers' ) def engines(opts, functions, runners, utils, proxy=None): ''' Return the master services plugins ''' pack = {'__salt__': functions, '__runners__': runners, '__proxy__': proxy, '__utils__': utils} return LazyLoader( _module_dirs(opts, 'engines'), opts, tag='engines', pack=pack, ) def proxy(opts, functions=None, returners=None, whitelist=None, utils=None): ''' Returns the proxy module for this salt-proxy-minion ''' ret = LazyLoader( _module_dirs(opts, 'proxy'), opts, tag='proxy', pack={'__salt__': functions, '__ret__': returners, '__utils__': utils}, ) ret.pack['__proxy__'] = ret return ret def returners(opts, functions, whitelist=None, context=None, proxy=None): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'returners', 'returner'), opts, tag='returner', whitelist=whitelist, pack={'__salt__': functions, '__context__': context, '__proxy__': proxy or {}}, ) def utils(opts, whitelist=None, context=None, proxy=proxy): ''' Returns the utility modules ''' return LazyLoader( _module_dirs(opts, 'utils', ext_type_dirs='utils_dirs'), opts, tag='utils', whitelist=whitelist, pack={'__context__': context, '__proxy__': proxy or {}}, ) def pillars(opts, functions, context=None): ''' Returns the pillars modules ''' ret = LazyLoader(_module_dirs(opts, 'pillar'), opts, tag='pillar', pack={'__salt__': functions, '__context__': context, '__utils__': utils(opts)}) ret.pack['__ext_pillar__'] = ret return FilterDictWrapper(ret, '.ext_pillar') def wheels(opts, whitelist=None, context=None): ''' Returns the wheels modules ''' if context is None: context = {} return LazyLoader( _module_dirs(opts, 'wheel'), opts, tag='wheel', whitelist=whitelist, pack={'__context__': context}, ) def outputters(opts): ''' Returns the outputters modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only outputters present in the keyspace ''' ret = LazyLoader( _module_dirs(opts, 'output', ext_type_dirs='outputter_dirs'), opts, tag='output', ) wrapped_ret = FilterDictWrapper(ret, '.output') # TODO: this name seems terrible... __salt__ should always be execution mods ret.pack['__salt__'] = wrapped_ret return wrapped_ret def serializers(opts): ''' Returns the serializers modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only serializers present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'serializers'), opts, tag='serializers', ) def eauth_tokens(opts): ''' Returns the tokens modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only token backends present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'tokens'), opts, tag='tokens', ) def auth(opts, whitelist=None): ''' Returns the auth modules :param dict opts: The Salt options dictionary :returns: LazyLoader ''' return LazyLoader( _module_dirs(opts, 'auth'), opts, tag='auth', whitelist=whitelist, pack={'__salt__': minion_mods(opts)}, ) def fileserver(opts, backends): ''' Returns the file server modules ''' return LazyLoader(_module_dirs(opts, 'fileserver'), opts, tag='fileserver', whitelist=backends, pack={'__utils__': utils(opts)}) def roster(opts, runner=None, utils=None, whitelist=None): ''' Returns the roster modules ''' return LazyLoader( _module_dirs(opts, 'roster'), opts, tag='roster', whitelist=whitelist, pack={ '__runner__': runner, '__utils__': utils, }, ) def thorium(opts, functions, runners): ''' Load the thorium runtime modules ''' pack = {'__salt__': functions, '__runner__': runners, '__context__': {}} ret = LazyLoader(_module_dirs(opts, 'thorium'), opts, tag='thorium', pack=pack) ret.pack['__thorium__'] = ret return ret def states(opts, functions, utils, serializers, whitelist=None, proxy=None, context=None): ''' Returns the state modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') statemods = salt.loader.states(__opts__, None, None) ''' if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'states'), opts, tag='states', pack={'__salt__': functions, '__proxy__': proxy or {}}, whitelist=whitelist, ) ret.pack['__states__'] = ret ret.pack['__utils__'] = utils ret.pack['__serializers__'] = serializers ret.pack['__context__'] = context return ret def beacons(opts, functions, context=None, proxy=None): ''' Load the beacon modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. ''' return LazyLoader( _module_dirs(opts, 'beacons'), opts, tag='beacons', pack={'__context__': context, '__salt__': functions, '__proxy__': proxy or {}}, virtual_funcs=[], ) def log_handlers(opts): ''' Returns the custom logging handler modules :param dict opts: The Salt options dictionary ''' ret = LazyLoader( _module_dirs( opts, 'log_handlers', int_type='handlers', base_path=os.path.join(SALT_BASE_PATH, 'log'), ), opts, tag='log_handlers', ) return FilterDictWrapper(ret, '.setup_handlers') def ssh_wrapper(opts, functions=None, context=None): ''' Returns the custom logging handler modules ''' return LazyLoader( _module_dirs( opts, 'wrapper', base_path=os.path.join(SALT_BASE_PATH, os.path.join('client', 'ssh')), ), opts, tag='wrapper', pack={ '__salt__': functions, '__grains__': opts.get('grains', {}), '__pillar__': opts.get('pillar', {}), '__context__': context, }, ) def render(opts, functions, states=None, proxy=None, context=None): ''' Returns the render modules ''' if context is None: context = {} pack = {'__salt__': functions, '__grains__': opts.get('grains', {}), '__context__': context} if states: pack['__states__'] = states pack['__proxy__'] = proxy or {} ret = LazyLoader( _module_dirs( opts, 'renderers', 'render', ext_type_dirs='render_dirs', ), opts, tag='render', pack=pack, ) rend = FilterDictWrapper(ret, '.render') if not check_render_pipe_str(opts['renderer'], rend, opts['renderer_blacklist'], opts['renderer_whitelist']): err = ('The renderer {0} is unavailable, this error is often because ' 'the needed software is unavailable'.format(opts['renderer'])) log.critical(err) raise LoaderError(err) return rend def grain_funcs(opts, proxy=None): ''' Returns the grain functions .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') grainfuncs = salt.loader.grain_funcs(__opts__) ''' ret = LazyLoader( _module_dirs( opts, 'grains', 'grain', ext_type_dirs='grains_dirs', ), opts, tag='grains', ) ret.pack['__utils__'] = utils(opts, proxy=proxy) return ret def _load_cached_grains(opts, cfn): ''' Returns the grains cached in cfn, or None if the cache is too old or is corrupted. ''' if not os.path.isfile(cfn): log.debug('Grains cache file does not exist.') return None grains_cache_age = int(time.time() - os.path.getmtime(cfn)) if grains_cache_age > opts.get('grains_cache_expiration', 300): log.debug( 'Grains cache last modified %s seconds ago and cache ' 'expiration is set to %s. Grains cache expired. ' 'Refreshing.', grains_cache_age, opts.get('grains_cache_expiration', 300) ) return None if opts.get('refresh_grains_cache', False): log.debug('refresh_grains_cache requested, Refreshing.') return None log.debug('Retrieving grains from cache') try: serial = salt.payload.Serial(opts) with salt.utils.files.fopen(cfn, 'rb') as fp_: cached_grains = salt.utils.data.decode(serial.load(fp_), preserve_tuples=True) if not cached_grains: log.debug('Cached grains are empty, cache might be corrupted. Refreshing.') return None return cached_grains except (IOError, OSError): return None def grains(opts, force_refresh=False, proxy=None): ''' Return the functions for the dynamic grains and the values for the static grains. Since grains are computed early in the startup process, grains functions do not have __salt__ or __proxy__ available. At proxy-minion startup, this function is called with the proxymodule LazyLoader object so grains functions can communicate with their controlled device. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) print __grains__['id'] ''' # Need to re-import salt.config, somehow it got lost when a minion is starting import salt.config # if we have no grains, lets try loading from disk (TODO: move to decorator?) cfn = os.path.join( opts['cachedir'], 'grains.cache.p' ) if not force_refresh and opts.get('grains_cache', False): cached_grains = _load_cached_grains(opts, cfn) if cached_grains: return cached_grains else: log.debug('Grains refresh requested. Refreshing grains.') if opts.get('skip_grains', False): return {} grains_deep_merge = opts.get('grains_deep_merge', False) is True if 'conf_file' in opts: pre_opts = {} pre_opts.update(salt.config.load_config( opts['conf_file'], 'SALT_MINION_CONFIG', salt.config.DEFAULT_MINION_OPTS['conf_file'] )) default_include = pre_opts.get( 'default_include', opts['default_include'] ) include = pre_opts.get('include', []) pre_opts.update(salt.config.include_config( default_include, opts['conf_file'], verbose=False )) pre_opts.update(salt.config.include_config( include, opts['conf_file'], verbose=True )) if 'grains' in pre_opts: opts['grains'] = pre_opts['grains'] else: opts['grains'] = {} else: opts['grains'] = {} grains_data = {} blist = opts.get('grains_blacklist', []) funcs = grain_funcs(opts, proxy=proxy) if force_refresh: # if we refresh, lets reload grain modules funcs.clear() # Run core grains for key in funcs: if not key.startswith('core.'): continue log.trace('Loading %s grain', key) ret = funcs[key]() if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) # Run the rest of the grains for key in funcs: if key.startswith('core.') or key == '_errors': continue try: # Grains are loaded too early to take advantage of the injected # __proxy__ variable. Pass an instance of that LazyLoader # here instead to grains functions if the grains functions take # one parameter. Then the grains can have access to the # proxymodule for retrieving information from the connected # device. log.trace('Loading %s grain', key) parameters = salt.utils.args.get_function_argspec(funcs[key]).args kwargs = {} if 'proxy' in parameters: kwargs['proxy'] = proxy if 'grains' in parameters: kwargs['grains'] = grains_data ret = funcs[key](**kwargs) except Exception: if salt.utils.platform.is_proxy(): log.info('The following CRITICAL message may not be an error; the proxy may not be completely established yet.') log.critical( 'Failed to load grains defined in grain file %s in ' 'function %s, error:\n', key, funcs[key], exc_info=True ) continue if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) if opts.get('proxy_merge_grains_in_module', True) and proxy: try: proxytype = proxy.opts['proxy']['proxytype'] if proxytype + '.grains' in proxy: if proxytype + '.initialized' in proxy and proxy[proxytype + '.initialized'](): try: proxytype = proxy.opts['proxy']['proxytype'] ret = proxy[proxytype + '.grains']() if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) except Exception: log.critical('Failed to run proxy\'s grains function!', exc_info=True ) except KeyError: pass grains_data.update(opts['grains']) # Write cache if enabled if opts.get('grains_cache', False): with salt.utils.files.set_umask(0o077): try: if salt.utils.platform.is_windows(): # Late import import salt.modules.cmdmod # Make sure cache file isn't read-only salt.modules.cmdmod._run_quiet('attrib -R "{0}"'.format(cfn)) with salt.utils.files.fopen(cfn, 'w+b') as fp_: try: serial = salt.payload.Serial(opts) serial.dump(grains_data, fp_) except TypeError as e: log.error('Failed to serialize grains cache: %s', e) raise # re-throw for cleanup except Exception as e: log.error('Unable to write to grains cache file %s: %s', cfn, e) # Based on the original exception, the file may or may not have been # created. If it was, we will remove it now, as the exception means # the serialized data is not to be trusted, no matter what the # exception is. if os.path.isfile(cfn): os.unlink(cfn) if grains_deep_merge: salt.utils.dictupdate.update(grains_data, opts['grains']) else: grains_data.update(opts['grains']) return salt.utils.data.decode(grains_data, preserve_tuples=True) # TODO: get rid of? Does anyone use this? You should use raw() instead def call(fun, **kwargs): ''' Directly call a function inside a loader directory ''' args = kwargs.get('args', []) dirs = kwargs.get('dirs', []) funcs = LazyLoader( [os.path.join(SALT_BASE_PATH, 'modules')] + dirs, None, tag='modules', virtual_enable=False, ) return funcs[fun](*args) def runner(opts, utils=None, context=None, whitelist=None): ''' Directly call a function inside a loader directory ''' if utils is None: utils = {} if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'runners', 'runner', ext_type_dirs='runner_dirs'), opts, tag='runners', pack={'__utils__': utils, '__context__': context}, whitelist=whitelist, ) # TODO: change from __salt__ to something else, we overload __salt__ too much ret.pack['__salt__'] = ret return ret def queues(opts): ''' Directly call a function inside a loader directory ''' return LazyLoader( _module_dirs(opts, 'queues', 'queue', ext_type_dirs='queue_dirs'), opts, tag='queues', ) def sdb(opts, functions=None, whitelist=None, utils=None): ''' Make a very small database call ''' if utils is None: utils = {} return LazyLoader( _module_dirs(opts, 'sdb'), opts, tag='sdb', pack={ '__sdb__': functions, '__opts__': opts, '__utils__': utils, '__salt__': minion_mods(opts, utils), }, whitelist=whitelist, ) def pkgdb(opts): ''' Return modules for SPM's package database .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgdb', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgdb' ) def pkgfiles(opts): ''' Return modules for SPM's file handling .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgfiles', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgfiles' ) def clouds(opts): ''' Return the cloud functions ''' # Let's bring __active_provider_name__, defaulting to None, to all cloud # drivers. This will get temporarily updated/overridden with a context # manager when needed. functions = LazyLoader( _module_dirs(opts, 'clouds', 'cloud', base_path=os.path.join(SALT_BASE_PATH, 'cloud'), int_type='clouds'), opts, tag='clouds', pack={'__utils__': salt.loader.utils(opts), '__active_provider_name__': None}, ) for funcname in LIBCLOUD_FUNCS_NOT_SUPPORTED: log.trace( '\'%s\' has been marked as not supported. Removing from the ' 'list of supported cloud functions', funcname ) functions.pop(funcname, None) return functions def netapi(opts): ''' Return the network api functions ''' return LazyLoader( _module_dirs(opts, 'netapi'), opts, tag='netapi', ) def executors(opts, functions=None, context=None, proxy=None): ''' Returns the executor modules ''' executors = LazyLoader( _module_dirs(opts, 'executors', 'executor'), opts, tag='executor', pack={'__salt__': functions, '__context__': context or {}, '__proxy__': proxy or {}}, ) executors.pack['__executors__'] = executors return executors def cache(opts, serial): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'cache', 'cache'), opts, tag='cache', pack={'__opts__': opts, '__context__': {'serial': serial}}, ) def _generate_module(name): if name in sys.modules: return code = "'''Salt loaded {0} parent module'''".format(name.split('.')[-1]) # ModuleType can't accept a unicode type on PY2 module = types.ModuleType(str(name)) # future lint: disable=blacklisted-function exec(code, module.__dict__) sys.modules[name] = module def _mod_type(module_path): if module_path.startswith(SALT_BASE_PATH): return 'int' return 'ext' def _inject_into_mod(mod, name, value, force_lock=False): ''' Inject a variable into a module. This is used to inject "globals" like ``__salt__``, ``__pillar``, or ``grains``. Instead of injecting the value directly, a ``ThreadLocalProxy`` is created. If such a proxy is already present under the specified name, it is updated with the new value. This update only affects the current thread, so that the same name can refer to different values depending on the thread of execution. This is important for data that is not truly global. For example, pillar data might be dynamically overriden through function parameters and thus the actual values available in pillar might depend on the thread that is calling a module. mod: module object into which the value is going to be injected. name: name of the variable that is injected into the module. value: value that is injected into the variable. The value is not injected directly, but instead set as the new reference of the proxy that has been created for the variable. force_lock: whether the lock should be acquired before checking whether a proxy object for the specified name has already been injected into the module. If ``False`` (the default), this function checks for the module's variable without acquiring the lock and only acquires the lock if a new proxy has to be created and injected. ''' old_value = getattr(mod, name, None) # We use a double-checked locking scheme in order to avoid taking the lock # when a proxy object has already been injected. # In most programming languages, double-checked locking is considered # unsafe when used without explicit memory barriers because one might read # an uninitialized value. In CPython it is safe due to the global # interpreter lock (GIL). In Python implementations that do not have the # GIL, it could be unsafe, but at least Jython also guarantees that (for # Python objects) memory is not corrupted when writing and reading without # explicit synchronization # (http://www.jython.org/jythonbook/en/1.0/Concurrency.html). # Please note that in order to make this code safe in a runtime environment # that does not make this guarantees, it is not sufficient. The # ThreadLocalProxy must also be created with fallback_to_shared set to # False or a lock must be added to the ThreadLocalProxy. if force_lock: with _inject_into_mod.lock: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: setattr(mod, name, ThreadLocalProxy(value, True)) else: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: _inject_into_mod(mod, name, value, True) # Lock used when injecting globals. This is needed to avoid a race condition # when two threads try to load the same module concurrently. This must be # outside the loader because there might be more than one loader for the same # namespace. _inject_into_mod.lock = threading.RLock() # TODO: move somewhere else? class FilterDictWrapper(MutableMapping): ''' Create a dict which wraps another dict with a specific key suffix on get This is to replace "filter_load" ''' def __init__(self, d, suffix): self._dict = d self.suffix = suffix def __setitem__(self, key, val): self._dict[key] = val def __delitem__(self, key): del self._dict[key] def __getitem__(self, key): return self._dict[key + self.suffix] def __len__(self): return len(self._dict) def __iter__(self): for key in self._dict: if key.endswith(self.suffix): yield key.replace(self.suffix, '') class LazyLoader(salt.utils.lazy.LazyDict): ''' A pseduo-dictionary which has a set of keys which are the name of the module and function, delimited by a dot. When the value of the key is accessed, the function is then loaded from disk and into memory. .. note:: Iterating over keys will cause all modules to be loaded. :param list module_dirs: A list of directories on disk to search for modules :param dict opts: The salt options dictionary. :param str tag: The tag for the type of module to load :param func mod_type_check: A function which can be used to verify files :param dict pack: A dictionary of function to be packed into modules as they are loaded :param list whitelist: A list of modules to whitelist :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules. :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality. If not true, the module will not load. :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values are function references themselves which are loaded on-demand. # TODO: - move modules_max_memory into here - singletons (per tag) ''' mod_dict_class = salt.utils.odict.OrderedDict def __init__(self, module_dirs, opts=None, tag='module', loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, proxy=None, virtual_funcs=None, ): # pylint: disable=W0231 ''' In pack, if any of the values are None they will be replaced with an empty context-specific dict ''' self.inject_globals = {} self.pack = {} if pack is None else pack if opts is None: opts = {} threadsafety = not opts.get('multiprocessing') self.context_dict = salt.utils.context.ContextDict(threadsafe=threadsafety) self.opts = self.__prep_mod_opts(opts) self.module_dirs = module_dirs self.tag = tag self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME self.mod_type_check = mod_type_check or _mod_type if '__context__' not in self.pack: self.pack['__context__'] = None for k, v in six.iteritems(self.pack): if v is None: # if the value of a pack is None, lets make an empty dict value = self.context_dict.get(k, {}) if isinstance(value, ThreadLocalProxy): value = ThreadLocalProxy.unproxy(value) self.context_dict[k] = value self.pack[k] = salt.utils.context.NamespacedDictWrapper(self.context_dict, k) self.whitelist = whitelist self.virtual_enable = virtual_enable self.initial_load = True # names of modules that we don't have (errors, __virtual__, etc.) self.missing_modules = {} # mapping of name -> error self.loaded_modules = {} # mapping of module_name -> dict_of_functions self.loaded_files = set() # TODO: just remove them from file_mapping? self.static_modules = static_modules if static_modules else [] if virtual_funcs is None: virtual_funcs = [] self.virtual_funcs = virtual_funcs self.disabled = set( self.opts.get( 'disable_{0}{1}'.format( self.tag, '' if self.tag[-1] == 's' else 's' ), [] ) ) # A map of suffix to description for imp self.suffix_map = {} # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [''] for (suffix, mode, kind) in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) self._lock = threading.RLock() self._refresh_file_mapping() super(LazyLoader, self).__init__() # late init the lazy loader # create all of the import namespaces _generate_module('{0}.int'.format(self.loaded_base_name)) _generate_module('{0}.int.{1}'.format(self.loaded_base_name, tag)) _generate_module('{0}.ext'.format(self.loaded_base_name)) _generate_module('{0}.ext.{1}'.format(self.loaded_base_name, tag)) def __getitem__(self, item): ''' Override the __getitem__ in order to decorate the returned function if we need to last-minute inject globals ''' func = super(LazyLoader, self).__getitem__(item) if self.inject_globals: return global_injector_decorator(self.inject_globals)(func) else: return func def __getattr__(self, mod_name): ''' Allow for "direct" attribute access-- this allows jinja templates to access things like `salt.test.ping()` ''' if mod_name in ('__getstate__', '__setstate__'): return object.__getattribute__(self, mod_name) # if we have an attribute named that, lets return it. try: return object.__getattr__(self, mod_name) # pylint: disable=no-member except AttributeError: pass # otherwise we assume its jinja template access if mod_name not in self.loaded_modules and not self.loaded: for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and mod_name in self.loaded_modules: break if mod_name in self.loaded_modules: return self.loaded_modules[mod_name] else: raise AttributeError(mod_name) def missing_fun_string(self, function_name): ''' Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ''' mod_name = function_name.split('.')[0] if mod_name in self.loaded_modules: return '\'{0}\' is not available.'.format(function_name) else: try: reason = self.missing_modules[mod_name] except KeyError: return '\'{0}\' is not available.'.format(function_name) else: if reason is not None: return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason) else: return '\'{0}\' __virtual__ returned False'.format(mod_name) def _refresh_file_mapping(self): ''' refresh the mapping of the FS on disk ''' # map of suffix to description for imp if self.opts.get('cython_enable', True) is True: try: global pyximport pyximport = __import__('pyximport') # pylint: disable=import-error pyximport.install() # add to suffix_map so file_mapping will pick it up self.suffix_map['.pyx'] = tuple() except ImportError: log.info('Cython is enabled in the options but not present ' 'in the system path. Skipping Cython modules.') # Allow for zipimport of modules if self.opts.get('enable_zip_modules', True) is True: self.suffix_map['.zip'] = tuple() # allow for module dirs if USE_IMPORTLIB: self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY) else: self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY) # create mapping of filename (without suffix) to (path, suffix) # The files are added in order of priority, so order *must* be retained. self.file_mapping = salt.utils.odict.OrderedDict() opt_match = [] def _replace_pre_ext(obj): ''' Hack so we can get the optimization level that we replaced (if any) out of the re.sub call below. We use a list here because it is a persistent data structure that we will be able to access after re.sub is called. ''' opt_match.append(obj) return '' for mod_dir in self.module_dirs: try: # Make sure we have a sorted listdir in order to have # expectable override results files = sorted( x for x in os.listdir(mod_dir) if x != '__pycache__' ) except OSError: continue # Next mod_dir if six.PY3: try: pycache_files = [ os.path.join('__pycache__', x) for x in sorted(os.listdir(os.path.join(mod_dir, '__pycache__'))) ] except OSError: pass else: files.extend(pycache_files) for filename in files: try: dirname, basename = os.path.split(filename) if basename.startswith('_'): # skip private modules # log messages omitted for obviousness continue # Next filename f_noext, ext = os.path.splitext(basename) if six.PY3: f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext) try: opt_level = int( opt_match.pop().group(1).rsplit('-', 1)[-1] ) except (AttributeError, IndexError, ValueError): # No regex match or no optimization level matched opt_level = 0 try: opt_index = self.opts['optimization_order'].index(opt_level) except KeyError: log.trace( 'Disallowed optimization level %d for module ' 'name \'%s\', skipping. Add %d to the ' '\'optimization_order\' config option if you ' 'do not want to ignore this optimization ' 'level.', opt_level, f_noext, opt_level ) continue else: # Optimization level not reflected in filename on PY2 opt_index = 0 # make sure it is a suffix we support if ext not in self.suffix_map: continue # Next filename if f_noext in self.disabled: log.trace( 'Skipping %s, it is disabled by configuration', filename ) continue # Next filename fpath = os.path.join(mod_dir, filename) # if its a directory, lets allow us to load that if ext == '': # is there something __init__? subfiles = os.listdir(fpath) for suffix in self.suffix_order: if '' == suffix: continue # Next suffix (__init__ must have a suffix) init_file = '__init__{0}'.format(suffix) if init_file in subfiles: break else: continue # Next filename try: curr_ext = self.file_mapping[f_noext][1] curr_opt_index = self.file_mapping[f_noext][2] except KeyError: pass else: if '' in (curr_ext, ext) and curr_ext != ext: log.error( 'Module/package collision: \'%s\' and \'%s\'', fpath, self.file_mapping[f_noext][0] ) if six.PY3 and ext == '.pyc' and curr_ext == '.pyc': # Check the optimization level if opt_index >= curr_opt_index: # Module name match, but a higher-priority # optimization level was already matched, skipping. continue elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext): # Match found but a higher-priorty match already # exists, so skip this. continue if six.PY3 and not dirname and ext == '.pyc': # On Python 3, we should only load .pyc files from the # __pycache__ subdirectory (i.e. when dirname is not an # empty string). continue # Made it this far - add it self.file_mapping[f_noext] = (fpath, ext, opt_index) except OSError: continue for smod in self.static_modules: f_noext = smod.split('.')[-1] self.file_mapping[f_noext] = (smod, '.o', 0) def clear(self): ''' Clear the dict ''' with self._lock: super(LazyLoader, self).clear() # clear the lazy loader self.loaded_files = set() self.missing_modules = {} self.loaded_modules = {} # if we have been loaded before, lets clear the file mapping since # we obviously want a re-do if hasattr(self, 'opts'): self._refresh_file_mapping() self.initial_load = False def __prep_mod_opts(self, opts): ''' Strip out of the opts any logger instance ''' if '__grains__' not in self.pack: grains = opts.get('grains', {}) if isinstance(grains, ThreadLocalProxy): grains = ThreadLocalProxy.unproxy(grains) self.context_dict['grains'] = grains self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains') if '__pillar__' not in self.pack: pillar = opts.get('pillar', {}) if isinstance(pillar, ThreadLocalProxy): pillar = ThreadLocalProxy.unproxy(pillar) self.context_dict['pillar'] = pillar self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar') mod_opts = {} for key, val in list(opts.items()): if key == 'logger': continue mod_opts[key] = val return mod_opts def _iter_files(self, mod_name): ''' Iterate over all file_mapping files in order of closeness to mod_name ''' # do we have an exact match? if mod_name in self.file_mapping: yield mod_name # do we have a partial match? for k in self.file_mapping: if mod_name in k: yield k # anyone else? Bueller? for k in self.file_mapping: if mod_name not in k: yield k def _reload_submodules(self, mod): submodules = ( getattr(mod, sname) for sname in dir(mod) if isinstance(getattr(mod, sname), mod.__class__) ) # reload only custom "sub"modules for submodule in submodules: # it is a submodule if the name is in a namespace under mod if submodule.__name__.startswith(mod.__name__ + '.'): reload_module(submodule) self._reload_submodules(submodule) def _load_module(self, name): mod = None fpath, suffix = self.file_mapping[name][:2] self.loaded_files.add(name) fpath_dirname = os.path.dirname(fpath) try: sys.path.append(fpath_dirname) if suffix == '.pyx': mod = pyximport.load_module(name, fpath, tempfile.gettempdir()) elif suffix == '.o': top_mod = __import__(fpath, globals(), locals(), []) comps = fpath.split('.') if len(comps) < 2: mod = top_mod else: mod = top_mod for subname in comps[1:]: mod = getattr(mod, subname) elif suffix == '.zip': mod = zipimporter(fpath).load_module(name) else: desc = self.suffix_map[suffix] # if it is a directory, we don't open a file try: mod_namespace = '.'.join(( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name)) except TypeError: mod_namespace = '{0}.{1}.{2}.{3}'.format( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name) if suffix == '': if USE_IMPORTLIB: # pylint: disable=no-member # Package directory, look for __init__ loader_details = [ (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES), (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES), (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), ] file_finder = importlib.machinery.FileFinder( fpath_dirname, *loader_details ) spec = file_finder.find_spec(mod_namespace) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: mod = imp.load_module(mod_namespace, None, fpath, desc) # reload all submodules if necessary if not self.initial_load: self._reload_submodules(mod) else: if USE_IMPORTLIB: # pylint: disable=no-member loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath) spec = importlib.util.spec_from_file_location( mod_namespace, fpath, loader=loader ) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() #mod = importlib.util.module_from_spec(spec) #spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: with salt.utils.files.fopen(fpath, desc[1]) as fn_: mod = imp.load_module(mod_namespace, fn_, fpath, desc) except IOError: raise except ImportError as exc: if 'magic number' in six.text_type(exc): error_msg = 'Failed to import {0} {1}. Bad magic number. If migrating from Python2 to Python3, remove all .pyc files and try again.'.format(self.tag, name) log.warning(error_msg) self.missing_modules[name] = error_msg log.debug( 'Failed to import %s %s:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = exc return False except Exception as error: log.error( 'Failed to import %s %s, this is due most likely to a ' 'syntax error:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False except SystemExit as error: try: fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1] except Exception: pass else: tgt_fn = os.path.join('salt', 'utils', 'process.py') if fn_.endswith(tgt_fn) and '_handle_signals' in caller: # Race conditon, SIGTERM or SIGINT received while loader # was in process of loading a module. Call sys.exit to # ensure that the process is killed. sys.exit(salt.defaults.exitcodes.EX_OK) log.error( 'Failed to import %s %s as the module called exit()\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False finally: sys.path.remove(fpath_dirname) if hasattr(mod, '__opts__'): mod.__opts__.update(self.opts) else: mod.__opts__ = self.opts # pack whatever other globals we were asked to for p_name, p_value in six.iteritems(self.pack): _inject_into_mod(mod, p_name, p_value) module_name = mod.__name__.rsplit('.', 1)[-1] # Call a module's initialization method if it exists module_init = getattr(mod, '__init__', None) if inspect.isfunction(module_init): try: module_init(self.opts) except TypeError as e: log.error(e) except Exception: err_string = '__init__ failed' log.debug( 'Error loading %s.%s: %s', self.tag, module_name, err_string, exc_info=True ) self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False # if virtual modules are enabled, we need to look for the # __virtual__() function inside that module and run it. if self.virtual_enable: virtual_funcs_to_process = ['__virtual__'] + self.virtual_funcs for virtual_func in virtual_funcs_to_process: virtual_ret, module_name, virtual_err, virtual_aliases = \ self._process_virtual(mod, module_name, virtual_func) if virtual_err is not None: log.trace( 'Error loading %s.%s: %s', self.tag, module_name, virtual_err ) # if _process_virtual returned a non-True value then we are # supposed to not process this module if virtual_ret is not True and module_name not in self.missing_modules: # If a module has information about why it could not be loaded, record it self.missing_modules[module_name] = virtual_err self.missing_modules[name] = virtual_err return False else: virtual_aliases = () # If this is a proxy minion then MOST modules cannot work. Therefore, require that # any module that does work with salt-proxy-minion define __proxyenabled__ as a list # containing the names of the proxy types that the module supports. # # Render modules and state modules are OK though if 'proxy' in self.opts: if self.tag in ['grains', 'proxy']: if not hasattr(mod, '__proxyenabled__') or \ (self.opts['proxy']['proxytype'] not in mod.__proxyenabled__ and '*' not in mod.__proxyenabled__): err_string = 'not a proxy_minion enabled module' self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False if getattr(mod, '__load__', False) is not False: log.info( 'The functions from module \'%s\' are being loaded from the ' 'provided __load__ attribute', module_name ) # If we had another module by the same virtual name, we should put any # new functions under the existing dictionary. mod_names = [module_name] + list(virtual_aliases) mod_dict = dict(( (x, self.loaded_modules.get(x, self.mod_dict_class())) for x in mod_names )) for attr in getattr(mod, '__load__', dir(mod)): if attr.startswith('_') and attr != '__call__': # private functions are skipped, # except __call__ which is default entrance # for multi-function batch-like state syntax continue func = getattr(mod, attr) if not inspect.isfunction(func) and not isinstance(func, functools.partial): # Not a function!? Skip it!!! continue # Let's get the function name. # If the module has the __func_alias__ attribute, it must be a # dictionary mapping in the form of(key -> value): # <real-func-name> -> <desired-func-name> # # It default's of course to the found callable attribute name # if no alias is defined. funcname = getattr(mod, '__func_alias__', {}).get(attr, attr) for tgt_mod in mod_names: try: full_funcname = '.'.join((tgt_mod, funcname)) except TypeError: full_funcname = '{0}.{1}'.format(tgt_mod, funcname) # Save many references for lookups # Careful not to overwrite existing (higher priority) functions if full_funcname not in self._dict: self._dict[full_funcname] = func if funcname not in mod_dict[tgt_mod]: setattr(mod_dict[tgt_mod], funcname, func) mod_dict[tgt_mod][funcname] = func self._apply_outputter(func, mod) # enforce depends try: Depends.enforce_dependencies(self._dict, self.tag) except RuntimeError as exc: log.info( 'Depends.enforce_dependencies() failed for the following ' 'reason: %s', exc ) for tgt_mod in mod_names: self.loaded_modules[tgt_mod] = mod_dict[tgt_mod] return True def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise KeyError('The key \'{0}\' should contain a \'.\''.format(key)) mod_name, _ = key.split('.', 1) with self._lock: # It is possible that the key is in the dictionary after # acquiring the lock due to another thread loading it. if mod_name in self.missing_modules or key in self._dict: return True # if the modulename isn't in the whitelist, don't bother if self.whitelist and mod_name not in self.whitelist: log.error( 'Failed to load function %s because its module (%s) is ' 'not in the whitelist: %s', key, mod_name, self.whitelist ) raise KeyError(key) def _inner_load(mod_name): for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and key in self._dict: return True return False # try to load the module ret = None reloaded = False # re-scan up to once, IOErrors or a failed load cause re-scans of the # filesystem while True: try: ret = _inner_load(mod_name) if not reloaded and ret is not True: self._refresh_file_mapping() reloaded = True continue break except IOError: if not reloaded: self._refresh_file_mapping() reloaded = True continue return ret def _load_all(self): ''' Load all of them ''' with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True def reload_modules(self): with self._lock: self.loaded_files = set() self._load_all() def _apply_outputter(self, func, mod): ''' Apply the __outputter__ variable to the functions ''' if hasattr(mod, '__outputter__'): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__] def _process_virtual(self, mod, module_name, virtual_func='__virtual__'): ''' Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1] ''' # The __virtual__ function will return either a True or False value. # If it returns a True value it can also set a module level attribute # named __virtualname__ with the name that the module should be # referred to as. # # This allows us to have things like the pkg module working on all # platforms under the name 'pkg'. It also allows for modules like # augeas_cfg to be referred to as 'augeas', which would otherwise have # namespace collisions. And finally it allows modules to return False # if they are not intended to run on the given platform or are missing # dependencies. virtual_aliases = getattr(mod, '__virtual_aliases__', tuple()) try: error_reason = None if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__): try: start = time.time() virtual = getattr(mod, virtual_func)() if isinstance(virtual, tuple): error_reason = virtual[1] virtual = virtual[0] if self.opts.get('virtual_timer', False): end = time.time() - start msg = 'Virtual function took {0} seconds for {1}'.format( end, module_name) log.warning(msg) except Exception as exc: error_reason = ( 'Exception raised when processing __virtual__ function' ' for {0}. Module will not be loaded: {1}'.format( mod.__name__, exc)) log.error(error_reason, exc_info_on_loglevel=logging.DEBUG) virtual = None # Get the module's virtual name virtualname = getattr(mod, '__virtualname__', virtual) if not virtual: # if __virtual__() evaluates to False then the module # wasn't meant for this platform or it's not supposed to # load for some other reason. # Some modules might accidentally return None and are # improperly loaded if virtual is None: log.warning( '%s.__virtual__() is wrongly returning `None`. ' 'It should either return `True`, `False` or a new ' 'name. If you\'re the developer of the module ' '\'%s\', please fix this.', mod.__name__, module_name ) return (False, module_name, error_reason, virtual_aliases) # At this point, __virtual__ did not return a # boolean value, let's check for deprecated usage # or module renames if virtual is not True and module_name != virtual: # The module is renaming itself. Updating the module name # with the new name log.trace('Loaded %s as virtual %s', module_name, virtual) if virtualname != virtual: # The __virtualname__ attribute does not match what's # being returned by the __virtual__() function. This # should be considered an error. log.error( 'The module \'%s\' is showing some bad usage. Its ' '__virtualname__ attribute is set to \'%s\' yet the ' '__virtual__() function is returning \'%s\'. These ' 'values should match!', mod.__name__, virtualname, virtual ) module_name = virtualname # If the __virtual__ function returns True and __virtualname__ # is set then use it elif virtual is True and virtualname != module_name: if virtualname is not True: module_name = virtualname except KeyError: # Key errors come out of the virtual function when passing # in incomplete grains sets, these can be safely ignored # and logged to debug, still, it includes the traceback to # help debugging. log.debug('KeyError when loading %s', module_name, exc_info=True) except Exception: # If the module throws an exception during __virtual__() # then log the information and continue to the next. log.error( 'Failed to read the virtual function for %s: %s', self.tag, module_name, exc_info=True ) return (False, module_name, error_reason, virtual_aliases) return (True, module_name, None, virtual_aliases) def global_injector_decorator(inject_globals): ''' Decorator used by the LazyLoader to inject globals into a function at execute time. globals Dictionary with global variables to inject ''' def inner_decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): with salt.utils.context.func_globals_inject(f, **inject_globals): return f(*args, **kwargs) return wrapper return inner_decorator
saltstack/salt
salt/loader.py
wheels
python
def wheels(opts, whitelist=None, context=None): ''' Returns the wheels modules ''' if context is None: context = {} return LazyLoader( _module_dirs(opts, 'wheel'), opts, tag='wheel', whitelist=whitelist, pack={'__context__': context}, )
Returns the wheels modules
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L429-L441
null
# -*- coding: utf-8 -*- ''' The Salt loader is the core to Salt's plugin system, the loader scans directories for python loadable code and organizes the code into the plugin interfaces used by Salt. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import sys import time import logging import inspect import tempfile import threading import functools import threading import traceback import types from zipimport import zipimporter # Import salt libs import salt.config import salt.defaults.events import salt.defaults.exitcodes import salt.syspaths import salt.utils.args import salt.utils.context import salt.utils.data import salt.utils.dictupdate import salt.utils.event import salt.utils.files import salt.utils.lazy import salt.utils.odict import salt.utils.platform import salt.utils.versions import salt.utils.stringutils from salt.exceptions import LoaderError from salt.template import check_render_pipe_str from salt.utils.decorators import Depends from salt.utils.thread_local_proxy import ThreadLocalProxy # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import reload_module if sys.version_info[:2] >= (3, 5): import importlib.machinery # pylint: disable=no-name-in-module,import-error import importlib.util # pylint: disable=no-name-in-module,import-error USE_IMPORTLIB = True else: import imp USE_IMPORTLIB = False try: from collections.abc import MutableMapping except ImportError: from collections import MutableMapping try: import pkg_resources HAS_PKG_RESOURCES = True except ImportError: HAS_PKG_RESOURCES = False log = logging.getLogger(__name__) SALT_BASE_PATH = os.path.abspath(salt.syspaths.INSTALL_DIR) LOADED_BASE_NAME = 'salt.loaded' if USE_IMPORTLIB: # pylint: disable=no-member MODULE_KIND_SOURCE = 1 MODULE_KIND_COMPILED = 2 MODULE_KIND_EXTENSION = 3 MODULE_KIND_PKG_DIRECTORY = 5 SUFFIXES = [] for suffix in importlib.machinery.EXTENSION_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_EXTENSION)) for suffix in importlib.machinery.SOURCE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_SOURCE)) for suffix in importlib.machinery.BYTECODE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_COMPILED)) MODULE_KIND_MAP = { MODULE_KIND_SOURCE: importlib.machinery.SourceFileLoader, MODULE_KIND_COMPILED: importlib.machinery.SourcelessFileLoader, MODULE_KIND_EXTENSION: importlib.machinery.ExtensionFileLoader } # pylint: enable=no-member else: SUFFIXES = imp.get_suffixes() PY3_PRE_EXT = \ re.compile(r'\.cpython-{0}{1}(\.opt-[1-9])?'.format(*sys.version_info[:2])) # Because on the cloud drivers we do `from salt.cloud.libcloudfuncs import *` # which simplifies code readability, it adds some unsupported functions into # the driver's module scope. # We list un-supported functions here. These will be removed from the loaded. # TODO: remove the need for this cross-module code. Maybe use NotImplemented LIBCLOUD_FUNCS_NOT_SUPPORTED = ( 'parallels.avail_sizes', 'parallels.avail_locations', 'proxmox.avail_sizes', ) # Will be set to pyximport module at runtime if cython is enabled in config. pyximport = None def static_loader( opts, ext_type, tag, pack=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, filter_name=None, ): funcs = LazyLoader( _module_dirs( opts, ext_type, tag, int_type, ext_dirs, ext_type_dirs, base_path, ), opts, tag=tag, pack=pack, ) ret = {} funcs._load_all() if filter_name: funcs = FilterDictWrapper(funcs, filter_name) for key in funcs: ret[key] = funcs[key] return ret def _format_entrypoint_target(ep): ''' Makes a string describing the target of an EntryPoint object. Base strongly on EntryPoint.__str__(). ''' s = ep.module_name if ep.attrs: s += ':' + '.'.join(ep.attrs) return s def _module_dirs( opts, ext_type, tag=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, ): if tag is None: tag = ext_type sys_types = os.path.join(base_path or SALT_BASE_PATH, int_type or ext_type) ext_types = os.path.join(opts['extension_modules'], ext_type) ext_type_types = [] if ext_dirs: if ext_type_dirs is None: ext_type_dirs = '{0}_dirs'.format(tag) if ext_type_dirs in opts: ext_type_types.extend(opts[ext_type_dirs]) if HAS_PKG_RESOURCES and ext_type_dirs: for entry_point in pkg_resources.iter_entry_points('salt.loader', ext_type_dirs): try: loaded_entry_point = entry_point.load() for path in loaded_entry_point(): ext_type_types.append(path) except Exception as exc: log.error("Error getting module directories from %s: %s", _format_entrypoint_target(entry_point), exc) log.debug("Full backtrace for module directories error", exc_info=True) cli_module_dirs = [] # The dirs can be any module dir, or a in-tree _{ext_type} dir for _dir in opts.get('module_dirs', []): # Prepend to the list to match cli argument ordering maybe_dir = os.path.join(_dir, ext_type) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) continue maybe_dir = os.path.join(_dir, '_{0}'.format(ext_type)) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) return cli_module_dirs + ext_type_types + [ext_types, sys_types] def minion_mods( opts, context=None, utils=None, whitelist=None, initial_load=False, loaded_base_name=None, notify=False, static_modules=None, proxy=None): ''' Load execution modules Returns a dictionary of execution modules appropriate for the current system by evaluating the __virtual__() function in each module. :param dict opts: The Salt options dictionary :param dict context: A Salt context that should be made present inside generated modules in __context__ :param dict utils: Utility functions which should be made available to Salt modules in __utils__. See `utils_dirs` in salt.config for additional information about configuration. :param list whitelist: A list of modules which should be whitelisted. :param bool initial_load: Deprecated flag! Unused. :param str loaded_base_name: A string marker for the loaded base name. :param bool notify: Flag indicating that an event should be fired upon completion of module loading. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) __opts__['grains'] = __grains__ __utils__ = salt.loader.utils(__opts__) __salt__ = salt.loader.minion_mods(__opts__, utils=__utils__) __salt__['test.ping']() ''' # TODO Publish documentation for module whitelisting if not whitelist: whitelist = opts.get('whitelist_modules', None) ret = LazyLoader( _module_dirs(opts, 'modules', 'module'), opts, tag='module', pack={'__context__': context, '__utils__': utils, '__proxy__': proxy}, whitelist=whitelist, loaded_base_name=loaded_base_name, static_modules=static_modules, ) ret.pack['__salt__'] = ret # Load any provider overrides from the configuration file providers option # Note: Providers can be pkg, service, user or group - not to be confused # with cloud providers. providers = opts.get('providers', False) if providers and isinstance(providers, dict): for mod in providers: # sometimes providers opts is not to diverge modules but # for other configuration try: funcs = raw_mod(opts, providers[mod], ret) except TypeError: break else: if funcs: for func in funcs: f_key = '{0}{1}'.format(mod, func[func.rindex('.'):]) ret[f_key] = funcs[func] if notify: evt = salt.utils.event.get_event('minion', opts=opts, listen=False) evt.fire_event({'complete': True}, tag=salt.defaults.events.MINION_MOD_COMPLETE) return ret def raw_mod(opts, name, functions, mod='modules'): ''' Returns a single module loaded raw and bypassing the __virtual__ function .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') testmod = salt.loader.raw_mod(__opts__, 'test', None) testmod['test.ping']() ''' loader = LazyLoader( _module_dirs(opts, mod, 'module'), opts, tag='rawmodule', virtual_enable=False, pack={'__salt__': functions}, ) # if we don't have the module, return an empty dict if name not in loader.file_mapping: return {} loader._load_module(name) # load a single module (the one passed in) return dict(loader._dict) # return a copy of *just* the funcs for `name` def metaproxy(opts): ''' Return functions used in the meta proxy ''' return LazyLoader( _module_dirs(opts, 'metaproxy'), opts, tag='metaproxy' ) def matchers(opts): ''' Return the matcher services plugins ''' return LazyLoader( _module_dirs(opts, 'matchers'), opts, tag='matchers' ) def engines(opts, functions, runners, utils, proxy=None): ''' Return the master services plugins ''' pack = {'__salt__': functions, '__runners__': runners, '__proxy__': proxy, '__utils__': utils} return LazyLoader( _module_dirs(opts, 'engines'), opts, tag='engines', pack=pack, ) def proxy(opts, functions=None, returners=None, whitelist=None, utils=None): ''' Returns the proxy module for this salt-proxy-minion ''' ret = LazyLoader( _module_dirs(opts, 'proxy'), opts, tag='proxy', pack={'__salt__': functions, '__ret__': returners, '__utils__': utils}, ) ret.pack['__proxy__'] = ret return ret def returners(opts, functions, whitelist=None, context=None, proxy=None): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'returners', 'returner'), opts, tag='returner', whitelist=whitelist, pack={'__salt__': functions, '__context__': context, '__proxy__': proxy or {}}, ) def utils(opts, whitelist=None, context=None, proxy=proxy): ''' Returns the utility modules ''' return LazyLoader( _module_dirs(opts, 'utils', ext_type_dirs='utils_dirs'), opts, tag='utils', whitelist=whitelist, pack={'__context__': context, '__proxy__': proxy or {}}, ) def pillars(opts, functions, context=None): ''' Returns the pillars modules ''' ret = LazyLoader(_module_dirs(opts, 'pillar'), opts, tag='pillar', pack={'__salt__': functions, '__context__': context, '__utils__': utils(opts)}) ret.pack['__ext_pillar__'] = ret return FilterDictWrapper(ret, '.ext_pillar') def tops(opts): ''' Returns the tops modules ''' if 'master_tops' not in opts: return {} whitelist = list(opts['master_tops'].keys()) ret = LazyLoader( _module_dirs(opts, 'tops', 'top'), opts, tag='top', whitelist=whitelist, ) return FilterDictWrapper(ret, '.top') def outputters(opts): ''' Returns the outputters modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only outputters present in the keyspace ''' ret = LazyLoader( _module_dirs(opts, 'output', ext_type_dirs='outputter_dirs'), opts, tag='output', ) wrapped_ret = FilterDictWrapper(ret, '.output') # TODO: this name seems terrible... __salt__ should always be execution mods ret.pack['__salt__'] = wrapped_ret return wrapped_ret def serializers(opts): ''' Returns the serializers modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only serializers present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'serializers'), opts, tag='serializers', ) def eauth_tokens(opts): ''' Returns the tokens modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only token backends present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'tokens'), opts, tag='tokens', ) def auth(opts, whitelist=None): ''' Returns the auth modules :param dict opts: The Salt options dictionary :returns: LazyLoader ''' return LazyLoader( _module_dirs(opts, 'auth'), opts, tag='auth', whitelist=whitelist, pack={'__salt__': minion_mods(opts)}, ) def fileserver(opts, backends): ''' Returns the file server modules ''' return LazyLoader(_module_dirs(opts, 'fileserver'), opts, tag='fileserver', whitelist=backends, pack={'__utils__': utils(opts)}) def roster(opts, runner=None, utils=None, whitelist=None): ''' Returns the roster modules ''' return LazyLoader( _module_dirs(opts, 'roster'), opts, tag='roster', whitelist=whitelist, pack={ '__runner__': runner, '__utils__': utils, }, ) def thorium(opts, functions, runners): ''' Load the thorium runtime modules ''' pack = {'__salt__': functions, '__runner__': runners, '__context__': {}} ret = LazyLoader(_module_dirs(opts, 'thorium'), opts, tag='thorium', pack=pack) ret.pack['__thorium__'] = ret return ret def states(opts, functions, utils, serializers, whitelist=None, proxy=None, context=None): ''' Returns the state modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') statemods = salt.loader.states(__opts__, None, None) ''' if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'states'), opts, tag='states', pack={'__salt__': functions, '__proxy__': proxy or {}}, whitelist=whitelist, ) ret.pack['__states__'] = ret ret.pack['__utils__'] = utils ret.pack['__serializers__'] = serializers ret.pack['__context__'] = context return ret def beacons(opts, functions, context=None, proxy=None): ''' Load the beacon modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. ''' return LazyLoader( _module_dirs(opts, 'beacons'), opts, tag='beacons', pack={'__context__': context, '__salt__': functions, '__proxy__': proxy or {}}, virtual_funcs=[], ) def log_handlers(opts): ''' Returns the custom logging handler modules :param dict opts: The Salt options dictionary ''' ret = LazyLoader( _module_dirs( opts, 'log_handlers', int_type='handlers', base_path=os.path.join(SALT_BASE_PATH, 'log'), ), opts, tag='log_handlers', ) return FilterDictWrapper(ret, '.setup_handlers') def ssh_wrapper(opts, functions=None, context=None): ''' Returns the custom logging handler modules ''' return LazyLoader( _module_dirs( opts, 'wrapper', base_path=os.path.join(SALT_BASE_PATH, os.path.join('client', 'ssh')), ), opts, tag='wrapper', pack={ '__salt__': functions, '__grains__': opts.get('grains', {}), '__pillar__': opts.get('pillar', {}), '__context__': context, }, ) def render(opts, functions, states=None, proxy=None, context=None): ''' Returns the render modules ''' if context is None: context = {} pack = {'__salt__': functions, '__grains__': opts.get('grains', {}), '__context__': context} if states: pack['__states__'] = states pack['__proxy__'] = proxy or {} ret = LazyLoader( _module_dirs( opts, 'renderers', 'render', ext_type_dirs='render_dirs', ), opts, tag='render', pack=pack, ) rend = FilterDictWrapper(ret, '.render') if not check_render_pipe_str(opts['renderer'], rend, opts['renderer_blacklist'], opts['renderer_whitelist']): err = ('The renderer {0} is unavailable, this error is often because ' 'the needed software is unavailable'.format(opts['renderer'])) log.critical(err) raise LoaderError(err) return rend def grain_funcs(opts, proxy=None): ''' Returns the grain functions .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') grainfuncs = salt.loader.grain_funcs(__opts__) ''' ret = LazyLoader( _module_dirs( opts, 'grains', 'grain', ext_type_dirs='grains_dirs', ), opts, tag='grains', ) ret.pack['__utils__'] = utils(opts, proxy=proxy) return ret def _load_cached_grains(opts, cfn): ''' Returns the grains cached in cfn, or None if the cache is too old or is corrupted. ''' if not os.path.isfile(cfn): log.debug('Grains cache file does not exist.') return None grains_cache_age = int(time.time() - os.path.getmtime(cfn)) if grains_cache_age > opts.get('grains_cache_expiration', 300): log.debug( 'Grains cache last modified %s seconds ago and cache ' 'expiration is set to %s. Grains cache expired. ' 'Refreshing.', grains_cache_age, opts.get('grains_cache_expiration', 300) ) return None if opts.get('refresh_grains_cache', False): log.debug('refresh_grains_cache requested, Refreshing.') return None log.debug('Retrieving grains from cache') try: serial = salt.payload.Serial(opts) with salt.utils.files.fopen(cfn, 'rb') as fp_: cached_grains = salt.utils.data.decode(serial.load(fp_), preserve_tuples=True) if not cached_grains: log.debug('Cached grains are empty, cache might be corrupted. Refreshing.') return None return cached_grains except (IOError, OSError): return None def grains(opts, force_refresh=False, proxy=None): ''' Return the functions for the dynamic grains and the values for the static grains. Since grains are computed early in the startup process, grains functions do not have __salt__ or __proxy__ available. At proxy-minion startup, this function is called with the proxymodule LazyLoader object so grains functions can communicate with their controlled device. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) print __grains__['id'] ''' # Need to re-import salt.config, somehow it got lost when a minion is starting import salt.config # if we have no grains, lets try loading from disk (TODO: move to decorator?) cfn = os.path.join( opts['cachedir'], 'grains.cache.p' ) if not force_refresh and opts.get('grains_cache', False): cached_grains = _load_cached_grains(opts, cfn) if cached_grains: return cached_grains else: log.debug('Grains refresh requested. Refreshing grains.') if opts.get('skip_grains', False): return {} grains_deep_merge = opts.get('grains_deep_merge', False) is True if 'conf_file' in opts: pre_opts = {} pre_opts.update(salt.config.load_config( opts['conf_file'], 'SALT_MINION_CONFIG', salt.config.DEFAULT_MINION_OPTS['conf_file'] )) default_include = pre_opts.get( 'default_include', opts['default_include'] ) include = pre_opts.get('include', []) pre_opts.update(salt.config.include_config( default_include, opts['conf_file'], verbose=False )) pre_opts.update(salt.config.include_config( include, opts['conf_file'], verbose=True )) if 'grains' in pre_opts: opts['grains'] = pre_opts['grains'] else: opts['grains'] = {} else: opts['grains'] = {} grains_data = {} blist = opts.get('grains_blacklist', []) funcs = grain_funcs(opts, proxy=proxy) if force_refresh: # if we refresh, lets reload grain modules funcs.clear() # Run core grains for key in funcs: if not key.startswith('core.'): continue log.trace('Loading %s grain', key) ret = funcs[key]() if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) # Run the rest of the grains for key in funcs: if key.startswith('core.') or key == '_errors': continue try: # Grains are loaded too early to take advantage of the injected # __proxy__ variable. Pass an instance of that LazyLoader # here instead to grains functions if the grains functions take # one parameter. Then the grains can have access to the # proxymodule for retrieving information from the connected # device. log.trace('Loading %s grain', key) parameters = salt.utils.args.get_function_argspec(funcs[key]).args kwargs = {} if 'proxy' in parameters: kwargs['proxy'] = proxy if 'grains' in parameters: kwargs['grains'] = grains_data ret = funcs[key](**kwargs) except Exception: if salt.utils.platform.is_proxy(): log.info('The following CRITICAL message may not be an error; the proxy may not be completely established yet.') log.critical( 'Failed to load grains defined in grain file %s in ' 'function %s, error:\n', key, funcs[key], exc_info=True ) continue if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) if opts.get('proxy_merge_grains_in_module', True) and proxy: try: proxytype = proxy.opts['proxy']['proxytype'] if proxytype + '.grains' in proxy: if proxytype + '.initialized' in proxy and proxy[proxytype + '.initialized'](): try: proxytype = proxy.opts['proxy']['proxytype'] ret = proxy[proxytype + '.grains']() if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) except Exception: log.critical('Failed to run proxy\'s grains function!', exc_info=True ) except KeyError: pass grains_data.update(opts['grains']) # Write cache if enabled if opts.get('grains_cache', False): with salt.utils.files.set_umask(0o077): try: if salt.utils.platform.is_windows(): # Late import import salt.modules.cmdmod # Make sure cache file isn't read-only salt.modules.cmdmod._run_quiet('attrib -R "{0}"'.format(cfn)) with salt.utils.files.fopen(cfn, 'w+b') as fp_: try: serial = salt.payload.Serial(opts) serial.dump(grains_data, fp_) except TypeError as e: log.error('Failed to serialize grains cache: %s', e) raise # re-throw for cleanup except Exception as e: log.error('Unable to write to grains cache file %s: %s', cfn, e) # Based on the original exception, the file may or may not have been # created. If it was, we will remove it now, as the exception means # the serialized data is not to be trusted, no matter what the # exception is. if os.path.isfile(cfn): os.unlink(cfn) if grains_deep_merge: salt.utils.dictupdate.update(grains_data, opts['grains']) else: grains_data.update(opts['grains']) return salt.utils.data.decode(grains_data, preserve_tuples=True) # TODO: get rid of? Does anyone use this? You should use raw() instead def call(fun, **kwargs): ''' Directly call a function inside a loader directory ''' args = kwargs.get('args', []) dirs = kwargs.get('dirs', []) funcs = LazyLoader( [os.path.join(SALT_BASE_PATH, 'modules')] + dirs, None, tag='modules', virtual_enable=False, ) return funcs[fun](*args) def runner(opts, utils=None, context=None, whitelist=None): ''' Directly call a function inside a loader directory ''' if utils is None: utils = {} if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'runners', 'runner', ext_type_dirs='runner_dirs'), opts, tag='runners', pack={'__utils__': utils, '__context__': context}, whitelist=whitelist, ) # TODO: change from __salt__ to something else, we overload __salt__ too much ret.pack['__salt__'] = ret return ret def queues(opts): ''' Directly call a function inside a loader directory ''' return LazyLoader( _module_dirs(opts, 'queues', 'queue', ext_type_dirs='queue_dirs'), opts, tag='queues', ) def sdb(opts, functions=None, whitelist=None, utils=None): ''' Make a very small database call ''' if utils is None: utils = {} return LazyLoader( _module_dirs(opts, 'sdb'), opts, tag='sdb', pack={ '__sdb__': functions, '__opts__': opts, '__utils__': utils, '__salt__': minion_mods(opts, utils), }, whitelist=whitelist, ) def pkgdb(opts): ''' Return modules for SPM's package database .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgdb', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgdb' ) def pkgfiles(opts): ''' Return modules for SPM's file handling .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgfiles', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgfiles' ) def clouds(opts): ''' Return the cloud functions ''' # Let's bring __active_provider_name__, defaulting to None, to all cloud # drivers. This will get temporarily updated/overridden with a context # manager when needed. functions = LazyLoader( _module_dirs(opts, 'clouds', 'cloud', base_path=os.path.join(SALT_BASE_PATH, 'cloud'), int_type='clouds'), opts, tag='clouds', pack={'__utils__': salt.loader.utils(opts), '__active_provider_name__': None}, ) for funcname in LIBCLOUD_FUNCS_NOT_SUPPORTED: log.trace( '\'%s\' has been marked as not supported. Removing from the ' 'list of supported cloud functions', funcname ) functions.pop(funcname, None) return functions def netapi(opts): ''' Return the network api functions ''' return LazyLoader( _module_dirs(opts, 'netapi'), opts, tag='netapi', ) def executors(opts, functions=None, context=None, proxy=None): ''' Returns the executor modules ''' executors = LazyLoader( _module_dirs(opts, 'executors', 'executor'), opts, tag='executor', pack={'__salt__': functions, '__context__': context or {}, '__proxy__': proxy or {}}, ) executors.pack['__executors__'] = executors return executors def cache(opts, serial): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'cache', 'cache'), opts, tag='cache', pack={'__opts__': opts, '__context__': {'serial': serial}}, ) def _generate_module(name): if name in sys.modules: return code = "'''Salt loaded {0} parent module'''".format(name.split('.')[-1]) # ModuleType can't accept a unicode type on PY2 module = types.ModuleType(str(name)) # future lint: disable=blacklisted-function exec(code, module.__dict__) sys.modules[name] = module def _mod_type(module_path): if module_path.startswith(SALT_BASE_PATH): return 'int' return 'ext' def _inject_into_mod(mod, name, value, force_lock=False): ''' Inject a variable into a module. This is used to inject "globals" like ``__salt__``, ``__pillar``, or ``grains``. Instead of injecting the value directly, a ``ThreadLocalProxy`` is created. If such a proxy is already present under the specified name, it is updated with the new value. This update only affects the current thread, so that the same name can refer to different values depending on the thread of execution. This is important for data that is not truly global. For example, pillar data might be dynamically overriden through function parameters and thus the actual values available in pillar might depend on the thread that is calling a module. mod: module object into which the value is going to be injected. name: name of the variable that is injected into the module. value: value that is injected into the variable. The value is not injected directly, but instead set as the new reference of the proxy that has been created for the variable. force_lock: whether the lock should be acquired before checking whether a proxy object for the specified name has already been injected into the module. If ``False`` (the default), this function checks for the module's variable without acquiring the lock and only acquires the lock if a new proxy has to be created and injected. ''' old_value = getattr(mod, name, None) # We use a double-checked locking scheme in order to avoid taking the lock # when a proxy object has already been injected. # In most programming languages, double-checked locking is considered # unsafe when used without explicit memory barriers because one might read # an uninitialized value. In CPython it is safe due to the global # interpreter lock (GIL). In Python implementations that do not have the # GIL, it could be unsafe, but at least Jython also guarantees that (for # Python objects) memory is not corrupted when writing and reading without # explicit synchronization # (http://www.jython.org/jythonbook/en/1.0/Concurrency.html). # Please note that in order to make this code safe in a runtime environment # that does not make this guarantees, it is not sufficient. The # ThreadLocalProxy must also be created with fallback_to_shared set to # False or a lock must be added to the ThreadLocalProxy. if force_lock: with _inject_into_mod.lock: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: setattr(mod, name, ThreadLocalProxy(value, True)) else: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: _inject_into_mod(mod, name, value, True) # Lock used when injecting globals. This is needed to avoid a race condition # when two threads try to load the same module concurrently. This must be # outside the loader because there might be more than one loader for the same # namespace. _inject_into_mod.lock = threading.RLock() # TODO: move somewhere else? class FilterDictWrapper(MutableMapping): ''' Create a dict which wraps another dict with a specific key suffix on get This is to replace "filter_load" ''' def __init__(self, d, suffix): self._dict = d self.suffix = suffix def __setitem__(self, key, val): self._dict[key] = val def __delitem__(self, key): del self._dict[key] def __getitem__(self, key): return self._dict[key + self.suffix] def __len__(self): return len(self._dict) def __iter__(self): for key in self._dict: if key.endswith(self.suffix): yield key.replace(self.suffix, '') class LazyLoader(salt.utils.lazy.LazyDict): ''' A pseduo-dictionary which has a set of keys which are the name of the module and function, delimited by a dot. When the value of the key is accessed, the function is then loaded from disk and into memory. .. note:: Iterating over keys will cause all modules to be loaded. :param list module_dirs: A list of directories on disk to search for modules :param dict opts: The salt options dictionary. :param str tag: The tag for the type of module to load :param func mod_type_check: A function which can be used to verify files :param dict pack: A dictionary of function to be packed into modules as they are loaded :param list whitelist: A list of modules to whitelist :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules. :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality. If not true, the module will not load. :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values are function references themselves which are loaded on-demand. # TODO: - move modules_max_memory into here - singletons (per tag) ''' mod_dict_class = salt.utils.odict.OrderedDict def __init__(self, module_dirs, opts=None, tag='module', loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, proxy=None, virtual_funcs=None, ): # pylint: disable=W0231 ''' In pack, if any of the values are None they will be replaced with an empty context-specific dict ''' self.inject_globals = {} self.pack = {} if pack is None else pack if opts is None: opts = {} threadsafety = not opts.get('multiprocessing') self.context_dict = salt.utils.context.ContextDict(threadsafe=threadsafety) self.opts = self.__prep_mod_opts(opts) self.module_dirs = module_dirs self.tag = tag self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME self.mod_type_check = mod_type_check or _mod_type if '__context__' not in self.pack: self.pack['__context__'] = None for k, v in six.iteritems(self.pack): if v is None: # if the value of a pack is None, lets make an empty dict value = self.context_dict.get(k, {}) if isinstance(value, ThreadLocalProxy): value = ThreadLocalProxy.unproxy(value) self.context_dict[k] = value self.pack[k] = salt.utils.context.NamespacedDictWrapper(self.context_dict, k) self.whitelist = whitelist self.virtual_enable = virtual_enable self.initial_load = True # names of modules that we don't have (errors, __virtual__, etc.) self.missing_modules = {} # mapping of name -> error self.loaded_modules = {} # mapping of module_name -> dict_of_functions self.loaded_files = set() # TODO: just remove them from file_mapping? self.static_modules = static_modules if static_modules else [] if virtual_funcs is None: virtual_funcs = [] self.virtual_funcs = virtual_funcs self.disabled = set( self.opts.get( 'disable_{0}{1}'.format( self.tag, '' if self.tag[-1] == 's' else 's' ), [] ) ) # A map of suffix to description for imp self.suffix_map = {} # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [''] for (suffix, mode, kind) in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) self._lock = threading.RLock() self._refresh_file_mapping() super(LazyLoader, self).__init__() # late init the lazy loader # create all of the import namespaces _generate_module('{0}.int'.format(self.loaded_base_name)) _generate_module('{0}.int.{1}'.format(self.loaded_base_name, tag)) _generate_module('{0}.ext'.format(self.loaded_base_name)) _generate_module('{0}.ext.{1}'.format(self.loaded_base_name, tag)) def __getitem__(self, item): ''' Override the __getitem__ in order to decorate the returned function if we need to last-minute inject globals ''' func = super(LazyLoader, self).__getitem__(item) if self.inject_globals: return global_injector_decorator(self.inject_globals)(func) else: return func def __getattr__(self, mod_name): ''' Allow for "direct" attribute access-- this allows jinja templates to access things like `salt.test.ping()` ''' if mod_name in ('__getstate__', '__setstate__'): return object.__getattribute__(self, mod_name) # if we have an attribute named that, lets return it. try: return object.__getattr__(self, mod_name) # pylint: disable=no-member except AttributeError: pass # otherwise we assume its jinja template access if mod_name not in self.loaded_modules and not self.loaded: for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and mod_name in self.loaded_modules: break if mod_name in self.loaded_modules: return self.loaded_modules[mod_name] else: raise AttributeError(mod_name) def missing_fun_string(self, function_name): ''' Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ''' mod_name = function_name.split('.')[0] if mod_name in self.loaded_modules: return '\'{0}\' is not available.'.format(function_name) else: try: reason = self.missing_modules[mod_name] except KeyError: return '\'{0}\' is not available.'.format(function_name) else: if reason is not None: return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason) else: return '\'{0}\' __virtual__ returned False'.format(mod_name) def _refresh_file_mapping(self): ''' refresh the mapping of the FS on disk ''' # map of suffix to description for imp if self.opts.get('cython_enable', True) is True: try: global pyximport pyximport = __import__('pyximport') # pylint: disable=import-error pyximport.install() # add to suffix_map so file_mapping will pick it up self.suffix_map['.pyx'] = tuple() except ImportError: log.info('Cython is enabled in the options but not present ' 'in the system path. Skipping Cython modules.') # Allow for zipimport of modules if self.opts.get('enable_zip_modules', True) is True: self.suffix_map['.zip'] = tuple() # allow for module dirs if USE_IMPORTLIB: self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY) else: self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY) # create mapping of filename (without suffix) to (path, suffix) # The files are added in order of priority, so order *must* be retained. self.file_mapping = salt.utils.odict.OrderedDict() opt_match = [] def _replace_pre_ext(obj): ''' Hack so we can get the optimization level that we replaced (if any) out of the re.sub call below. We use a list here because it is a persistent data structure that we will be able to access after re.sub is called. ''' opt_match.append(obj) return '' for mod_dir in self.module_dirs: try: # Make sure we have a sorted listdir in order to have # expectable override results files = sorted( x for x in os.listdir(mod_dir) if x != '__pycache__' ) except OSError: continue # Next mod_dir if six.PY3: try: pycache_files = [ os.path.join('__pycache__', x) for x in sorted(os.listdir(os.path.join(mod_dir, '__pycache__'))) ] except OSError: pass else: files.extend(pycache_files) for filename in files: try: dirname, basename = os.path.split(filename) if basename.startswith('_'): # skip private modules # log messages omitted for obviousness continue # Next filename f_noext, ext = os.path.splitext(basename) if six.PY3: f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext) try: opt_level = int( opt_match.pop().group(1).rsplit('-', 1)[-1] ) except (AttributeError, IndexError, ValueError): # No regex match or no optimization level matched opt_level = 0 try: opt_index = self.opts['optimization_order'].index(opt_level) except KeyError: log.trace( 'Disallowed optimization level %d for module ' 'name \'%s\', skipping. Add %d to the ' '\'optimization_order\' config option if you ' 'do not want to ignore this optimization ' 'level.', opt_level, f_noext, opt_level ) continue else: # Optimization level not reflected in filename on PY2 opt_index = 0 # make sure it is a suffix we support if ext not in self.suffix_map: continue # Next filename if f_noext in self.disabled: log.trace( 'Skipping %s, it is disabled by configuration', filename ) continue # Next filename fpath = os.path.join(mod_dir, filename) # if its a directory, lets allow us to load that if ext == '': # is there something __init__? subfiles = os.listdir(fpath) for suffix in self.suffix_order: if '' == suffix: continue # Next suffix (__init__ must have a suffix) init_file = '__init__{0}'.format(suffix) if init_file in subfiles: break else: continue # Next filename try: curr_ext = self.file_mapping[f_noext][1] curr_opt_index = self.file_mapping[f_noext][2] except KeyError: pass else: if '' in (curr_ext, ext) and curr_ext != ext: log.error( 'Module/package collision: \'%s\' and \'%s\'', fpath, self.file_mapping[f_noext][0] ) if six.PY3 and ext == '.pyc' and curr_ext == '.pyc': # Check the optimization level if opt_index >= curr_opt_index: # Module name match, but a higher-priority # optimization level was already matched, skipping. continue elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext): # Match found but a higher-priorty match already # exists, so skip this. continue if six.PY3 and not dirname and ext == '.pyc': # On Python 3, we should only load .pyc files from the # __pycache__ subdirectory (i.e. when dirname is not an # empty string). continue # Made it this far - add it self.file_mapping[f_noext] = (fpath, ext, opt_index) except OSError: continue for smod in self.static_modules: f_noext = smod.split('.')[-1] self.file_mapping[f_noext] = (smod, '.o', 0) def clear(self): ''' Clear the dict ''' with self._lock: super(LazyLoader, self).clear() # clear the lazy loader self.loaded_files = set() self.missing_modules = {} self.loaded_modules = {} # if we have been loaded before, lets clear the file mapping since # we obviously want a re-do if hasattr(self, 'opts'): self._refresh_file_mapping() self.initial_load = False def __prep_mod_opts(self, opts): ''' Strip out of the opts any logger instance ''' if '__grains__' not in self.pack: grains = opts.get('grains', {}) if isinstance(grains, ThreadLocalProxy): grains = ThreadLocalProxy.unproxy(grains) self.context_dict['grains'] = grains self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains') if '__pillar__' not in self.pack: pillar = opts.get('pillar', {}) if isinstance(pillar, ThreadLocalProxy): pillar = ThreadLocalProxy.unproxy(pillar) self.context_dict['pillar'] = pillar self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar') mod_opts = {} for key, val in list(opts.items()): if key == 'logger': continue mod_opts[key] = val return mod_opts def _iter_files(self, mod_name): ''' Iterate over all file_mapping files in order of closeness to mod_name ''' # do we have an exact match? if mod_name in self.file_mapping: yield mod_name # do we have a partial match? for k in self.file_mapping: if mod_name in k: yield k # anyone else? Bueller? for k in self.file_mapping: if mod_name not in k: yield k def _reload_submodules(self, mod): submodules = ( getattr(mod, sname) for sname in dir(mod) if isinstance(getattr(mod, sname), mod.__class__) ) # reload only custom "sub"modules for submodule in submodules: # it is a submodule if the name is in a namespace under mod if submodule.__name__.startswith(mod.__name__ + '.'): reload_module(submodule) self._reload_submodules(submodule) def _load_module(self, name): mod = None fpath, suffix = self.file_mapping[name][:2] self.loaded_files.add(name) fpath_dirname = os.path.dirname(fpath) try: sys.path.append(fpath_dirname) if suffix == '.pyx': mod = pyximport.load_module(name, fpath, tempfile.gettempdir()) elif suffix == '.o': top_mod = __import__(fpath, globals(), locals(), []) comps = fpath.split('.') if len(comps) < 2: mod = top_mod else: mod = top_mod for subname in comps[1:]: mod = getattr(mod, subname) elif suffix == '.zip': mod = zipimporter(fpath).load_module(name) else: desc = self.suffix_map[suffix] # if it is a directory, we don't open a file try: mod_namespace = '.'.join(( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name)) except TypeError: mod_namespace = '{0}.{1}.{2}.{3}'.format( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name) if suffix == '': if USE_IMPORTLIB: # pylint: disable=no-member # Package directory, look for __init__ loader_details = [ (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES), (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES), (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), ] file_finder = importlib.machinery.FileFinder( fpath_dirname, *loader_details ) spec = file_finder.find_spec(mod_namespace) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: mod = imp.load_module(mod_namespace, None, fpath, desc) # reload all submodules if necessary if not self.initial_load: self._reload_submodules(mod) else: if USE_IMPORTLIB: # pylint: disable=no-member loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath) spec = importlib.util.spec_from_file_location( mod_namespace, fpath, loader=loader ) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() #mod = importlib.util.module_from_spec(spec) #spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: with salt.utils.files.fopen(fpath, desc[1]) as fn_: mod = imp.load_module(mod_namespace, fn_, fpath, desc) except IOError: raise except ImportError as exc: if 'magic number' in six.text_type(exc): error_msg = 'Failed to import {0} {1}. Bad magic number. If migrating from Python2 to Python3, remove all .pyc files and try again.'.format(self.tag, name) log.warning(error_msg) self.missing_modules[name] = error_msg log.debug( 'Failed to import %s %s:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = exc return False except Exception as error: log.error( 'Failed to import %s %s, this is due most likely to a ' 'syntax error:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False except SystemExit as error: try: fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1] except Exception: pass else: tgt_fn = os.path.join('salt', 'utils', 'process.py') if fn_.endswith(tgt_fn) and '_handle_signals' in caller: # Race conditon, SIGTERM or SIGINT received while loader # was in process of loading a module. Call sys.exit to # ensure that the process is killed. sys.exit(salt.defaults.exitcodes.EX_OK) log.error( 'Failed to import %s %s as the module called exit()\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False finally: sys.path.remove(fpath_dirname) if hasattr(mod, '__opts__'): mod.__opts__.update(self.opts) else: mod.__opts__ = self.opts # pack whatever other globals we were asked to for p_name, p_value in six.iteritems(self.pack): _inject_into_mod(mod, p_name, p_value) module_name = mod.__name__.rsplit('.', 1)[-1] # Call a module's initialization method if it exists module_init = getattr(mod, '__init__', None) if inspect.isfunction(module_init): try: module_init(self.opts) except TypeError as e: log.error(e) except Exception: err_string = '__init__ failed' log.debug( 'Error loading %s.%s: %s', self.tag, module_name, err_string, exc_info=True ) self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False # if virtual modules are enabled, we need to look for the # __virtual__() function inside that module and run it. if self.virtual_enable: virtual_funcs_to_process = ['__virtual__'] + self.virtual_funcs for virtual_func in virtual_funcs_to_process: virtual_ret, module_name, virtual_err, virtual_aliases = \ self._process_virtual(mod, module_name, virtual_func) if virtual_err is not None: log.trace( 'Error loading %s.%s: %s', self.tag, module_name, virtual_err ) # if _process_virtual returned a non-True value then we are # supposed to not process this module if virtual_ret is not True and module_name not in self.missing_modules: # If a module has information about why it could not be loaded, record it self.missing_modules[module_name] = virtual_err self.missing_modules[name] = virtual_err return False else: virtual_aliases = () # If this is a proxy minion then MOST modules cannot work. Therefore, require that # any module that does work with salt-proxy-minion define __proxyenabled__ as a list # containing the names of the proxy types that the module supports. # # Render modules and state modules are OK though if 'proxy' in self.opts: if self.tag in ['grains', 'proxy']: if not hasattr(mod, '__proxyenabled__') or \ (self.opts['proxy']['proxytype'] not in mod.__proxyenabled__ and '*' not in mod.__proxyenabled__): err_string = 'not a proxy_minion enabled module' self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False if getattr(mod, '__load__', False) is not False: log.info( 'The functions from module \'%s\' are being loaded from the ' 'provided __load__ attribute', module_name ) # If we had another module by the same virtual name, we should put any # new functions under the existing dictionary. mod_names = [module_name] + list(virtual_aliases) mod_dict = dict(( (x, self.loaded_modules.get(x, self.mod_dict_class())) for x in mod_names )) for attr in getattr(mod, '__load__', dir(mod)): if attr.startswith('_') and attr != '__call__': # private functions are skipped, # except __call__ which is default entrance # for multi-function batch-like state syntax continue func = getattr(mod, attr) if not inspect.isfunction(func) and not isinstance(func, functools.partial): # Not a function!? Skip it!!! continue # Let's get the function name. # If the module has the __func_alias__ attribute, it must be a # dictionary mapping in the form of(key -> value): # <real-func-name> -> <desired-func-name> # # It default's of course to the found callable attribute name # if no alias is defined. funcname = getattr(mod, '__func_alias__', {}).get(attr, attr) for tgt_mod in mod_names: try: full_funcname = '.'.join((tgt_mod, funcname)) except TypeError: full_funcname = '{0}.{1}'.format(tgt_mod, funcname) # Save many references for lookups # Careful not to overwrite existing (higher priority) functions if full_funcname not in self._dict: self._dict[full_funcname] = func if funcname not in mod_dict[tgt_mod]: setattr(mod_dict[tgt_mod], funcname, func) mod_dict[tgt_mod][funcname] = func self._apply_outputter(func, mod) # enforce depends try: Depends.enforce_dependencies(self._dict, self.tag) except RuntimeError as exc: log.info( 'Depends.enforce_dependencies() failed for the following ' 'reason: %s', exc ) for tgt_mod in mod_names: self.loaded_modules[tgt_mod] = mod_dict[tgt_mod] return True def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise KeyError('The key \'{0}\' should contain a \'.\''.format(key)) mod_name, _ = key.split('.', 1) with self._lock: # It is possible that the key is in the dictionary after # acquiring the lock due to another thread loading it. if mod_name in self.missing_modules or key in self._dict: return True # if the modulename isn't in the whitelist, don't bother if self.whitelist and mod_name not in self.whitelist: log.error( 'Failed to load function %s because its module (%s) is ' 'not in the whitelist: %s', key, mod_name, self.whitelist ) raise KeyError(key) def _inner_load(mod_name): for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and key in self._dict: return True return False # try to load the module ret = None reloaded = False # re-scan up to once, IOErrors or a failed load cause re-scans of the # filesystem while True: try: ret = _inner_load(mod_name) if not reloaded and ret is not True: self._refresh_file_mapping() reloaded = True continue break except IOError: if not reloaded: self._refresh_file_mapping() reloaded = True continue return ret def _load_all(self): ''' Load all of them ''' with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True def reload_modules(self): with self._lock: self.loaded_files = set() self._load_all() def _apply_outputter(self, func, mod): ''' Apply the __outputter__ variable to the functions ''' if hasattr(mod, '__outputter__'): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__] def _process_virtual(self, mod, module_name, virtual_func='__virtual__'): ''' Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1] ''' # The __virtual__ function will return either a True or False value. # If it returns a True value it can also set a module level attribute # named __virtualname__ with the name that the module should be # referred to as. # # This allows us to have things like the pkg module working on all # platforms under the name 'pkg'. It also allows for modules like # augeas_cfg to be referred to as 'augeas', which would otherwise have # namespace collisions. And finally it allows modules to return False # if they are not intended to run on the given platform or are missing # dependencies. virtual_aliases = getattr(mod, '__virtual_aliases__', tuple()) try: error_reason = None if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__): try: start = time.time() virtual = getattr(mod, virtual_func)() if isinstance(virtual, tuple): error_reason = virtual[1] virtual = virtual[0] if self.opts.get('virtual_timer', False): end = time.time() - start msg = 'Virtual function took {0} seconds for {1}'.format( end, module_name) log.warning(msg) except Exception as exc: error_reason = ( 'Exception raised when processing __virtual__ function' ' for {0}. Module will not be loaded: {1}'.format( mod.__name__, exc)) log.error(error_reason, exc_info_on_loglevel=logging.DEBUG) virtual = None # Get the module's virtual name virtualname = getattr(mod, '__virtualname__', virtual) if not virtual: # if __virtual__() evaluates to False then the module # wasn't meant for this platform or it's not supposed to # load for some other reason. # Some modules might accidentally return None and are # improperly loaded if virtual is None: log.warning( '%s.__virtual__() is wrongly returning `None`. ' 'It should either return `True`, `False` or a new ' 'name. If you\'re the developer of the module ' '\'%s\', please fix this.', mod.__name__, module_name ) return (False, module_name, error_reason, virtual_aliases) # At this point, __virtual__ did not return a # boolean value, let's check for deprecated usage # or module renames if virtual is not True and module_name != virtual: # The module is renaming itself. Updating the module name # with the new name log.trace('Loaded %s as virtual %s', module_name, virtual) if virtualname != virtual: # The __virtualname__ attribute does not match what's # being returned by the __virtual__() function. This # should be considered an error. log.error( 'The module \'%s\' is showing some bad usage. Its ' '__virtualname__ attribute is set to \'%s\' yet the ' '__virtual__() function is returning \'%s\'. These ' 'values should match!', mod.__name__, virtualname, virtual ) module_name = virtualname # If the __virtual__ function returns True and __virtualname__ # is set then use it elif virtual is True and virtualname != module_name: if virtualname is not True: module_name = virtualname except KeyError: # Key errors come out of the virtual function when passing # in incomplete grains sets, these can be safely ignored # and logged to debug, still, it includes the traceback to # help debugging. log.debug('KeyError when loading %s', module_name, exc_info=True) except Exception: # If the module throws an exception during __virtual__() # then log the information and continue to the next. log.error( 'Failed to read the virtual function for %s: %s', self.tag, module_name, exc_info=True ) return (False, module_name, error_reason, virtual_aliases) return (True, module_name, None, virtual_aliases) def global_injector_decorator(inject_globals): ''' Decorator used by the LazyLoader to inject globals into a function at execute time. globals Dictionary with global variables to inject ''' def inner_decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): with salt.utils.context.func_globals_inject(f, **inject_globals): return f(*args, **kwargs) return wrapper return inner_decorator
saltstack/salt
salt/loader.py
outputters
python
def outputters(opts): ''' Returns the outputters modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only outputters present in the keyspace ''' ret = LazyLoader( _module_dirs(opts, 'output', ext_type_dirs='outputter_dirs'), opts, tag='output', ) wrapped_ret = FilterDictWrapper(ret, '.output') # TODO: this name seems terrible... __salt__ should always be execution mods ret.pack['__salt__'] = wrapped_ret return wrapped_ret
Returns the outputters modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only outputters present in the keyspace
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L444-L459
null
# -*- coding: utf-8 -*- ''' The Salt loader is the core to Salt's plugin system, the loader scans directories for python loadable code and organizes the code into the plugin interfaces used by Salt. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import sys import time import logging import inspect import tempfile import threading import functools import threading import traceback import types from zipimport import zipimporter # Import salt libs import salt.config import salt.defaults.events import salt.defaults.exitcodes import salt.syspaths import salt.utils.args import salt.utils.context import salt.utils.data import salt.utils.dictupdate import salt.utils.event import salt.utils.files import salt.utils.lazy import salt.utils.odict import salt.utils.platform import salt.utils.versions import salt.utils.stringutils from salt.exceptions import LoaderError from salt.template import check_render_pipe_str from salt.utils.decorators import Depends from salt.utils.thread_local_proxy import ThreadLocalProxy # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import reload_module if sys.version_info[:2] >= (3, 5): import importlib.machinery # pylint: disable=no-name-in-module,import-error import importlib.util # pylint: disable=no-name-in-module,import-error USE_IMPORTLIB = True else: import imp USE_IMPORTLIB = False try: from collections.abc import MutableMapping except ImportError: from collections import MutableMapping try: import pkg_resources HAS_PKG_RESOURCES = True except ImportError: HAS_PKG_RESOURCES = False log = logging.getLogger(__name__) SALT_BASE_PATH = os.path.abspath(salt.syspaths.INSTALL_DIR) LOADED_BASE_NAME = 'salt.loaded' if USE_IMPORTLIB: # pylint: disable=no-member MODULE_KIND_SOURCE = 1 MODULE_KIND_COMPILED = 2 MODULE_KIND_EXTENSION = 3 MODULE_KIND_PKG_DIRECTORY = 5 SUFFIXES = [] for suffix in importlib.machinery.EXTENSION_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_EXTENSION)) for suffix in importlib.machinery.SOURCE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_SOURCE)) for suffix in importlib.machinery.BYTECODE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_COMPILED)) MODULE_KIND_MAP = { MODULE_KIND_SOURCE: importlib.machinery.SourceFileLoader, MODULE_KIND_COMPILED: importlib.machinery.SourcelessFileLoader, MODULE_KIND_EXTENSION: importlib.machinery.ExtensionFileLoader } # pylint: enable=no-member else: SUFFIXES = imp.get_suffixes() PY3_PRE_EXT = \ re.compile(r'\.cpython-{0}{1}(\.opt-[1-9])?'.format(*sys.version_info[:2])) # Because on the cloud drivers we do `from salt.cloud.libcloudfuncs import *` # which simplifies code readability, it adds some unsupported functions into # the driver's module scope. # We list un-supported functions here. These will be removed from the loaded. # TODO: remove the need for this cross-module code. Maybe use NotImplemented LIBCLOUD_FUNCS_NOT_SUPPORTED = ( 'parallels.avail_sizes', 'parallels.avail_locations', 'proxmox.avail_sizes', ) # Will be set to pyximport module at runtime if cython is enabled in config. pyximport = None def static_loader( opts, ext_type, tag, pack=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, filter_name=None, ): funcs = LazyLoader( _module_dirs( opts, ext_type, tag, int_type, ext_dirs, ext_type_dirs, base_path, ), opts, tag=tag, pack=pack, ) ret = {} funcs._load_all() if filter_name: funcs = FilterDictWrapper(funcs, filter_name) for key in funcs: ret[key] = funcs[key] return ret def _format_entrypoint_target(ep): ''' Makes a string describing the target of an EntryPoint object. Base strongly on EntryPoint.__str__(). ''' s = ep.module_name if ep.attrs: s += ':' + '.'.join(ep.attrs) return s def _module_dirs( opts, ext_type, tag=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, ): if tag is None: tag = ext_type sys_types = os.path.join(base_path or SALT_BASE_PATH, int_type or ext_type) ext_types = os.path.join(opts['extension_modules'], ext_type) ext_type_types = [] if ext_dirs: if ext_type_dirs is None: ext_type_dirs = '{0}_dirs'.format(tag) if ext_type_dirs in opts: ext_type_types.extend(opts[ext_type_dirs]) if HAS_PKG_RESOURCES and ext_type_dirs: for entry_point in pkg_resources.iter_entry_points('salt.loader', ext_type_dirs): try: loaded_entry_point = entry_point.load() for path in loaded_entry_point(): ext_type_types.append(path) except Exception as exc: log.error("Error getting module directories from %s: %s", _format_entrypoint_target(entry_point), exc) log.debug("Full backtrace for module directories error", exc_info=True) cli_module_dirs = [] # The dirs can be any module dir, or a in-tree _{ext_type} dir for _dir in opts.get('module_dirs', []): # Prepend to the list to match cli argument ordering maybe_dir = os.path.join(_dir, ext_type) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) continue maybe_dir = os.path.join(_dir, '_{0}'.format(ext_type)) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) return cli_module_dirs + ext_type_types + [ext_types, sys_types] def minion_mods( opts, context=None, utils=None, whitelist=None, initial_load=False, loaded_base_name=None, notify=False, static_modules=None, proxy=None): ''' Load execution modules Returns a dictionary of execution modules appropriate for the current system by evaluating the __virtual__() function in each module. :param dict opts: The Salt options dictionary :param dict context: A Salt context that should be made present inside generated modules in __context__ :param dict utils: Utility functions which should be made available to Salt modules in __utils__. See `utils_dirs` in salt.config for additional information about configuration. :param list whitelist: A list of modules which should be whitelisted. :param bool initial_load: Deprecated flag! Unused. :param str loaded_base_name: A string marker for the loaded base name. :param bool notify: Flag indicating that an event should be fired upon completion of module loading. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) __opts__['grains'] = __grains__ __utils__ = salt.loader.utils(__opts__) __salt__ = salt.loader.minion_mods(__opts__, utils=__utils__) __salt__['test.ping']() ''' # TODO Publish documentation for module whitelisting if not whitelist: whitelist = opts.get('whitelist_modules', None) ret = LazyLoader( _module_dirs(opts, 'modules', 'module'), opts, tag='module', pack={'__context__': context, '__utils__': utils, '__proxy__': proxy}, whitelist=whitelist, loaded_base_name=loaded_base_name, static_modules=static_modules, ) ret.pack['__salt__'] = ret # Load any provider overrides from the configuration file providers option # Note: Providers can be pkg, service, user or group - not to be confused # with cloud providers. providers = opts.get('providers', False) if providers and isinstance(providers, dict): for mod in providers: # sometimes providers opts is not to diverge modules but # for other configuration try: funcs = raw_mod(opts, providers[mod], ret) except TypeError: break else: if funcs: for func in funcs: f_key = '{0}{1}'.format(mod, func[func.rindex('.'):]) ret[f_key] = funcs[func] if notify: evt = salt.utils.event.get_event('minion', opts=opts, listen=False) evt.fire_event({'complete': True}, tag=salt.defaults.events.MINION_MOD_COMPLETE) return ret def raw_mod(opts, name, functions, mod='modules'): ''' Returns a single module loaded raw and bypassing the __virtual__ function .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') testmod = salt.loader.raw_mod(__opts__, 'test', None) testmod['test.ping']() ''' loader = LazyLoader( _module_dirs(opts, mod, 'module'), opts, tag='rawmodule', virtual_enable=False, pack={'__salt__': functions}, ) # if we don't have the module, return an empty dict if name not in loader.file_mapping: return {} loader._load_module(name) # load a single module (the one passed in) return dict(loader._dict) # return a copy of *just* the funcs for `name` def metaproxy(opts): ''' Return functions used in the meta proxy ''' return LazyLoader( _module_dirs(opts, 'metaproxy'), opts, tag='metaproxy' ) def matchers(opts): ''' Return the matcher services plugins ''' return LazyLoader( _module_dirs(opts, 'matchers'), opts, tag='matchers' ) def engines(opts, functions, runners, utils, proxy=None): ''' Return the master services plugins ''' pack = {'__salt__': functions, '__runners__': runners, '__proxy__': proxy, '__utils__': utils} return LazyLoader( _module_dirs(opts, 'engines'), opts, tag='engines', pack=pack, ) def proxy(opts, functions=None, returners=None, whitelist=None, utils=None): ''' Returns the proxy module for this salt-proxy-minion ''' ret = LazyLoader( _module_dirs(opts, 'proxy'), opts, tag='proxy', pack={'__salt__': functions, '__ret__': returners, '__utils__': utils}, ) ret.pack['__proxy__'] = ret return ret def returners(opts, functions, whitelist=None, context=None, proxy=None): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'returners', 'returner'), opts, tag='returner', whitelist=whitelist, pack={'__salt__': functions, '__context__': context, '__proxy__': proxy or {}}, ) def utils(opts, whitelist=None, context=None, proxy=proxy): ''' Returns the utility modules ''' return LazyLoader( _module_dirs(opts, 'utils', ext_type_dirs='utils_dirs'), opts, tag='utils', whitelist=whitelist, pack={'__context__': context, '__proxy__': proxy or {}}, ) def pillars(opts, functions, context=None): ''' Returns the pillars modules ''' ret = LazyLoader(_module_dirs(opts, 'pillar'), opts, tag='pillar', pack={'__salt__': functions, '__context__': context, '__utils__': utils(opts)}) ret.pack['__ext_pillar__'] = ret return FilterDictWrapper(ret, '.ext_pillar') def tops(opts): ''' Returns the tops modules ''' if 'master_tops' not in opts: return {} whitelist = list(opts['master_tops'].keys()) ret = LazyLoader( _module_dirs(opts, 'tops', 'top'), opts, tag='top', whitelist=whitelist, ) return FilterDictWrapper(ret, '.top') def wheels(opts, whitelist=None, context=None): ''' Returns the wheels modules ''' if context is None: context = {} return LazyLoader( _module_dirs(opts, 'wheel'), opts, tag='wheel', whitelist=whitelist, pack={'__context__': context}, ) def serializers(opts): ''' Returns the serializers modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only serializers present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'serializers'), opts, tag='serializers', ) def eauth_tokens(opts): ''' Returns the tokens modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only token backends present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'tokens'), opts, tag='tokens', ) def auth(opts, whitelist=None): ''' Returns the auth modules :param dict opts: The Salt options dictionary :returns: LazyLoader ''' return LazyLoader( _module_dirs(opts, 'auth'), opts, tag='auth', whitelist=whitelist, pack={'__salt__': minion_mods(opts)}, ) def fileserver(opts, backends): ''' Returns the file server modules ''' return LazyLoader(_module_dirs(opts, 'fileserver'), opts, tag='fileserver', whitelist=backends, pack={'__utils__': utils(opts)}) def roster(opts, runner=None, utils=None, whitelist=None): ''' Returns the roster modules ''' return LazyLoader( _module_dirs(opts, 'roster'), opts, tag='roster', whitelist=whitelist, pack={ '__runner__': runner, '__utils__': utils, }, ) def thorium(opts, functions, runners): ''' Load the thorium runtime modules ''' pack = {'__salt__': functions, '__runner__': runners, '__context__': {}} ret = LazyLoader(_module_dirs(opts, 'thorium'), opts, tag='thorium', pack=pack) ret.pack['__thorium__'] = ret return ret def states(opts, functions, utils, serializers, whitelist=None, proxy=None, context=None): ''' Returns the state modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') statemods = salt.loader.states(__opts__, None, None) ''' if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'states'), opts, tag='states', pack={'__salt__': functions, '__proxy__': proxy or {}}, whitelist=whitelist, ) ret.pack['__states__'] = ret ret.pack['__utils__'] = utils ret.pack['__serializers__'] = serializers ret.pack['__context__'] = context return ret def beacons(opts, functions, context=None, proxy=None): ''' Load the beacon modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. ''' return LazyLoader( _module_dirs(opts, 'beacons'), opts, tag='beacons', pack={'__context__': context, '__salt__': functions, '__proxy__': proxy or {}}, virtual_funcs=[], ) def log_handlers(opts): ''' Returns the custom logging handler modules :param dict opts: The Salt options dictionary ''' ret = LazyLoader( _module_dirs( opts, 'log_handlers', int_type='handlers', base_path=os.path.join(SALT_BASE_PATH, 'log'), ), opts, tag='log_handlers', ) return FilterDictWrapper(ret, '.setup_handlers') def ssh_wrapper(opts, functions=None, context=None): ''' Returns the custom logging handler modules ''' return LazyLoader( _module_dirs( opts, 'wrapper', base_path=os.path.join(SALT_BASE_PATH, os.path.join('client', 'ssh')), ), opts, tag='wrapper', pack={ '__salt__': functions, '__grains__': opts.get('grains', {}), '__pillar__': opts.get('pillar', {}), '__context__': context, }, ) def render(opts, functions, states=None, proxy=None, context=None): ''' Returns the render modules ''' if context is None: context = {} pack = {'__salt__': functions, '__grains__': opts.get('grains', {}), '__context__': context} if states: pack['__states__'] = states pack['__proxy__'] = proxy or {} ret = LazyLoader( _module_dirs( opts, 'renderers', 'render', ext_type_dirs='render_dirs', ), opts, tag='render', pack=pack, ) rend = FilterDictWrapper(ret, '.render') if not check_render_pipe_str(opts['renderer'], rend, opts['renderer_blacklist'], opts['renderer_whitelist']): err = ('The renderer {0} is unavailable, this error is often because ' 'the needed software is unavailable'.format(opts['renderer'])) log.critical(err) raise LoaderError(err) return rend def grain_funcs(opts, proxy=None): ''' Returns the grain functions .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') grainfuncs = salt.loader.grain_funcs(__opts__) ''' ret = LazyLoader( _module_dirs( opts, 'grains', 'grain', ext_type_dirs='grains_dirs', ), opts, tag='grains', ) ret.pack['__utils__'] = utils(opts, proxy=proxy) return ret def _load_cached_grains(opts, cfn): ''' Returns the grains cached in cfn, or None if the cache is too old or is corrupted. ''' if not os.path.isfile(cfn): log.debug('Grains cache file does not exist.') return None grains_cache_age = int(time.time() - os.path.getmtime(cfn)) if grains_cache_age > opts.get('grains_cache_expiration', 300): log.debug( 'Grains cache last modified %s seconds ago and cache ' 'expiration is set to %s. Grains cache expired. ' 'Refreshing.', grains_cache_age, opts.get('grains_cache_expiration', 300) ) return None if opts.get('refresh_grains_cache', False): log.debug('refresh_grains_cache requested, Refreshing.') return None log.debug('Retrieving grains from cache') try: serial = salt.payload.Serial(opts) with salt.utils.files.fopen(cfn, 'rb') as fp_: cached_grains = salt.utils.data.decode(serial.load(fp_), preserve_tuples=True) if not cached_grains: log.debug('Cached grains are empty, cache might be corrupted. Refreshing.') return None return cached_grains except (IOError, OSError): return None def grains(opts, force_refresh=False, proxy=None): ''' Return the functions for the dynamic grains and the values for the static grains. Since grains are computed early in the startup process, grains functions do not have __salt__ or __proxy__ available. At proxy-minion startup, this function is called with the proxymodule LazyLoader object so grains functions can communicate with their controlled device. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) print __grains__['id'] ''' # Need to re-import salt.config, somehow it got lost when a minion is starting import salt.config # if we have no grains, lets try loading from disk (TODO: move to decorator?) cfn = os.path.join( opts['cachedir'], 'grains.cache.p' ) if not force_refresh and opts.get('grains_cache', False): cached_grains = _load_cached_grains(opts, cfn) if cached_grains: return cached_grains else: log.debug('Grains refresh requested. Refreshing grains.') if opts.get('skip_grains', False): return {} grains_deep_merge = opts.get('grains_deep_merge', False) is True if 'conf_file' in opts: pre_opts = {} pre_opts.update(salt.config.load_config( opts['conf_file'], 'SALT_MINION_CONFIG', salt.config.DEFAULT_MINION_OPTS['conf_file'] )) default_include = pre_opts.get( 'default_include', opts['default_include'] ) include = pre_opts.get('include', []) pre_opts.update(salt.config.include_config( default_include, opts['conf_file'], verbose=False )) pre_opts.update(salt.config.include_config( include, opts['conf_file'], verbose=True )) if 'grains' in pre_opts: opts['grains'] = pre_opts['grains'] else: opts['grains'] = {} else: opts['grains'] = {} grains_data = {} blist = opts.get('grains_blacklist', []) funcs = grain_funcs(opts, proxy=proxy) if force_refresh: # if we refresh, lets reload grain modules funcs.clear() # Run core grains for key in funcs: if not key.startswith('core.'): continue log.trace('Loading %s grain', key) ret = funcs[key]() if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) # Run the rest of the grains for key in funcs: if key.startswith('core.') or key == '_errors': continue try: # Grains are loaded too early to take advantage of the injected # __proxy__ variable. Pass an instance of that LazyLoader # here instead to grains functions if the grains functions take # one parameter. Then the grains can have access to the # proxymodule for retrieving information from the connected # device. log.trace('Loading %s grain', key) parameters = salt.utils.args.get_function_argspec(funcs[key]).args kwargs = {} if 'proxy' in parameters: kwargs['proxy'] = proxy if 'grains' in parameters: kwargs['grains'] = grains_data ret = funcs[key](**kwargs) except Exception: if salt.utils.platform.is_proxy(): log.info('The following CRITICAL message may not be an error; the proxy may not be completely established yet.') log.critical( 'Failed to load grains defined in grain file %s in ' 'function %s, error:\n', key, funcs[key], exc_info=True ) continue if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) if opts.get('proxy_merge_grains_in_module', True) and proxy: try: proxytype = proxy.opts['proxy']['proxytype'] if proxytype + '.grains' in proxy: if proxytype + '.initialized' in proxy and proxy[proxytype + '.initialized'](): try: proxytype = proxy.opts['proxy']['proxytype'] ret = proxy[proxytype + '.grains']() if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) except Exception: log.critical('Failed to run proxy\'s grains function!', exc_info=True ) except KeyError: pass grains_data.update(opts['grains']) # Write cache if enabled if opts.get('grains_cache', False): with salt.utils.files.set_umask(0o077): try: if salt.utils.platform.is_windows(): # Late import import salt.modules.cmdmod # Make sure cache file isn't read-only salt.modules.cmdmod._run_quiet('attrib -R "{0}"'.format(cfn)) with salt.utils.files.fopen(cfn, 'w+b') as fp_: try: serial = salt.payload.Serial(opts) serial.dump(grains_data, fp_) except TypeError as e: log.error('Failed to serialize grains cache: %s', e) raise # re-throw for cleanup except Exception as e: log.error('Unable to write to grains cache file %s: %s', cfn, e) # Based on the original exception, the file may or may not have been # created. If it was, we will remove it now, as the exception means # the serialized data is not to be trusted, no matter what the # exception is. if os.path.isfile(cfn): os.unlink(cfn) if grains_deep_merge: salt.utils.dictupdate.update(grains_data, opts['grains']) else: grains_data.update(opts['grains']) return salt.utils.data.decode(grains_data, preserve_tuples=True) # TODO: get rid of? Does anyone use this? You should use raw() instead def call(fun, **kwargs): ''' Directly call a function inside a loader directory ''' args = kwargs.get('args', []) dirs = kwargs.get('dirs', []) funcs = LazyLoader( [os.path.join(SALT_BASE_PATH, 'modules')] + dirs, None, tag='modules', virtual_enable=False, ) return funcs[fun](*args) def runner(opts, utils=None, context=None, whitelist=None): ''' Directly call a function inside a loader directory ''' if utils is None: utils = {} if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'runners', 'runner', ext_type_dirs='runner_dirs'), opts, tag='runners', pack={'__utils__': utils, '__context__': context}, whitelist=whitelist, ) # TODO: change from __salt__ to something else, we overload __salt__ too much ret.pack['__salt__'] = ret return ret def queues(opts): ''' Directly call a function inside a loader directory ''' return LazyLoader( _module_dirs(opts, 'queues', 'queue', ext_type_dirs='queue_dirs'), opts, tag='queues', ) def sdb(opts, functions=None, whitelist=None, utils=None): ''' Make a very small database call ''' if utils is None: utils = {} return LazyLoader( _module_dirs(opts, 'sdb'), opts, tag='sdb', pack={ '__sdb__': functions, '__opts__': opts, '__utils__': utils, '__salt__': minion_mods(opts, utils), }, whitelist=whitelist, ) def pkgdb(opts): ''' Return modules for SPM's package database .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgdb', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgdb' ) def pkgfiles(opts): ''' Return modules for SPM's file handling .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgfiles', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgfiles' ) def clouds(opts): ''' Return the cloud functions ''' # Let's bring __active_provider_name__, defaulting to None, to all cloud # drivers. This will get temporarily updated/overridden with a context # manager when needed. functions = LazyLoader( _module_dirs(opts, 'clouds', 'cloud', base_path=os.path.join(SALT_BASE_PATH, 'cloud'), int_type='clouds'), opts, tag='clouds', pack={'__utils__': salt.loader.utils(opts), '__active_provider_name__': None}, ) for funcname in LIBCLOUD_FUNCS_NOT_SUPPORTED: log.trace( '\'%s\' has been marked as not supported. Removing from the ' 'list of supported cloud functions', funcname ) functions.pop(funcname, None) return functions def netapi(opts): ''' Return the network api functions ''' return LazyLoader( _module_dirs(opts, 'netapi'), opts, tag='netapi', ) def executors(opts, functions=None, context=None, proxy=None): ''' Returns the executor modules ''' executors = LazyLoader( _module_dirs(opts, 'executors', 'executor'), opts, tag='executor', pack={'__salt__': functions, '__context__': context or {}, '__proxy__': proxy or {}}, ) executors.pack['__executors__'] = executors return executors def cache(opts, serial): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'cache', 'cache'), opts, tag='cache', pack={'__opts__': opts, '__context__': {'serial': serial}}, ) def _generate_module(name): if name in sys.modules: return code = "'''Salt loaded {0} parent module'''".format(name.split('.')[-1]) # ModuleType can't accept a unicode type on PY2 module = types.ModuleType(str(name)) # future lint: disable=blacklisted-function exec(code, module.__dict__) sys.modules[name] = module def _mod_type(module_path): if module_path.startswith(SALT_BASE_PATH): return 'int' return 'ext' def _inject_into_mod(mod, name, value, force_lock=False): ''' Inject a variable into a module. This is used to inject "globals" like ``__salt__``, ``__pillar``, or ``grains``. Instead of injecting the value directly, a ``ThreadLocalProxy`` is created. If such a proxy is already present under the specified name, it is updated with the new value. This update only affects the current thread, so that the same name can refer to different values depending on the thread of execution. This is important for data that is not truly global. For example, pillar data might be dynamically overriden through function parameters and thus the actual values available in pillar might depend on the thread that is calling a module. mod: module object into which the value is going to be injected. name: name of the variable that is injected into the module. value: value that is injected into the variable. The value is not injected directly, but instead set as the new reference of the proxy that has been created for the variable. force_lock: whether the lock should be acquired before checking whether a proxy object for the specified name has already been injected into the module. If ``False`` (the default), this function checks for the module's variable without acquiring the lock and only acquires the lock if a new proxy has to be created and injected. ''' old_value = getattr(mod, name, None) # We use a double-checked locking scheme in order to avoid taking the lock # when a proxy object has already been injected. # In most programming languages, double-checked locking is considered # unsafe when used without explicit memory barriers because one might read # an uninitialized value. In CPython it is safe due to the global # interpreter lock (GIL). In Python implementations that do not have the # GIL, it could be unsafe, but at least Jython also guarantees that (for # Python objects) memory is not corrupted when writing and reading without # explicit synchronization # (http://www.jython.org/jythonbook/en/1.0/Concurrency.html). # Please note that in order to make this code safe in a runtime environment # that does not make this guarantees, it is not sufficient. The # ThreadLocalProxy must also be created with fallback_to_shared set to # False or a lock must be added to the ThreadLocalProxy. if force_lock: with _inject_into_mod.lock: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: setattr(mod, name, ThreadLocalProxy(value, True)) else: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: _inject_into_mod(mod, name, value, True) # Lock used when injecting globals. This is needed to avoid a race condition # when two threads try to load the same module concurrently. This must be # outside the loader because there might be more than one loader for the same # namespace. _inject_into_mod.lock = threading.RLock() # TODO: move somewhere else? class FilterDictWrapper(MutableMapping): ''' Create a dict which wraps another dict with a specific key suffix on get This is to replace "filter_load" ''' def __init__(self, d, suffix): self._dict = d self.suffix = suffix def __setitem__(self, key, val): self._dict[key] = val def __delitem__(self, key): del self._dict[key] def __getitem__(self, key): return self._dict[key + self.suffix] def __len__(self): return len(self._dict) def __iter__(self): for key in self._dict: if key.endswith(self.suffix): yield key.replace(self.suffix, '') class LazyLoader(salt.utils.lazy.LazyDict): ''' A pseduo-dictionary which has a set of keys which are the name of the module and function, delimited by a dot. When the value of the key is accessed, the function is then loaded from disk and into memory. .. note:: Iterating over keys will cause all modules to be loaded. :param list module_dirs: A list of directories on disk to search for modules :param dict opts: The salt options dictionary. :param str tag: The tag for the type of module to load :param func mod_type_check: A function which can be used to verify files :param dict pack: A dictionary of function to be packed into modules as they are loaded :param list whitelist: A list of modules to whitelist :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules. :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality. If not true, the module will not load. :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values are function references themselves which are loaded on-demand. # TODO: - move modules_max_memory into here - singletons (per tag) ''' mod_dict_class = salt.utils.odict.OrderedDict def __init__(self, module_dirs, opts=None, tag='module', loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, proxy=None, virtual_funcs=None, ): # pylint: disable=W0231 ''' In pack, if any of the values are None they will be replaced with an empty context-specific dict ''' self.inject_globals = {} self.pack = {} if pack is None else pack if opts is None: opts = {} threadsafety = not opts.get('multiprocessing') self.context_dict = salt.utils.context.ContextDict(threadsafe=threadsafety) self.opts = self.__prep_mod_opts(opts) self.module_dirs = module_dirs self.tag = tag self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME self.mod_type_check = mod_type_check or _mod_type if '__context__' not in self.pack: self.pack['__context__'] = None for k, v in six.iteritems(self.pack): if v is None: # if the value of a pack is None, lets make an empty dict value = self.context_dict.get(k, {}) if isinstance(value, ThreadLocalProxy): value = ThreadLocalProxy.unproxy(value) self.context_dict[k] = value self.pack[k] = salt.utils.context.NamespacedDictWrapper(self.context_dict, k) self.whitelist = whitelist self.virtual_enable = virtual_enable self.initial_load = True # names of modules that we don't have (errors, __virtual__, etc.) self.missing_modules = {} # mapping of name -> error self.loaded_modules = {} # mapping of module_name -> dict_of_functions self.loaded_files = set() # TODO: just remove them from file_mapping? self.static_modules = static_modules if static_modules else [] if virtual_funcs is None: virtual_funcs = [] self.virtual_funcs = virtual_funcs self.disabled = set( self.opts.get( 'disable_{0}{1}'.format( self.tag, '' if self.tag[-1] == 's' else 's' ), [] ) ) # A map of suffix to description for imp self.suffix_map = {} # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [''] for (suffix, mode, kind) in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) self._lock = threading.RLock() self._refresh_file_mapping() super(LazyLoader, self).__init__() # late init the lazy loader # create all of the import namespaces _generate_module('{0}.int'.format(self.loaded_base_name)) _generate_module('{0}.int.{1}'.format(self.loaded_base_name, tag)) _generate_module('{0}.ext'.format(self.loaded_base_name)) _generate_module('{0}.ext.{1}'.format(self.loaded_base_name, tag)) def __getitem__(self, item): ''' Override the __getitem__ in order to decorate the returned function if we need to last-minute inject globals ''' func = super(LazyLoader, self).__getitem__(item) if self.inject_globals: return global_injector_decorator(self.inject_globals)(func) else: return func def __getattr__(self, mod_name): ''' Allow for "direct" attribute access-- this allows jinja templates to access things like `salt.test.ping()` ''' if mod_name in ('__getstate__', '__setstate__'): return object.__getattribute__(self, mod_name) # if we have an attribute named that, lets return it. try: return object.__getattr__(self, mod_name) # pylint: disable=no-member except AttributeError: pass # otherwise we assume its jinja template access if mod_name not in self.loaded_modules and not self.loaded: for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and mod_name in self.loaded_modules: break if mod_name in self.loaded_modules: return self.loaded_modules[mod_name] else: raise AttributeError(mod_name) def missing_fun_string(self, function_name): ''' Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ''' mod_name = function_name.split('.')[0] if mod_name in self.loaded_modules: return '\'{0}\' is not available.'.format(function_name) else: try: reason = self.missing_modules[mod_name] except KeyError: return '\'{0}\' is not available.'.format(function_name) else: if reason is not None: return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason) else: return '\'{0}\' __virtual__ returned False'.format(mod_name) def _refresh_file_mapping(self): ''' refresh the mapping of the FS on disk ''' # map of suffix to description for imp if self.opts.get('cython_enable', True) is True: try: global pyximport pyximport = __import__('pyximport') # pylint: disable=import-error pyximport.install() # add to suffix_map so file_mapping will pick it up self.suffix_map['.pyx'] = tuple() except ImportError: log.info('Cython is enabled in the options but not present ' 'in the system path. Skipping Cython modules.') # Allow for zipimport of modules if self.opts.get('enable_zip_modules', True) is True: self.suffix_map['.zip'] = tuple() # allow for module dirs if USE_IMPORTLIB: self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY) else: self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY) # create mapping of filename (without suffix) to (path, suffix) # The files are added in order of priority, so order *must* be retained. self.file_mapping = salt.utils.odict.OrderedDict() opt_match = [] def _replace_pre_ext(obj): ''' Hack so we can get the optimization level that we replaced (if any) out of the re.sub call below. We use a list here because it is a persistent data structure that we will be able to access after re.sub is called. ''' opt_match.append(obj) return '' for mod_dir in self.module_dirs: try: # Make sure we have a sorted listdir in order to have # expectable override results files = sorted( x for x in os.listdir(mod_dir) if x != '__pycache__' ) except OSError: continue # Next mod_dir if six.PY3: try: pycache_files = [ os.path.join('__pycache__', x) for x in sorted(os.listdir(os.path.join(mod_dir, '__pycache__'))) ] except OSError: pass else: files.extend(pycache_files) for filename in files: try: dirname, basename = os.path.split(filename) if basename.startswith('_'): # skip private modules # log messages omitted for obviousness continue # Next filename f_noext, ext = os.path.splitext(basename) if six.PY3: f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext) try: opt_level = int( opt_match.pop().group(1).rsplit('-', 1)[-1] ) except (AttributeError, IndexError, ValueError): # No regex match or no optimization level matched opt_level = 0 try: opt_index = self.opts['optimization_order'].index(opt_level) except KeyError: log.trace( 'Disallowed optimization level %d for module ' 'name \'%s\', skipping. Add %d to the ' '\'optimization_order\' config option if you ' 'do not want to ignore this optimization ' 'level.', opt_level, f_noext, opt_level ) continue else: # Optimization level not reflected in filename on PY2 opt_index = 0 # make sure it is a suffix we support if ext not in self.suffix_map: continue # Next filename if f_noext in self.disabled: log.trace( 'Skipping %s, it is disabled by configuration', filename ) continue # Next filename fpath = os.path.join(mod_dir, filename) # if its a directory, lets allow us to load that if ext == '': # is there something __init__? subfiles = os.listdir(fpath) for suffix in self.suffix_order: if '' == suffix: continue # Next suffix (__init__ must have a suffix) init_file = '__init__{0}'.format(suffix) if init_file in subfiles: break else: continue # Next filename try: curr_ext = self.file_mapping[f_noext][1] curr_opt_index = self.file_mapping[f_noext][2] except KeyError: pass else: if '' in (curr_ext, ext) and curr_ext != ext: log.error( 'Module/package collision: \'%s\' and \'%s\'', fpath, self.file_mapping[f_noext][0] ) if six.PY3 and ext == '.pyc' and curr_ext == '.pyc': # Check the optimization level if opt_index >= curr_opt_index: # Module name match, but a higher-priority # optimization level was already matched, skipping. continue elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext): # Match found but a higher-priorty match already # exists, so skip this. continue if six.PY3 and not dirname and ext == '.pyc': # On Python 3, we should only load .pyc files from the # __pycache__ subdirectory (i.e. when dirname is not an # empty string). continue # Made it this far - add it self.file_mapping[f_noext] = (fpath, ext, opt_index) except OSError: continue for smod in self.static_modules: f_noext = smod.split('.')[-1] self.file_mapping[f_noext] = (smod, '.o', 0) def clear(self): ''' Clear the dict ''' with self._lock: super(LazyLoader, self).clear() # clear the lazy loader self.loaded_files = set() self.missing_modules = {} self.loaded_modules = {} # if we have been loaded before, lets clear the file mapping since # we obviously want a re-do if hasattr(self, 'opts'): self._refresh_file_mapping() self.initial_load = False def __prep_mod_opts(self, opts): ''' Strip out of the opts any logger instance ''' if '__grains__' not in self.pack: grains = opts.get('grains', {}) if isinstance(grains, ThreadLocalProxy): grains = ThreadLocalProxy.unproxy(grains) self.context_dict['grains'] = grains self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains') if '__pillar__' not in self.pack: pillar = opts.get('pillar', {}) if isinstance(pillar, ThreadLocalProxy): pillar = ThreadLocalProxy.unproxy(pillar) self.context_dict['pillar'] = pillar self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar') mod_opts = {} for key, val in list(opts.items()): if key == 'logger': continue mod_opts[key] = val return mod_opts def _iter_files(self, mod_name): ''' Iterate over all file_mapping files in order of closeness to mod_name ''' # do we have an exact match? if mod_name in self.file_mapping: yield mod_name # do we have a partial match? for k in self.file_mapping: if mod_name in k: yield k # anyone else? Bueller? for k in self.file_mapping: if mod_name not in k: yield k def _reload_submodules(self, mod): submodules = ( getattr(mod, sname) for sname in dir(mod) if isinstance(getattr(mod, sname), mod.__class__) ) # reload only custom "sub"modules for submodule in submodules: # it is a submodule if the name is in a namespace under mod if submodule.__name__.startswith(mod.__name__ + '.'): reload_module(submodule) self._reload_submodules(submodule) def _load_module(self, name): mod = None fpath, suffix = self.file_mapping[name][:2] self.loaded_files.add(name) fpath_dirname = os.path.dirname(fpath) try: sys.path.append(fpath_dirname) if suffix == '.pyx': mod = pyximport.load_module(name, fpath, tempfile.gettempdir()) elif suffix == '.o': top_mod = __import__(fpath, globals(), locals(), []) comps = fpath.split('.') if len(comps) < 2: mod = top_mod else: mod = top_mod for subname in comps[1:]: mod = getattr(mod, subname) elif suffix == '.zip': mod = zipimporter(fpath).load_module(name) else: desc = self.suffix_map[suffix] # if it is a directory, we don't open a file try: mod_namespace = '.'.join(( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name)) except TypeError: mod_namespace = '{0}.{1}.{2}.{3}'.format( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name) if suffix == '': if USE_IMPORTLIB: # pylint: disable=no-member # Package directory, look for __init__ loader_details = [ (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES), (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES), (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), ] file_finder = importlib.machinery.FileFinder( fpath_dirname, *loader_details ) spec = file_finder.find_spec(mod_namespace) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: mod = imp.load_module(mod_namespace, None, fpath, desc) # reload all submodules if necessary if not self.initial_load: self._reload_submodules(mod) else: if USE_IMPORTLIB: # pylint: disable=no-member loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath) spec = importlib.util.spec_from_file_location( mod_namespace, fpath, loader=loader ) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() #mod = importlib.util.module_from_spec(spec) #spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: with salt.utils.files.fopen(fpath, desc[1]) as fn_: mod = imp.load_module(mod_namespace, fn_, fpath, desc) except IOError: raise except ImportError as exc: if 'magic number' in six.text_type(exc): error_msg = 'Failed to import {0} {1}. Bad magic number. If migrating from Python2 to Python3, remove all .pyc files and try again.'.format(self.tag, name) log.warning(error_msg) self.missing_modules[name] = error_msg log.debug( 'Failed to import %s %s:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = exc return False except Exception as error: log.error( 'Failed to import %s %s, this is due most likely to a ' 'syntax error:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False except SystemExit as error: try: fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1] except Exception: pass else: tgt_fn = os.path.join('salt', 'utils', 'process.py') if fn_.endswith(tgt_fn) and '_handle_signals' in caller: # Race conditon, SIGTERM or SIGINT received while loader # was in process of loading a module. Call sys.exit to # ensure that the process is killed. sys.exit(salt.defaults.exitcodes.EX_OK) log.error( 'Failed to import %s %s as the module called exit()\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False finally: sys.path.remove(fpath_dirname) if hasattr(mod, '__opts__'): mod.__opts__.update(self.opts) else: mod.__opts__ = self.opts # pack whatever other globals we were asked to for p_name, p_value in six.iteritems(self.pack): _inject_into_mod(mod, p_name, p_value) module_name = mod.__name__.rsplit('.', 1)[-1] # Call a module's initialization method if it exists module_init = getattr(mod, '__init__', None) if inspect.isfunction(module_init): try: module_init(self.opts) except TypeError as e: log.error(e) except Exception: err_string = '__init__ failed' log.debug( 'Error loading %s.%s: %s', self.tag, module_name, err_string, exc_info=True ) self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False # if virtual modules are enabled, we need to look for the # __virtual__() function inside that module and run it. if self.virtual_enable: virtual_funcs_to_process = ['__virtual__'] + self.virtual_funcs for virtual_func in virtual_funcs_to_process: virtual_ret, module_name, virtual_err, virtual_aliases = \ self._process_virtual(mod, module_name, virtual_func) if virtual_err is not None: log.trace( 'Error loading %s.%s: %s', self.tag, module_name, virtual_err ) # if _process_virtual returned a non-True value then we are # supposed to not process this module if virtual_ret is not True and module_name not in self.missing_modules: # If a module has information about why it could not be loaded, record it self.missing_modules[module_name] = virtual_err self.missing_modules[name] = virtual_err return False else: virtual_aliases = () # If this is a proxy minion then MOST modules cannot work. Therefore, require that # any module that does work with salt-proxy-minion define __proxyenabled__ as a list # containing the names of the proxy types that the module supports. # # Render modules and state modules are OK though if 'proxy' in self.opts: if self.tag in ['grains', 'proxy']: if not hasattr(mod, '__proxyenabled__') or \ (self.opts['proxy']['proxytype'] not in mod.__proxyenabled__ and '*' not in mod.__proxyenabled__): err_string = 'not a proxy_minion enabled module' self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False if getattr(mod, '__load__', False) is not False: log.info( 'The functions from module \'%s\' are being loaded from the ' 'provided __load__ attribute', module_name ) # If we had another module by the same virtual name, we should put any # new functions under the existing dictionary. mod_names = [module_name] + list(virtual_aliases) mod_dict = dict(( (x, self.loaded_modules.get(x, self.mod_dict_class())) for x in mod_names )) for attr in getattr(mod, '__load__', dir(mod)): if attr.startswith('_') and attr != '__call__': # private functions are skipped, # except __call__ which is default entrance # for multi-function batch-like state syntax continue func = getattr(mod, attr) if not inspect.isfunction(func) and not isinstance(func, functools.partial): # Not a function!? Skip it!!! continue # Let's get the function name. # If the module has the __func_alias__ attribute, it must be a # dictionary mapping in the form of(key -> value): # <real-func-name> -> <desired-func-name> # # It default's of course to the found callable attribute name # if no alias is defined. funcname = getattr(mod, '__func_alias__', {}).get(attr, attr) for tgt_mod in mod_names: try: full_funcname = '.'.join((tgt_mod, funcname)) except TypeError: full_funcname = '{0}.{1}'.format(tgt_mod, funcname) # Save many references for lookups # Careful not to overwrite existing (higher priority) functions if full_funcname not in self._dict: self._dict[full_funcname] = func if funcname not in mod_dict[tgt_mod]: setattr(mod_dict[tgt_mod], funcname, func) mod_dict[tgt_mod][funcname] = func self._apply_outputter(func, mod) # enforce depends try: Depends.enforce_dependencies(self._dict, self.tag) except RuntimeError as exc: log.info( 'Depends.enforce_dependencies() failed for the following ' 'reason: %s', exc ) for tgt_mod in mod_names: self.loaded_modules[tgt_mod] = mod_dict[tgt_mod] return True def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise KeyError('The key \'{0}\' should contain a \'.\''.format(key)) mod_name, _ = key.split('.', 1) with self._lock: # It is possible that the key is in the dictionary after # acquiring the lock due to another thread loading it. if mod_name in self.missing_modules or key in self._dict: return True # if the modulename isn't in the whitelist, don't bother if self.whitelist and mod_name not in self.whitelist: log.error( 'Failed to load function %s because its module (%s) is ' 'not in the whitelist: %s', key, mod_name, self.whitelist ) raise KeyError(key) def _inner_load(mod_name): for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and key in self._dict: return True return False # try to load the module ret = None reloaded = False # re-scan up to once, IOErrors or a failed load cause re-scans of the # filesystem while True: try: ret = _inner_load(mod_name) if not reloaded and ret is not True: self._refresh_file_mapping() reloaded = True continue break except IOError: if not reloaded: self._refresh_file_mapping() reloaded = True continue return ret def _load_all(self): ''' Load all of them ''' with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True def reload_modules(self): with self._lock: self.loaded_files = set() self._load_all() def _apply_outputter(self, func, mod): ''' Apply the __outputter__ variable to the functions ''' if hasattr(mod, '__outputter__'): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__] def _process_virtual(self, mod, module_name, virtual_func='__virtual__'): ''' Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1] ''' # The __virtual__ function will return either a True or False value. # If it returns a True value it can also set a module level attribute # named __virtualname__ with the name that the module should be # referred to as. # # This allows us to have things like the pkg module working on all # platforms under the name 'pkg'. It also allows for modules like # augeas_cfg to be referred to as 'augeas', which would otherwise have # namespace collisions. And finally it allows modules to return False # if they are not intended to run on the given platform or are missing # dependencies. virtual_aliases = getattr(mod, '__virtual_aliases__', tuple()) try: error_reason = None if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__): try: start = time.time() virtual = getattr(mod, virtual_func)() if isinstance(virtual, tuple): error_reason = virtual[1] virtual = virtual[0] if self.opts.get('virtual_timer', False): end = time.time() - start msg = 'Virtual function took {0} seconds for {1}'.format( end, module_name) log.warning(msg) except Exception as exc: error_reason = ( 'Exception raised when processing __virtual__ function' ' for {0}. Module will not be loaded: {1}'.format( mod.__name__, exc)) log.error(error_reason, exc_info_on_loglevel=logging.DEBUG) virtual = None # Get the module's virtual name virtualname = getattr(mod, '__virtualname__', virtual) if not virtual: # if __virtual__() evaluates to False then the module # wasn't meant for this platform or it's not supposed to # load for some other reason. # Some modules might accidentally return None and are # improperly loaded if virtual is None: log.warning( '%s.__virtual__() is wrongly returning `None`. ' 'It should either return `True`, `False` or a new ' 'name. If you\'re the developer of the module ' '\'%s\', please fix this.', mod.__name__, module_name ) return (False, module_name, error_reason, virtual_aliases) # At this point, __virtual__ did not return a # boolean value, let's check for deprecated usage # or module renames if virtual is not True and module_name != virtual: # The module is renaming itself. Updating the module name # with the new name log.trace('Loaded %s as virtual %s', module_name, virtual) if virtualname != virtual: # The __virtualname__ attribute does not match what's # being returned by the __virtual__() function. This # should be considered an error. log.error( 'The module \'%s\' is showing some bad usage. Its ' '__virtualname__ attribute is set to \'%s\' yet the ' '__virtual__() function is returning \'%s\'. These ' 'values should match!', mod.__name__, virtualname, virtual ) module_name = virtualname # If the __virtual__ function returns True and __virtualname__ # is set then use it elif virtual is True and virtualname != module_name: if virtualname is not True: module_name = virtualname except KeyError: # Key errors come out of the virtual function when passing # in incomplete grains sets, these can be safely ignored # and logged to debug, still, it includes the traceback to # help debugging. log.debug('KeyError when loading %s', module_name, exc_info=True) except Exception: # If the module throws an exception during __virtual__() # then log the information and continue to the next. log.error( 'Failed to read the virtual function for %s: %s', self.tag, module_name, exc_info=True ) return (False, module_name, error_reason, virtual_aliases) return (True, module_name, None, virtual_aliases) def global_injector_decorator(inject_globals): ''' Decorator used by the LazyLoader to inject globals into a function at execute time. globals Dictionary with global variables to inject ''' def inner_decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): with salt.utils.context.func_globals_inject(f, **inject_globals): return f(*args, **kwargs) return wrapper return inner_decorator
saltstack/salt
salt/loader.py
auth
python
def auth(opts, whitelist=None): ''' Returns the auth modules :param dict opts: The Salt options dictionary :returns: LazyLoader ''' return LazyLoader( _module_dirs(opts, 'auth'), opts, tag='auth', whitelist=whitelist, pack={'__salt__': minion_mods(opts)}, )
Returns the auth modules :param dict opts: The Salt options dictionary :returns: LazyLoader
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L488-L501
null
# -*- coding: utf-8 -*- ''' The Salt loader is the core to Salt's plugin system, the loader scans directories for python loadable code and organizes the code into the plugin interfaces used by Salt. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import sys import time import logging import inspect import tempfile import threading import functools import threading import traceback import types from zipimport import zipimporter # Import salt libs import salt.config import salt.defaults.events import salt.defaults.exitcodes import salt.syspaths import salt.utils.args import salt.utils.context import salt.utils.data import salt.utils.dictupdate import salt.utils.event import salt.utils.files import salt.utils.lazy import salt.utils.odict import salt.utils.platform import salt.utils.versions import salt.utils.stringutils from salt.exceptions import LoaderError from salt.template import check_render_pipe_str from salt.utils.decorators import Depends from salt.utils.thread_local_proxy import ThreadLocalProxy # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import reload_module if sys.version_info[:2] >= (3, 5): import importlib.machinery # pylint: disable=no-name-in-module,import-error import importlib.util # pylint: disable=no-name-in-module,import-error USE_IMPORTLIB = True else: import imp USE_IMPORTLIB = False try: from collections.abc import MutableMapping except ImportError: from collections import MutableMapping try: import pkg_resources HAS_PKG_RESOURCES = True except ImportError: HAS_PKG_RESOURCES = False log = logging.getLogger(__name__) SALT_BASE_PATH = os.path.abspath(salt.syspaths.INSTALL_DIR) LOADED_BASE_NAME = 'salt.loaded' if USE_IMPORTLIB: # pylint: disable=no-member MODULE_KIND_SOURCE = 1 MODULE_KIND_COMPILED = 2 MODULE_KIND_EXTENSION = 3 MODULE_KIND_PKG_DIRECTORY = 5 SUFFIXES = [] for suffix in importlib.machinery.EXTENSION_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_EXTENSION)) for suffix in importlib.machinery.SOURCE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_SOURCE)) for suffix in importlib.machinery.BYTECODE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_COMPILED)) MODULE_KIND_MAP = { MODULE_KIND_SOURCE: importlib.machinery.SourceFileLoader, MODULE_KIND_COMPILED: importlib.machinery.SourcelessFileLoader, MODULE_KIND_EXTENSION: importlib.machinery.ExtensionFileLoader } # pylint: enable=no-member else: SUFFIXES = imp.get_suffixes() PY3_PRE_EXT = \ re.compile(r'\.cpython-{0}{1}(\.opt-[1-9])?'.format(*sys.version_info[:2])) # Because on the cloud drivers we do `from salt.cloud.libcloudfuncs import *` # which simplifies code readability, it adds some unsupported functions into # the driver's module scope. # We list un-supported functions here. These will be removed from the loaded. # TODO: remove the need for this cross-module code. Maybe use NotImplemented LIBCLOUD_FUNCS_NOT_SUPPORTED = ( 'parallels.avail_sizes', 'parallels.avail_locations', 'proxmox.avail_sizes', ) # Will be set to pyximport module at runtime if cython is enabled in config. pyximport = None def static_loader( opts, ext_type, tag, pack=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, filter_name=None, ): funcs = LazyLoader( _module_dirs( opts, ext_type, tag, int_type, ext_dirs, ext_type_dirs, base_path, ), opts, tag=tag, pack=pack, ) ret = {} funcs._load_all() if filter_name: funcs = FilterDictWrapper(funcs, filter_name) for key in funcs: ret[key] = funcs[key] return ret def _format_entrypoint_target(ep): ''' Makes a string describing the target of an EntryPoint object. Base strongly on EntryPoint.__str__(). ''' s = ep.module_name if ep.attrs: s += ':' + '.'.join(ep.attrs) return s def _module_dirs( opts, ext_type, tag=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, ): if tag is None: tag = ext_type sys_types = os.path.join(base_path or SALT_BASE_PATH, int_type or ext_type) ext_types = os.path.join(opts['extension_modules'], ext_type) ext_type_types = [] if ext_dirs: if ext_type_dirs is None: ext_type_dirs = '{0}_dirs'.format(tag) if ext_type_dirs in opts: ext_type_types.extend(opts[ext_type_dirs]) if HAS_PKG_RESOURCES and ext_type_dirs: for entry_point in pkg_resources.iter_entry_points('salt.loader', ext_type_dirs): try: loaded_entry_point = entry_point.load() for path in loaded_entry_point(): ext_type_types.append(path) except Exception as exc: log.error("Error getting module directories from %s: %s", _format_entrypoint_target(entry_point), exc) log.debug("Full backtrace for module directories error", exc_info=True) cli_module_dirs = [] # The dirs can be any module dir, or a in-tree _{ext_type} dir for _dir in opts.get('module_dirs', []): # Prepend to the list to match cli argument ordering maybe_dir = os.path.join(_dir, ext_type) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) continue maybe_dir = os.path.join(_dir, '_{0}'.format(ext_type)) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) return cli_module_dirs + ext_type_types + [ext_types, sys_types] def minion_mods( opts, context=None, utils=None, whitelist=None, initial_load=False, loaded_base_name=None, notify=False, static_modules=None, proxy=None): ''' Load execution modules Returns a dictionary of execution modules appropriate for the current system by evaluating the __virtual__() function in each module. :param dict opts: The Salt options dictionary :param dict context: A Salt context that should be made present inside generated modules in __context__ :param dict utils: Utility functions which should be made available to Salt modules in __utils__. See `utils_dirs` in salt.config for additional information about configuration. :param list whitelist: A list of modules which should be whitelisted. :param bool initial_load: Deprecated flag! Unused. :param str loaded_base_name: A string marker for the loaded base name. :param bool notify: Flag indicating that an event should be fired upon completion of module loading. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) __opts__['grains'] = __grains__ __utils__ = salt.loader.utils(__opts__) __salt__ = salt.loader.minion_mods(__opts__, utils=__utils__) __salt__['test.ping']() ''' # TODO Publish documentation for module whitelisting if not whitelist: whitelist = opts.get('whitelist_modules', None) ret = LazyLoader( _module_dirs(opts, 'modules', 'module'), opts, tag='module', pack={'__context__': context, '__utils__': utils, '__proxy__': proxy}, whitelist=whitelist, loaded_base_name=loaded_base_name, static_modules=static_modules, ) ret.pack['__salt__'] = ret # Load any provider overrides from the configuration file providers option # Note: Providers can be pkg, service, user or group - not to be confused # with cloud providers. providers = opts.get('providers', False) if providers and isinstance(providers, dict): for mod in providers: # sometimes providers opts is not to diverge modules but # for other configuration try: funcs = raw_mod(opts, providers[mod], ret) except TypeError: break else: if funcs: for func in funcs: f_key = '{0}{1}'.format(mod, func[func.rindex('.'):]) ret[f_key] = funcs[func] if notify: evt = salt.utils.event.get_event('minion', opts=opts, listen=False) evt.fire_event({'complete': True}, tag=salt.defaults.events.MINION_MOD_COMPLETE) return ret def raw_mod(opts, name, functions, mod='modules'): ''' Returns a single module loaded raw and bypassing the __virtual__ function .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') testmod = salt.loader.raw_mod(__opts__, 'test', None) testmod['test.ping']() ''' loader = LazyLoader( _module_dirs(opts, mod, 'module'), opts, tag='rawmodule', virtual_enable=False, pack={'__salt__': functions}, ) # if we don't have the module, return an empty dict if name not in loader.file_mapping: return {} loader._load_module(name) # load a single module (the one passed in) return dict(loader._dict) # return a copy of *just* the funcs for `name` def metaproxy(opts): ''' Return functions used in the meta proxy ''' return LazyLoader( _module_dirs(opts, 'metaproxy'), opts, tag='metaproxy' ) def matchers(opts): ''' Return the matcher services plugins ''' return LazyLoader( _module_dirs(opts, 'matchers'), opts, tag='matchers' ) def engines(opts, functions, runners, utils, proxy=None): ''' Return the master services plugins ''' pack = {'__salt__': functions, '__runners__': runners, '__proxy__': proxy, '__utils__': utils} return LazyLoader( _module_dirs(opts, 'engines'), opts, tag='engines', pack=pack, ) def proxy(opts, functions=None, returners=None, whitelist=None, utils=None): ''' Returns the proxy module for this salt-proxy-minion ''' ret = LazyLoader( _module_dirs(opts, 'proxy'), opts, tag='proxy', pack={'__salt__': functions, '__ret__': returners, '__utils__': utils}, ) ret.pack['__proxy__'] = ret return ret def returners(opts, functions, whitelist=None, context=None, proxy=None): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'returners', 'returner'), opts, tag='returner', whitelist=whitelist, pack={'__salt__': functions, '__context__': context, '__proxy__': proxy or {}}, ) def utils(opts, whitelist=None, context=None, proxy=proxy): ''' Returns the utility modules ''' return LazyLoader( _module_dirs(opts, 'utils', ext_type_dirs='utils_dirs'), opts, tag='utils', whitelist=whitelist, pack={'__context__': context, '__proxy__': proxy or {}}, ) def pillars(opts, functions, context=None): ''' Returns the pillars modules ''' ret = LazyLoader(_module_dirs(opts, 'pillar'), opts, tag='pillar', pack={'__salt__': functions, '__context__': context, '__utils__': utils(opts)}) ret.pack['__ext_pillar__'] = ret return FilterDictWrapper(ret, '.ext_pillar') def tops(opts): ''' Returns the tops modules ''' if 'master_tops' not in opts: return {} whitelist = list(opts['master_tops'].keys()) ret = LazyLoader( _module_dirs(opts, 'tops', 'top'), opts, tag='top', whitelist=whitelist, ) return FilterDictWrapper(ret, '.top') def wheels(opts, whitelist=None, context=None): ''' Returns the wheels modules ''' if context is None: context = {} return LazyLoader( _module_dirs(opts, 'wheel'), opts, tag='wheel', whitelist=whitelist, pack={'__context__': context}, ) def outputters(opts): ''' Returns the outputters modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only outputters present in the keyspace ''' ret = LazyLoader( _module_dirs(opts, 'output', ext_type_dirs='outputter_dirs'), opts, tag='output', ) wrapped_ret = FilterDictWrapper(ret, '.output') # TODO: this name seems terrible... __salt__ should always be execution mods ret.pack['__salt__'] = wrapped_ret return wrapped_ret def serializers(opts): ''' Returns the serializers modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only serializers present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'serializers'), opts, tag='serializers', ) def eauth_tokens(opts): ''' Returns the tokens modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only token backends present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'tokens'), opts, tag='tokens', ) def fileserver(opts, backends): ''' Returns the file server modules ''' return LazyLoader(_module_dirs(opts, 'fileserver'), opts, tag='fileserver', whitelist=backends, pack={'__utils__': utils(opts)}) def roster(opts, runner=None, utils=None, whitelist=None): ''' Returns the roster modules ''' return LazyLoader( _module_dirs(opts, 'roster'), opts, tag='roster', whitelist=whitelist, pack={ '__runner__': runner, '__utils__': utils, }, ) def thorium(opts, functions, runners): ''' Load the thorium runtime modules ''' pack = {'__salt__': functions, '__runner__': runners, '__context__': {}} ret = LazyLoader(_module_dirs(opts, 'thorium'), opts, tag='thorium', pack=pack) ret.pack['__thorium__'] = ret return ret def states(opts, functions, utils, serializers, whitelist=None, proxy=None, context=None): ''' Returns the state modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') statemods = salt.loader.states(__opts__, None, None) ''' if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'states'), opts, tag='states', pack={'__salt__': functions, '__proxy__': proxy or {}}, whitelist=whitelist, ) ret.pack['__states__'] = ret ret.pack['__utils__'] = utils ret.pack['__serializers__'] = serializers ret.pack['__context__'] = context return ret def beacons(opts, functions, context=None, proxy=None): ''' Load the beacon modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. ''' return LazyLoader( _module_dirs(opts, 'beacons'), opts, tag='beacons', pack={'__context__': context, '__salt__': functions, '__proxy__': proxy or {}}, virtual_funcs=[], ) def log_handlers(opts): ''' Returns the custom logging handler modules :param dict opts: The Salt options dictionary ''' ret = LazyLoader( _module_dirs( opts, 'log_handlers', int_type='handlers', base_path=os.path.join(SALT_BASE_PATH, 'log'), ), opts, tag='log_handlers', ) return FilterDictWrapper(ret, '.setup_handlers') def ssh_wrapper(opts, functions=None, context=None): ''' Returns the custom logging handler modules ''' return LazyLoader( _module_dirs( opts, 'wrapper', base_path=os.path.join(SALT_BASE_PATH, os.path.join('client', 'ssh')), ), opts, tag='wrapper', pack={ '__salt__': functions, '__grains__': opts.get('grains', {}), '__pillar__': opts.get('pillar', {}), '__context__': context, }, ) def render(opts, functions, states=None, proxy=None, context=None): ''' Returns the render modules ''' if context is None: context = {} pack = {'__salt__': functions, '__grains__': opts.get('grains', {}), '__context__': context} if states: pack['__states__'] = states pack['__proxy__'] = proxy or {} ret = LazyLoader( _module_dirs( opts, 'renderers', 'render', ext_type_dirs='render_dirs', ), opts, tag='render', pack=pack, ) rend = FilterDictWrapper(ret, '.render') if not check_render_pipe_str(opts['renderer'], rend, opts['renderer_blacklist'], opts['renderer_whitelist']): err = ('The renderer {0} is unavailable, this error is often because ' 'the needed software is unavailable'.format(opts['renderer'])) log.critical(err) raise LoaderError(err) return rend def grain_funcs(opts, proxy=None): ''' Returns the grain functions .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') grainfuncs = salt.loader.grain_funcs(__opts__) ''' ret = LazyLoader( _module_dirs( opts, 'grains', 'grain', ext_type_dirs='grains_dirs', ), opts, tag='grains', ) ret.pack['__utils__'] = utils(opts, proxy=proxy) return ret def _load_cached_grains(opts, cfn): ''' Returns the grains cached in cfn, or None if the cache is too old or is corrupted. ''' if not os.path.isfile(cfn): log.debug('Grains cache file does not exist.') return None grains_cache_age = int(time.time() - os.path.getmtime(cfn)) if grains_cache_age > opts.get('grains_cache_expiration', 300): log.debug( 'Grains cache last modified %s seconds ago and cache ' 'expiration is set to %s. Grains cache expired. ' 'Refreshing.', grains_cache_age, opts.get('grains_cache_expiration', 300) ) return None if opts.get('refresh_grains_cache', False): log.debug('refresh_grains_cache requested, Refreshing.') return None log.debug('Retrieving grains from cache') try: serial = salt.payload.Serial(opts) with salt.utils.files.fopen(cfn, 'rb') as fp_: cached_grains = salt.utils.data.decode(serial.load(fp_), preserve_tuples=True) if not cached_grains: log.debug('Cached grains are empty, cache might be corrupted. Refreshing.') return None return cached_grains except (IOError, OSError): return None def grains(opts, force_refresh=False, proxy=None): ''' Return the functions for the dynamic grains and the values for the static grains. Since grains are computed early in the startup process, grains functions do not have __salt__ or __proxy__ available. At proxy-minion startup, this function is called with the proxymodule LazyLoader object so grains functions can communicate with their controlled device. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) print __grains__['id'] ''' # Need to re-import salt.config, somehow it got lost when a minion is starting import salt.config # if we have no grains, lets try loading from disk (TODO: move to decorator?) cfn = os.path.join( opts['cachedir'], 'grains.cache.p' ) if not force_refresh and opts.get('grains_cache', False): cached_grains = _load_cached_grains(opts, cfn) if cached_grains: return cached_grains else: log.debug('Grains refresh requested. Refreshing grains.') if opts.get('skip_grains', False): return {} grains_deep_merge = opts.get('grains_deep_merge', False) is True if 'conf_file' in opts: pre_opts = {} pre_opts.update(salt.config.load_config( opts['conf_file'], 'SALT_MINION_CONFIG', salt.config.DEFAULT_MINION_OPTS['conf_file'] )) default_include = pre_opts.get( 'default_include', opts['default_include'] ) include = pre_opts.get('include', []) pre_opts.update(salt.config.include_config( default_include, opts['conf_file'], verbose=False )) pre_opts.update(salt.config.include_config( include, opts['conf_file'], verbose=True )) if 'grains' in pre_opts: opts['grains'] = pre_opts['grains'] else: opts['grains'] = {} else: opts['grains'] = {} grains_data = {} blist = opts.get('grains_blacklist', []) funcs = grain_funcs(opts, proxy=proxy) if force_refresh: # if we refresh, lets reload grain modules funcs.clear() # Run core grains for key in funcs: if not key.startswith('core.'): continue log.trace('Loading %s grain', key) ret = funcs[key]() if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) # Run the rest of the grains for key in funcs: if key.startswith('core.') or key == '_errors': continue try: # Grains are loaded too early to take advantage of the injected # __proxy__ variable. Pass an instance of that LazyLoader # here instead to grains functions if the grains functions take # one parameter. Then the grains can have access to the # proxymodule for retrieving information from the connected # device. log.trace('Loading %s grain', key) parameters = salt.utils.args.get_function_argspec(funcs[key]).args kwargs = {} if 'proxy' in parameters: kwargs['proxy'] = proxy if 'grains' in parameters: kwargs['grains'] = grains_data ret = funcs[key](**kwargs) except Exception: if salt.utils.platform.is_proxy(): log.info('The following CRITICAL message may not be an error; the proxy may not be completely established yet.') log.critical( 'Failed to load grains defined in grain file %s in ' 'function %s, error:\n', key, funcs[key], exc_info=True ) continue if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) if opts.get('proxy_merge_grains_in_module', True) and proxy: try: proxytype = proxy.opts['proxy']['proxytype'] if proxytype + '.grains' in proxy: if proxytype + '.initialized' in proxy and proxy[proxytype + '.initialized'](): try: proxytype = proxy.opts['proxy']['proxytype'] ret = proxy[proxytype + '.grains']() if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) except Exception: log.critical('Failed to run proxy\'s grains function!', exc_info=True ) except KeyError: pass grains_data.update(opts['grains']) # Write cache if enabled if opts.get('grains_cache', False): with salt.utils.files.set_umask(0o077): try: if salt.utils.platform.is_windows(): # Late import import salt.modules.cmdmod # Make sure cache file isn't read-only salt.modules.cmdmod._run_quiet('attrib -R "{0}"'.format(cfn)) with salt.utils.files.fopen(cfn, 'w+b') as fp_: try: serial = salt.payload.Serial(opts) serial.dump(grains_data, fp_) except TypeError as e: log.error('Failed to serialize grains cache: %s', e) raise # re-throw for cleanup except Exception as e: log.error('Unable to write to grains cache file %s: %s', cfn, e) # Based on the original exception, the file may or may not have been # created. If it was, we will remove it now, as the exception means # the serialized data is not to be trusted, no matter what the # exception is. if os.path.isfile(cfn): os.unlink(cfn) if grains_deep_merge: salt.utils.dictupdate.update(grains_data, opts['grains']) else: grains_data.update(opts['grains']) return salt.utils.data.decode(grains_data, preserve_tuples=True) # TODO: get rid of? Does anyone use this? You should use raw() instead def call(fun, **kwargs): ''' Directly call a function inside a loader directory ''' args = kwargs.get('args', []) dirs = kwargs.get('dirs', []) funcs = LazyLoader( [os.path.join(SALT_BASE_PATH, 'modules')] + dirs, None, tag='modules', virtual_enable=False, ) return funcs[fun](*args) def runner(opts, utils=None, context=None, whitelist=None): ''' Directly call a function inside a loader directory ''' if utils is None: utils = {} if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'runners', 'runner', ext_type_dirs='runner_dirs'), opts, tag='runners', pack={'__utils__': utils, '__context__': context}, whitelist=whitelist, ) # TODO: change from __salt__ to something else, we overload __salt__ too much ret.pack['__salt__'] = ret return ret def queues(opts): ''' Directly call a function inside a loader directory ''' return LazyLoader( _module_dirs(opts, 'queues', 'queue', ext_type_dirs='queue_dirs'), opts, tag='queues', ) def sdb(opts, functions=None, whitelist=None, utils=None): ''' Make a very small database call ''' if utils is None: utils = {} return LazyLoader( _module_dirs(opts, 'sdb'), opts, tag='sdb', pack={ '__sdb__': functions, '__opts__': opts, '__utils__': utils, '__salt__': minion_mods(opts, utils), }, whitelist=whitelist, ) def pkgdb(opts): ''' Return modules for SPM's package database .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgdb', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgdb' ) def pkgfiles(opts): ''' Return modules for SPM's file handling .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgfiles', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgfiles' ) def clouds(opts): ''' Return the cloud functions ''' # Let's bring __active_provider_name__, defaulting to None, to all cloud # drivers. This will get temporarily updated/overridden with a context # manager when needed. functions = LazyLoader( _module_dirs(opts, 'clouds', 'cloud', base_path=os.path.join(SALT_BASE_PATH, 'cloud'), int_type='clouds'), opts, tag='clouds', pack={'__utils__': salt.loader.utils(opts), '__active_provider_name__': None}, ) for funcname in LIBCLOUD_FUNCS_NOT_SUPPORTED: log.trace( '\'%s\' has been marked as not supported. Removing from the ' 'list of supported cloud functions', funcname ) functions.pop(funcname, None) return functions def netapi(opts): ''' Return the network api functions ''' return LazyLoader( _module_dirs(opts, 'netapi'), opts, tag='netapi', ) def executors(opts, functions=None, context=None, proxy=None): ''' Returns the executor modules ''' executors = LazyLoader( _module_dirs(opts, 'executors', 'executor'), opts, tag='executor', pack={'__salt__': functions, '__context__': context or {}, '__proxy__': proxy or {}}, ) executors.pack['__executors__'] = executors return executors def cache(opts, serial): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'cache', 'cache'), opts, tag='cache', pack={'__opts__': opts, '__context__': {'serial': serial}}, ) def _generate_module(name): if name in sys.modules: return code = "'''Salt loaded {0} parent module'''".format(name.split('.')[-1]) # ModuleType can't accept a unicode type on PY2 module = types.ModuleType(str(name)) # future lint: disable=blacklisted-function exec(code, module.__dict__) sys.modules[name] = module def _mod_type(module_path): if module_path.startswith(SALT_BASE_PATH): return 'int' return 'ext' def _inject_into_mod(mod, name, value, force_lock=False): ''' Inject a variable into a module. This is used to inject "globals" like ``__salt__``, ``__pillar``, or ``grains``. Instead of injecting the value directly, a ``ThreadLocalProxy`` is created. If such a proxy is already present under the specified name, it is updated with the new value. This update only affects the current thread, so that the same name can refer to different values depending on the thread of execution. This is important for data that is not truly global. For example, pillar data might be dynamically overriden through function parameters and thus the actual values available in pillar might depend on the thread that is calling a module. mod: module object into which the value is going to be injected. name: name of the variable that is injected into the module. value: value that is injected into the variable. The value is not injected directly, but instead set as the new reference of the proxy that has been created for the variable. force_lock: whether the lock should be acquired before checking whether a proxy object for the specified name has already been injected into the module. If ``False`` (the default), this function checks for the module's variable without acquiring the lock and only acquires the lock if a new proxy has to be created and injected. ''' old_value = getattr(mod, name, None) # We use a double-checked locking scheme in order to avoid taking the lock # when a proxy object has already been injected. # In most programming languages, double-checked locking is considered # unsafe when used without explicit memory barriers because one might read # an uninitialized value. In CPython it is safe due to the global # interpreter lock (GIL). In Python implementations that do not have the # GIL, it could be unsafe, but at least Jython also guarantees that (for # Python objects) memory is not corrupted when writing and reading without # explicit synchronization # (http://www.jython.org/jythonbook/en/1.0/Concurrency.html). # Please note that in order to make this code safe in a runtime environment # that does not make this guarantees, it is not sufficient. The # ThreadLocalProxy must also be created with fallback_to_shared set to # False or a lock must be added to the ThreadLocalProxy. if force_lock: with _inject_into_mod.lock: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: setattr(mod, name, ThreadLocalProxy(value, True)) else: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: _inject_into_mod(mod, name, value, True) # Lock used when injecting globals. This is needed to avoid a race condition # when two threads try to load the same module concurrently. This must be # outside the loader because there might be more than one loader for the same # namespace. _inject_into_mod.lock = threading.RLock() # TODO: move somewhere else? class FilterDictWrapper(MutableMapping): ''' Create a dict which wraps another dict with a specific key suffix on get This is to replace "filter_load" ''' def __init__(self, d, suffix): self._dict = d self.suffix = suffix def __setitem__(self, key, val): self._dict[key] = val def __delitem__(self, key): del self._dict[key] def __getitem__(self, key): return self._dict[key + self.suffix] def __len__(self): return len(self._dict) def __iter__(self): for key in self._dict: if key.endswith(self.suffix): yield key.replace(self.suffix, '') class LazyLoader(salt.utils.lazy.LazyDict): ''' A pseduo-dictionary which has a set of keys which are the name of the module and function, delimited by a dot. When the value of the key is accessed, the function is then loaded from disk and into memory. .. note:: Iterating over keys will cause all modules to be loaded. :param list module_dirs: A list of directories on disk to search for modules :param dict opts: The salt options dictionary. :param str tag: The tag for the type of module to load :param func mod_type_check: A function which can be used to verify files :param dict pack: A dictionary of function to be packed into modules as they are loaded :param list whitelist: A list of modules to whitelist :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules. :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality. If not true, the module will not load. :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values are function references themselves which are loaded on-demand. # TODO: - move modules_max_memory into here - singletons (per tag) ''' mod_dict_class = salt.utils.odict.OrderedDict def __init__(self, module_dirs, opts=None, tag='module', loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, proxy=None, virtual_funcs=None, ): # pylint: disable=W0231 ''' In pack, if any of the values are None they will be replaced with an empty context-specific dict ''' self.inject_globals = {} self.pack = {} if pack is None else pack if opts is None: opts = {} threadsafety = not opts.get('multiprocessing') self.context_dict = salt.utils.context.ContextDict(threadsafe=threadsafety) self.opts = self.__prep_mod_opts(opts) self.module_dirs = module_dirs self.tag = tag self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME self.mod_type_check = mod_type_check or _mod_type if '__context__' not in self.pack: self.pack['__context__'] = None for k, v in six.iteritems(self.pack): if v is None: # if the value of a pack is None, lets make an empty dict value = self.context_dict.get(k, {}) if isinstance(value, ThreadLocalProxy): value = ThreadLocalProxy.unproxy(value) self.context_dict[k] = value self.pack[k] = salt.utils.context.NamespacedDictWrapper(self.context_dict, k) self.whitelist = whitelist self.virtual_enable = virtual_enable self.initial_load = True # names of modules that we don't have (errors, __virtual__, etc.) self.missing_modules = {} # mapping of name -> error self.loaded_modules = {} # mapping of module_name -> dict_of_functions self.loaded_files = set() # TODO: just remove them from file_mapping? self.static_modules = static_modules if static_modules else [] if virtual_funcs is None: virtual_funcs = [] self.virtual_funcs = virtual_funcs self.disabled = set( self.opts.get( 'disable_{0}{1}'.format( self.tag, '' if self.tag[-1] == 's' else 's' ), [] ) ) # A map of suffix to description for imp self.suffix_map = {} # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [''] for (suffix, mode, kind) in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) self._lock = threading.RLock() self._refresh_file_mapping() super(LazyLoader, self).__init__() # late init the lazy loader # create all of the import namespaces _generate_module('{0}.int'.format(self.loaded_base_name)) _generate_module('{0}.int.{1}'.format(self.loaded_base_name, tag)) _generate_module('{0}.ext'.format(self.loaded_base_name)) _generate_module('{0}.ext.{1}'.format(self.loaded_base_name, tag)) def __getitem__(self, item): ''' Override the __getitem__ in order to decorate the returned function if we need to last-minute inject globals ''' func = super(LazyLoader, self).__getitem__(item) if self.inject_globals: return global_injector_decorator(self.inject_globals)(func) else: return func def __getattr__(self, mod_name): ''' Allow for "direct" attribute access-- this allows jinja templates to access things like `salt.test.ping()` ''' if mod_name in ('__getstate__', '__setstate__'): return object.__getattribute__(self, mod_name) # if we have an attribute named that, lets return it. try: return object.__getattr__(self, mod_name) # pylint: disable=no-member except AttributeError: pass # otherwise we assume its jinja template access if mod_name not in self.loaded_modules and not self.loaded: for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and mod_name in self.loaded_modules: break if mod_name in self.loaded_modules: return self.loaded_modules[mod_name] else: raise AttributeError(mod_name) def missing_fun_string(self, function_name): ''' Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ''' mod_name = function_name.split('.')[0] if mod_name in self.loaded_modules: return '\'{0}\' is not available.'.format(function_name) else: try: reason = self.missing_modules[mod_name] except KeyError: return '\'{0}\' is not available.'.format(function_name) else: if reason is not None: return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason) else: return '\'{0}\' __virtual__ returned False'.format(mod_name) def _refresh_file_mapping(self): ''' refresh the mapping of the FS on disk ''' # map of suffix to description for imp if self.opts.get('cython_enable', True) is True: try: global pyximport pyximport = __import__('pyximport') # pylint: disable=import-error pyximport.install() # add to suffix_map so file_mapping will pick it up self.suffix_map['.pyx'] = tuple() except ImportError: log.info('Cython is enabled in the options but not present ' 'in the system path. Skipping Cython modules.') # Allow for zipimport of modules if self.opts.get('enable_zip_modules', True) is True: self.suffix_map['.zip'] = tuple() # allow for module dirs if USE_IMPORTLIB: self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY) else: self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY) # create mapping of filename (without suffix) to (path, suffix) # The files are added in order of priority, so order *must* be retained. self.file_mapping = salt.utils.odict.OrderedDict() opt_match = [] def _replace_pre_ext(obj): ''' Hack so we can get the optimization level that we replaced (if any) out of the re.sub call below. We use a list here because it is a persistent data structure that we will be able to access after re.sub is called. ''' opt_match.append(obj) return '' for mod_dir in self.module_dirs: try: # Make sure we have a sorted listdir in order to have # expectable override results files = sorted( x for x in os.listdir(mod_dir) if x != '__pycache__' ) except OSError: continue # Next mod_dir if six.PY3: try: pycache_files = [ os.path.join('__pycache__', x) for x in sorted(os.listdir(os.path.join(mod_dir, '__pycache__'))) ] except OSError: pass else: files.extend(pycache_files) for filename in files: try: dirname, basename = os.path.split(filename) if basename.startswith('_'): # skip private modules # log messages omitted for obviousness continue # Next filename f_noext, ext = os.path.splitext(basename) if six.PY3: f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext) try: opt_level = int( opt_match.pop().group(1).rsplit('-', 1)[-1] ) except (AttributeError, IndexError, ValueError): # No regex match or no optimization level matched opt_level = 0 try: opt_index = self.opts['optimization_order'].index(opt_level) except KeyError: log.trace( 'Disallowed optimization level %d for module ' 'name \'%s\', skipping. Add %d to the ' '\'optimization_order\' config option if you ' 'do not want to ignore this optimization ' 'level.', opt_level, f_noext, opt_level ) continue else: # Optimization level not reflected in filename on PY2 opt_index = 0 # make sure it is a suffix we support if ext not in self.suffix_map: continue # Next filename if f_noext in self.disabled: log.trace( 'Skipping %s, it is disabled by configuration', filename ) continue # Next filename fpath = os.path.join(mod_dir, filename) # if its a directory, lets allow us to load that if ext == '': # is there something __init__? subfiles = os.listdir(fpath) for suffix in self.suffix_order: if '' == suffix: continue # Next suffix (__init__ must have a suffix) init_file = '__init__{0}'.format(suffix) if init_file in subfiles: break else: continue # Next filename try: curr_ext = self.file_mapping[f_noext][1] curr_opt_index = self.file_mapping[f_noext][2] except KeyError: pass else: if '' in (curr_ext, ext) and curr_ext != ext: log.error( 'Module/package collision: \'%s\' and \'%s\'', fpath, self.file_mapping[f_noext][0] ) if six.PY3 and ext == '.pyc' and curr_ext == '.pyc': # Check the optimization level if opt_index >= curr_opt_index: # Module name match, but a higher-priority # optimization level was already matched, skipping. continue elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext): # Match found but a higher-priorty match already # exists, so skip this. continue if six.PY3 and not dirname and ext == '.pyc': # On Python 3, we should only load .pyc files from the # __pycache__ subdirectory (i.e. when dirname is not an # empty string). continue # Made it this far - add it self.file_mapping[f_noext] = (fpath, ext, opt_index) except OSError: continue for smod in self.static_modules: f_noext = smod.split('.')[-1] self.file_mapping[f_noext] = (smod, '.o', 0) def clear(self): ''' Clear the dict ''' with self._lock: super(LazyLoader, self).clear() # clear the lazy loader self.loaded_files = set() self.missing_modules = {} self.loaded_modules = {} # if we have been loaded before, lets clear the file mapping since # we obviously want a re-do if hasattr(self, 'opts'): self._refresh_file_mapping() self.initial_load = False def __prep_mod_opts(self, opts): ''' Strip out of the opts any logger instance ''' if '__grains__' not in self.pack: grains = opts.get('grains', {}) if isinstance(grains, ThreadLocalProxy): grains = ThreadLocalProxy.unproxy(grains) self.context_dict['grains'] = grains self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains') if '__pillar__' not in self.pack: pillar = opts.get('pillar', {}) if isinstance(pillar, ThreadLocalProxy): pillar = ThreadLocalProxy.unproxy(pillar) self.context_dict['pillar'] = pillar self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar') mod_opts = {} for key, val in list(opts.items()): if key == 'logger': continue mod_opts[key] = val return mod_opts def _iter_files(self, mod_name): ''' Iterate over all file_mapping files in order of closeness to mod_name ''' # do we have an exact match? if mod_name in self.file_mapping: yield mod_name # do we have a partial match? for k in self.file_mapping: if mod_name in k: yield k # anyone else? Bueller? for k in self.file_mapping: if mod_name not in k: yield k def _reload_submodules(self, mod): submodules = ( getattr(mod, sname) for sname in dir(mod) if isinstance(getattr(mod, sname), mod.__class__) ) # reload only custom "sub"modules for submodule in submodules: # it is a submodule if the name is in a namespace under mod if submodule.__name__.startswith(mod.__name__ + '.'): reload_module(submodule) self._reload_submodules(submodule) def _load_module(self, name): mod = None fpath, suffix = self.file_mapping[name][:2] self.loaded_files.add(name) fpath_dirname = os.path.dirname(fpath) try: sys.path.append(fpath_dirname) if suffix == '.pyx': mod = pyximport.load_module(name, fpath, tempfile.gettempdir()) elif suffix == '.o': top_mod = __import__(fpath, globals(), locals(), []) comps = fpath.split('.') if len(comps) < 2: mod = top_mod else: mod = top_mod for subname in comps[1:]: mod = getattr(mod, subname) elif suffix == '.zip': mod = zipimporter(fpath).load_module(name) else: desc = self.suffix_map[suffix] # if it is a directory, we don't open a file try: mod_namespace = '.'.join(( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name)) except TypeError: mod_namespace = '{0}.{1}.{2}.{3}'.format( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name) if suffix == '': if USE_IMPORTLIB: # pylint: disable=no-member # Package directory, look for __init__ loader_details = [ (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES), (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES), (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), ] file_finder = importlib.machinery.FileFinder( fpath_dirname, *loader_details ) spec = file_finder.find_spec(mod_namespace) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: mod = imp.load_module(mod_namespace, None, fpath, desc) # reload all submodules if necessary if not self.initial_load: self._reload_submodules(mod) else: if USE_IMPORTLIB: # pylint: disable=no-member loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath) spec = importlib.util.spec_from_file_location( mod_namespace, fpath, loader=loader ) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() #mod = importlib.util.module_from_spec(spec) #spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: with salt.utils.files.fopen(fpath, desc[1]) as fn_: mod = imp.load_module(mod_namespace, fn_, fpath, desc) except IOError: raise except ImportError as exc: if 'magic number' in six.text_type(exc): error_msg = 'Failed to import {0} {1}. Bad magic number. If migrating from Python2 to Python3, remove all .pyc files and try again.'.format(self.tag, name) log.warning(error_msg) self.missing_modules[name] = error_msg log.debug( 'Failed to import %s %s:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = exc return False except Exception as error: log.error( 'Failed to import %s %s, this is due most likely to a ' 'syntax error:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False except SystemExit as error: try: fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1] except Exception: pass else: tgt_fn = os.path.join('salt', 'utils', 'process.py') if fn_.endswith(tgt_fn) and '_handle_signals' in caller: # Race conditon, SIGTERM or SIGINT received while loader # was in process of loading a module. Call sys.exit to # ensure that the process is killed. sys.exit(salt.defaults.exitcodes.EX_OK) log.error( 'Failed to import %s %s as the module called exit()\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False finally: sys.path.remove(fpath_dirname) if hasattr(mod, '__opts__'): mod.__opts__.update(self.opts) else: mod.__opts__ = self.opts # pack whatever other globals we were asked to for p_name, p_value in six.iteritems(self.pack): _inject_into_mod(mod, p_name, p_value) module_name = mod.__name__.rsplit('.', 1)[-1] # Call a module's initialization method if it exists module_init = getattr(mod, '__init__', None) if inspect.isfunction(module_init): try: module_init(self.opts) except TypeError as e: log.error(e) except Exception: err_string = '__init__ failed' log.debug( 'Error loading %s.%s: %s', self.tag, module_name, err_string, exc_info=True ) self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False # if virtual modules are enabled, we need to look for the # __virtual__() function inside that module and run it. if self.virtual_enable: virtual_funcs_to_process = ['__virtual__'] + self.virtual_funcs for virtual_func in virtual_funcs_to_process: virtual_ret, module_name, virtual_err, virtual_aliases = \ self._process_virtual(mod, module_name, virtual_func) if virtual_err is not None: log.trace( 'Error loading %s.%s: %s', self.tag, module_name, virtual_err ) # if _process_virtual returned a non-True value then we are # supposed to not process this module if virtual_ret is not True and module_name not in self.missing_modules: # If a module has information about why it could not be loaded, record it self.missing_modules[module_name] = virtual_err self.missing_modules[name] = virtual_err return False else: virtual_aliases = () # If this is a proxy minion then MOST modules cannot work. Therefore, require that # any module that does work with salt-proxy-minion define __proxyenabled__ as a list # containing the names of the proxy types that the module supports. # # Render modules and state modules are OK though if 'proxy' in self.opts: if self.tag in ['grains', 'proxy']: if not hasattr(mod, '__proxyenabled__') or \ (self.opts['proxy']['proxytype'] not in mod.__proxyenabled__ and '*' not in mod.__proxyenabled__): err_string = 'not a proxy_minion enabled module' self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False if getattr(mod, '__load__', False) is not False: log.info( 'The functions from module \'%s\' are being loaded from the ' 'provided __load__ attribute', module_name ) # If we had another module by the same virtual name, we should put any # new functions under the existing dictionary. mod_names = [module_name] + list(virtual_aliases) mod_dict = dict(( (x, self.loaded_modules.get(x, self.mod_dict_class())) for x in mod_names )) for attr in getattr(mod, '__load__', dir(mod)): if attr.startswith('_') and attr != '__call__': # private functions are skipped, # except __call__ which is default entrance # for multi-function batch-like state syntax continue func = getattr(mod, attr) if not inspect.isfunction(func) and not isinstance(func, functools.partial): # Not a function!? Skip it!!! continue # Let's get the function name. # If the module has the __func_alias__ attribute, it must be a # dictionary mapping in the form of(key -> value): # <real-func-name> -> <desired-func-name> # # It default's of course to the found callable attribute name # if no alias is defined. funcname = getattr(mod, '__func_alias__', {}).get(attr, attr) for tgt_mod in mod_names: try: full_funcname = '.'.join((tgt_mod, funcname)) except TypeError: full_funcname = '{0}.{1}'.format(tgt_mod, funcname) # Save many references for lookups # Careful not to overwrite existing (higher priority) functions if full_funcname not in self._dict: self._dict[full_funcname] = func if funcname not in mod_dict[tgt_mod]: setattr(mod_dict[tgt_mod], funcname, func) mod_dict[tgt_mod][funcname] = func self._apply_outputter(func, mod) # enforce depends try: Depends.enforce_dependencies(self._dict, self.tag) except RuntimeError as exc: log.info( 'Depends.enforce_dependencies() failed for the following ' 'reason: %s', exc ) for tgt_mod in mod_names: self.loaded_modules[tgt_mod] = mod_dict[tgt_mod] return True def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise KeyError('The key \'{0}\' should contain a \'.\''.format(key)) mod_name, _ = key.split('.', 1) with self._lock: # It is possible that the key is in the dictionary after # acquiring the lock due to another thread loading it. if mod_name in self.missing_modules or key in self._dict: return True # if the modulename isn't in the whitelist, don't bother if self.whitelist and mod_name not in self.whitelist: log.error( 'Failed to load function %s because its module (%s) is ' 'not in the whitelist: %s', key, mod_name, self.whitelist ) raise KeyError(key) def _inner_load(mod_name): for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and key in self._dict: return True return False # try to load the module ret = None reloaded = False # re-scan up to once, IOErrors or a failed load cause re-scans of the # filesystem while True: try: ret = _inner_load(mod_name) if not reloaded and ret is not True: self._refresh_file_mapping() reloaded = True continue break except IOError: if not reloaded: self._refresh_file_mapping() reloaded = True continue return ret def _load_all(self): ''' Load all of them ''' with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True def reload_modules(self): with self._lock: self.loaded_files = set() self._load_all() def _apply_outputter(self, func, mod): ''' Apply the __outputter__ variable to the functions ''' if hasattr(mod, '__outputter__'): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__] def _process_virtual(self, mod, module_name, virtual_func='__virtual__'): ''' Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1] ''' # The __virtual__ function will return either a True or False value. # If it returns a True value it can also set a module level attribute # named __virtualname__ with the name that the module should be # referred to as. # # This allows us to have things like the pkg module working on all # platforms under the name 'pkg'. It also allows for modules like # augeas_cfg to be referred to as 'augeas', which would otherwise have # namespace collisions. And finally it allows modules to return False # if they are not intended to run on the given platform or are missing # dependencies. virtual_aliases = getattr(mod, '__virtual_aliases__', tuple()) try: error_reason = None if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__): try: start = time.time() virtual = getattr(mod, virtual_func)() if isinstance(virtual, tuple): error_reason = virtual[1] virtual = virtual[0] if self.opts.get('virtual_timer', False): end = time.time() - start msg = 'Virtual function took {0} seconds for {1}'.format( end, module_name) log.warning(msg) except Exception as exc: error_reason = ( 'Exception raised when processing __virtual__ function' ' for {0}. Module will not be loaded: {1}'.format( mod.__name__, exc)) log.error(error_reason, exc_info_on_loglevel=logging.DEBUG) virtual = None # Get the module's virtual name virtualname = getattr(mod, '__virtualname__', virtual) if not virtual: # if __virtual__() evaluates to False then the module # wasn't meant for this platform or it's not supposed to # load for some other reason. # Some modules might accidentally return None and are # improperly loaded if virtual is None: log.warning( '%s.__virtual__() is wrongly returning `None`. ' 'It should either return `True`, `False` or a new ' 'name. If you\'re the developer of the module ' '\'%s\', please fix this.', mod.__name__, module_name ) return (False, module_name, error_reason, virtual_aliases) # At this point, __virtual__ did not return a # boolean value, let's check for deprecated usage # or module renames if virtual is not True and module_name != virtual: # The module is renaming itself. Updating the module name # with the new name log.trace('Loaded %s as virtual %s', module_name, virtual) if virtualname != virtual: # The __virtualname__ attribute does not match what's # being returned by the __virtual__() function. This # should be considered an error. log.error( 'The module \'%s\' is showing some bad usage. Its ' '__virtualname__ attribute is set to \'%s\' yet the ' '__virtual__() function is returning \'%s\'. These ' 'values should match!', mod.__name__, virtualname, virtual ) module_name = virtualname # If the __virtual__ function returns True and __virtualname__ # is set then use it elif virtual is True and virtualname != module_name: if virtualname is not True: module_name = virtualname except KeyError: # Key errors come out of the virtual function when passing # in incomplete grains sets, these can be safely ignored # and logged to debug, still, it includes the traceback to # help debugging. log.debug('KeyError when loading %s', module_name, exc_info=True) except Exception: # If the module throws an exception during __virtual__() # then log the information and continue to the next. log.error( 'Failed to read the virtual function for %s: %s', self.tag, module_name, exc_info=True ) return (False, module_name, error_reason, virtual_aliases) return (True, module_name, None, virtual_aliases) def global_injector_decorator(inject_globals): ''' Decorator used by the LazyLoader to inject globals into a function at execute time. globals Dictionary with global variables to inject ''' def inner_decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): with salt.utils.context.func_globals_inject(f, **inject_globals): return f(*args, **kwargs) return wrapper return inner_decorator
saltstack/salt
salt/loader.py
fileserver
python
def fileserver(opts, backends): ''' Returns the file server modules ''' return LazyLoader(_module_dirs(opts, 'fileserver'), opts, tag='fileserver', whitelist=backends, pack={'__utils__': utils(opts)})
Returns the file server modules
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L504-L512
null
# -*- coding: utf-8 -*- ''' The Salt loader is the core to Salt's plugin system, the loader scans directories for python loadable code and organizes the code into the plugin interfaces used by Salt. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import sys import time import logging import inspect import tempfile import threading import functools import threading import traceback import types from zipimport import zipimporter # Import salt libs import salt.config import salt.defaults.events import salt.defaults.exitcodes import salt.syspaths import salt.utils.args import salt.utils.context import salt.utils.data import salt.utils.dictupdate import salt.utils.event import salt.utils.files import salt.utils.lazy import salt.utils.odict import salt.utils.platform import salt.utils.versions import salt.utils.stringutils from salt.exceptions import LoaderError from salt.template import check_render_pipe_str from salt.utils.decorators import Depends from salt.utils.thread_local_proxy import ThreadLocalProxy # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import reload_module if sys.version_info[:2] >= (3, 5): import importlib.machinery # pylint: disable=no-name-in-module,import-error import importlib.util # pylint: disable=no-name-in-module,import-error USE_IMPORTLIB = True else: import imp USE_IMPORTLIB = False try: from collections.abc import MutableMapping except ImportError: from collections import MutableMapping try: import pkg_resources HAS_PKG_RESOURCES = True except ImportError: HAS_PKG_RESOURCES = False log = logging.getLogger(__name__) SALT_BASE_PATH = os.path.abspath(salt.syspaths.INSTALL_DIR) LOADED_BASE_NAME = 'salt.loaded' if USE_IMPORTLIB: # pylint: disable=no-member MODULE_KIND_SOURCE = 1 MODULE_KIND_COMPILED = 2 MODULE_KIND_EXTENSION = 3 MODULE_KIND_PKG_DIRECTORY = 5 SUFFIXES = [] for suffix in importlib.machinery.EXTENSION_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_EXTENSION)) for suffix in importlib.machinery.SOURCE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_SOURCE)) for suffix in importlib.machinery.BYTECODE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_COMPILED)) MODULE_KIND_MAP = { MODULE_KIND_SOURCE: importlib.machinery.SourceFileLoader, MODULE_KIND_COMPILED: importlib.machinery.SourcelessFileLoader, MODULE_KIND_EXTENSION: importlib.machinery.ExtensionFileLoader } # pylint: enable=no-member else: SUFFIXES = imp.get_suffixes() PY3_PRE_EXT = \ re.compile(r'\.cpython-{0}{1}(\.opt-[1-9])?'.format(*sys.version_info[:2])) # Because on the cloud drivers we do `from salt.cloud.libcloudfuncs import *` # which simplifies code readability, it adds some unsupported functions into # the driver's module scope. # We list un-supported functions here. These will be removed from the loaded. # TODO: remove the need for this cross-module code. Maybe use NotImplemented LIBCLOUD_FUNCS_NOT_SUPPORTED = ( 'parallels.avail_sizes', 'parallels.avail_locations', 'proxmox.avail_sizes', ) # Will be set to pyximport module at runtime if cython is enabled in config. pyximport = None def static_loader( opts, ext_type, tag, pack=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, filter_name=None, ): funcs = LazyLoader( _module_dirs( opts, ext_type, tag, int_type, ext_dirs, ext_type_dirs, base_path, ), opts, tag=tag, pack=pack, ) ret = {} funcs._load_all() if filter_name: funcs = FilterDictWrapper(funcs, filter_name) for key in funcs: ret[key] = funcs[key] return ret def _format_entrypoint_target(ep): ''' Makes a string describing the target of an EntryPoint object. Base strongly on EntryPoint.__str__(). ''' s = ep.module_name if ep.attrs: s += ':' + '.'.join(ep.attrs) return s def _module_dirs( opts, ext_type, tag=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, ): if tag is None: tag = ext_type sys_types = os.path.join(base_path or SALT_BASE_PATH, int_type or ext_type) ext_types = os.path.join(opts['extension_modules'], ext_type) ext_type_types = [] if ext_dirs: if ext_type_dirs is None: ext_type_dirs = '{0}_dirs'.format(tag) if ext_type_dirs in opts: ext_type_types.extend(opts[ext_type_dirs]) if HAS_PKG_RESOURCES and ext_type_dirs: for entry_point in pkg_resources.iter_entry_points('salt.loader', ext_type_dirs): try: loaded_entry_point = entry_point.load() for path in loaded_entry_point(): ext_type_types.append(path) except Exception as exc: log.error("Error getting module directories from %s: %s", _format_entrypoint_target(entry_point), exc) log.debug("Full backtrace for module directories error", exc_info=True) cli_module_dirs = [] # The dirs can be any module dir, or a in-tree _{ext_type} dir for _dir in opts.get('module_dirs', []): # Prepend to the list to match cli argument ordering maybe_dir = os.path.join(_dir, ext_type) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) continue maybe_dir = os.path.join(_dir, '_{0}'.format(ext_type)) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) return cli_module_dirs + ext_type_types + [ext_types, sys_types] def minion_mods( opts, context=None, utils=None, whitelist=None, initial_load=False, loaded_base_name=None, notify=False, static_modules=None, proxy=None): ''' Load execution modules Returns a dictionary of execution modules appropriate for the current system by evaluating the __virtual__() function in each module. :param dict opts: The Salt options dictionary :param dict context: A Salt context that should be made present inside generated modules in __context__ :param dict utils: Utility functions which should be made available to Salt modules in __utils__. See `utils_dirs` in salt.config for additional information about configuration. :param list whitelist: A list of modules which should be whitelisted. :param bool initial_load: Deprecated flag! Unused. :param str loaded_base_name: A string marker for the loaded base name. :param bool notify: Flag indicating that an event should be fired upon completion of module loading. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) __opts__['grains'] = __grains__ __utils__ = salt.loader.utils(__opts__) __salt__ = salt.loader.minion_mods(__opts__, utils=__utils__) __salt__['test.ping']() ''' # TODO Publish documentation for module whitelisting if not whitelist: whitelist = opts.get('whitelist_modules', None) ret = LazyLoader( _module_dirs(opts, 'modules', 'module'), opts, tag='module', pack={'__context__': context, '__utils__': utils, '__proxy__': proxy}, whitelist=whitelist, loaded_base_name=loaded_base_name, static_modules=static_modules, ) ret.pack['__salt__'] = ret # Load any provider overrides from the configuration file providers option # Note: Providers can be pkg, service, user or group - not to be confused # with cloud providers. providers = opts.get('providers', False) if providers and isinstance(providers, dict): for mod in providers: # sometimes providers opts is not to diverge modules but # for other configuration try: funcs = raw_mod(opts, providers[mod], ret) except TypeError: break else: if funcs: for func in funcs: f_key = '{0}{1}'.format(mod, func[func.rindex('.'):]) ret[f_key] = funcs[func] if notify: evt = salt.utils.event.get_event('minion', opts=opts, listen=False) evt.fire_event({'complete': True}, tag=salt.defaults.events.MINION_MOD_COMPLETE) return ret def raw_mod(opts, name, functions, mod='modules'): ''' Returns a single module loaded raw and bypassing the __virtual__ function .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') testmod = salt.loader.raw_mod(__opts__, 'test', None) testmod['test.ping']() ''' loader = LazyLoader( _module_dirs(opts, mod, 'module'), opts, tag='rawmodule', virtual_enable=False, pack={'__salt__': functions}, ) # if we don't have the module, return an empty dict if name not in loader.file_mapping: return {} loader._load_module(name) # load a single module (the one passed in) return dict(loader._dict) # return a copy of *just* the funcs for `name` def metaproxy(opts): ''' Return functions used in the meta proxy ''' return LazyLoader( _module_dirs(opts, 'metaproxy'), opts, tag='metaproxy' ) def matchers(opts): ''' Return the matcher services plugins ''' return LazyLoader( _module_dirs(opts, 'matchers'), opts, tag='matchers' ) def engines(opts, functions, runners, utils, proxy=None): ''' Return the master services plugins ''' pack = {'__salt__': functions, '__runners__': runners, '__proxy__': proxy, '__utils__': utils} return LazyLoader( _module_dirs(opts, 'engines'), opts, tag='engines', pack=pack, ) def proxy(opts, functions=None, returners=None, whitelist=None, utils=None): ''' Returns the proxy module for this salt-proxy-minion ''' ret = LazyLoader( _module_dirs(opts, 'proxy'), opts, tag='proxy', pack={'__salt__': functions, '__ret__': returners, '__utils__': utils}, ) ret.pack['__proxy__'] = ret return ret def returners(opts, functions, whitelist=None, context=None, proxy=None): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'returners', 'returner'), opts, tag='returner', whitelist=whitelist, pack={'__salt__': functions, '__context__': context, '__proxy__': proxy or {}}, ) def utils(opts, whitelist=None, context=None, proxy=proxy): ''' Returns the utility modules ''' return LazyLoader( _module_dirs(opts, 'utils', ext_type_dirs='utils_dirs'), opts, tag='utils', whitelist=whitelist, pack={'__context__': context, '__proxy__': proxy or {}}, ) def pillars(opts, functions, context=None): ''' Returns the pillars modules ''' ret = LazyLoader(_module_dirs(opts, 'pillar'), opts, tag='pillar', pack={'__salt__': functions, '__context__': context, '__utils__': utils(opts)}) ret.pack['__ext_pillar__'] = ret return FilterDictWrapper(ret, '.ext_pillar') def tops(opts): ''' Returns the tops modules ''' if 'master_tops' not in opts: return {} whitelist = list(opts['master_tops'].keys()) ret = LazyLoader( _module_dirs(opts, 'tops', 'top'), opts, tag='top', whitelist=whitelist, ) return FilterDictWrapper(ret, '.top') def wheels(opts, whitelist=None, context=None): ''' Returns the wheels modules ''' if context is None: context = {} return LazyLoader( _module_dirs(opts, 'wheel'), opts, tag='wheel', whitelist=whitelist, pack={'__context__': context}, ) def outputters(opts): ''' Returns the outputters modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only outputters present in the keyspace ''' ret = LazyLoader( _module_dirs(opts, 'output', ext_type_dirs='outputter_dirs'), opts, tag='output', ) wrapped_ret = FilterDictWrapper(ret, '.output') # TODO: this name seems terrible... __salt__ should always be execution mods ret.pack['__salt__'] = wrapped_ret return wrapped_ret def serializers(opts): ''' Returns the serializers modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only serializers present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'serializers'), opts, tag='serializers', ) def eauth_tokens(opts): ''' Returns the tokens modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only token backends present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'tokens'), opts, tag='tokens', ) def auth(opts, whitelist=None): ''' Returns the auth modules :param dict opts: The Salt options dictionary :returns: LazyLoader ''' return LazyLoader( _module_dirs(opts, 'auth'), opts, tag='auth', whitelist=whitelist, pack={'__salt__': minion_mods(opts)}, ) def roster(opts, runner=None, utils=None, whitelist=None): ''' Returns the roster modules ''' return LazyLoader( _module_dirs(opts, 'roster'), opts, tag='roster', whitelist=whitelist, pack={ '__runner__': runner, '__utils__': utils, }, ) def thorium(opts, functions, runners): ''' Load the thorium runtime modules ''' pack = {'__salt__': functions, '__runner__': runners, '__context__': {}} ret = LazyLoader(_module_dirs(opts, 'thorium'), opts, tag='thorium', pack=pack) ret.pack['__thorium__'] = ret return ret def states(opts, functions, utils, serializers, whitelist=None, proxy=None, context=None): ''' Returns the state modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') statemods = salt.loader.states(__opts__, None, None) ''' if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'states'), opts, tag='states', pack={'__salt__': functions, '__proxy__': proxy or {}}, whitelist=whitelist, ) ret.pack['__states__'] = ret ret.pack['__utils__'] = utils ret.pack['__serializers__'] = serializers ret.pack['__context__'] = context return ret def beacons(opts, functions, context=None, proxy=None): ''' Load the beacon modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. ''' return LazyLoader( _module_dirs(opts, 'beacons'), opts, tag='beacons', pack={'__context__': context, '__salt__': functions, '__proxy__': proxy or {}}, virtual_funcs=[], ) def log_handlers(opts): ''' Returns the custom logging handler modules :param dict opts: The Salt options dictionary ''' ret = LazyLoader( _module_dirs( opts, 'log_handlers', int_type='handlers', base_path=os.path.join(SALT_BASE_PATH, 'log'), ), opts, tag='log_handlers', ) return FilterDictWrapper(ret, '.setup_handlers') def ssh_wrapper(opts, functions=None, context=None): ''' Returns the custom logging handler modules ''' return LazyLoader( _module_dirs( opts, 'wrapper', base_path=os.path.join(SALT_BASE_PATH, os.path.join('client', 'ssh')), ), opts, tag='wrapper', pack={ '__salt__': functions, '__grains__': opts.get('grains', {}), '__pillar__': opts.get('pillar', {}), '__context__': context, }, ) def render(opts, functions, states=None, proxy=None, context=None): ''' Returns the render modules ''' if context is None: context = {} pack = {'__salt__': functions, '__grains__': opts.get('grains', {}), '__context__': context} if states: pack['__states__'] = states pack['__proxy__'] = proxy or {} ret = LazyLoader( _module_dirs( opts, 'renderers', 'render', ext_type_dirs='render_dirs', ), opts, tag='render', pack=pack, ) rend = FilterDictWrapper(ret, '.render') if not check_render_pipe_str(opts['renderer'], rend, opts['renderer_blacklist'], opts['renderer_whitelist']): err = ('The renderer {0} is unavailable, this error is often because ' 'the needed software is unavailable'.format(opts['renderer'])) log.critical(err) raise LoaderError(err) return rend def grain_funcs(opts, proxy=None): ''' Returns the grain functions .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') grainfuncs = salt.loader.grain_funcs(__opts__) ''' ret = LazyLoader( _module_dirs( opts, 'grains', 'grain', ext_type_dirs='grains_dirs', ), opts, tag='grains', ) ret.pack['__utils__'] = utils(opts, proxy=proxy) return ret def _load_cached_grains(opts, cfn): ''' Returns the grains cached in cfn, or None if the cache is too old or is corrupted. ''' if not os.path.isfile(cfn): log.debug('Grains cache file does not exist.') return None grains_cache_age = int(time.time() - os.path.getmtime(cfn)) if grains_cache_age > opts.get('grains_cache_expiration', 300): log.debug( 'Grains cache last modified %s seconds ago and cache ' 'expiration is set to %s. Grains cache expired. ' 'Refreshing.', grains_cache_age, opts.get('grains_cache_expiration', 300) ) return None if opts.get('refresh_grains_cache', False): log.debug('refresh_grains_cache requested, Refreshing.') return None log.debug('Retrieving grains from cache') try: serial = salt.payload.Serial(opts) with salt.utils.files.fopen(cfn, 'rb') as fp_: cached_grains = salt.utils.data.decode(serial.load(fp_), preserve_tuples=True) if not cached_grains: log.debug('Cached grains are empty, cache might be corrupted. Refreshing.') return None return cached_grains except (IOError, OSError): return None def grains(opts, force_refresh=False, proxy=None): ''' Return the functions for the dynamic grains and the values for the static grains. Since grains are computed early in the startup process, grains functions do not have __salt__ or __proxy__ available. At proxy-minion startup, this function is called with the proxymodule LazyLoader object so grains functions can communicate with their controlled device. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) print __grains__['id'] ''' # Need to re-import salt.config, somehow it got lost when a minion is starting import salt.config # if we have no grains, lets try loading from disk (TODO: move to decorator?) cfn = os.path.join( opts['cachedir'], 'grains.cache.p' ) if not force_refresh and opts.get('grains_cache', False): cached_grains = _load_cached_grains(opts, cfn) if cached_grains: return cached_grains else: log.debug('Grains refresh requested. Refreshing grains.') if opts.get('skip_grains', False): return {} grains_deep_merge = opts.get('grains_deep_merge', False) is True if 'conf_file' in opts: pre_opts = {} pre_opts.update(salt.config.load_config( opts['conf_file'], 'SALT_MINION_CONFIG', salt.config.DEFAULT_MINION_OPTS['conf_file'] )) default_include = pre_opts.get( 'default_include', opts['default_include'] ) include = pre_opts.get('include', []) pre_opts.update(salt.config.include_config( default_include, opts['conf_file'], verbose=False )) pre_opts.update(salt.config.include_config( include, opts['conf_file'], verbose=True )) if 'grains' in pre_opts: opts['grains'] = pre_opts['grains'] else: opts['grains'] = {} else: opts['grains'] = {} grains_data = {} blist = opts.get('grains_blacklist', []) funcs = grain_funcs(opts, proxy=proxy) if force_refresh: # if we refresh, lets reload grain modules funcs.clear() # Run core grains for key in funcs: if not key.startswith('core.'): continue log.trace('Loading %s grain', key) ret = funcs[key]() if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) # Run the rest of the grains for key in funcs: if key.startswith('core.') or key == '_errors': continue try: # Grains are loaded too early to take advantage of the injected # __proxy__ variable. Pass an instance of that LazyLoader # here instead to grains functions if the grains functions take # one parameter. Then the grains can have access to the # proxymodule for retrieving information from the connected # device. log.trace('Loading %s grain', key) parameters = salt.utils.args.get_function_argspec(funcs[key]).args kwargs = {} if 'proxy' in parameters: kwargs['proxy'] = proxy if 'grains' in parameters: kwargs['grains'] = grains_data ret = funcs[key](**kwargs) except Exception: if salt.utils.platform.is_proxy(): log.info('The following CRITICAL message may not be an error; the proxy may not be completely established yet.') log.critical( 'Failed to load grains defined in grain file %s in ' 'function %s, error:\n', key, funcs[key], exc_info=True ) continue if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) if opts.get('proxy_merge_grains_in_module', True) and proxy: try: proxytype = proxy.opts['proxy']['proxytype'] if proxytype + '.grains' in proxy: if proxytype + '.initialized' in proxy and proxy[proxytype + '.initialized'](): try: proxytype = proxy.opts['proxy']['proxytype'] ret = proxy[proxytype + '.grains']() if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) except Exception: log.critical('Failed to run proxy\'s grains function!', exc_info=True ) except KeyError: pass grains_data.update(opts['grains']) # Write cache if enabled if opts.get('grains_cache', False): with salt.utils.files.set_umask(0o077): try: if salt.utils.platform.is_windows(): # Late import import salt.modules.cmdmod # Make sure cache file isn't read-only salt.modules.cmdmod._run_quiet('attrib -R "{0}"'.format(cfn)) with salt.utils.files.fopen(cfn, 'w+b') as fp_: try: serial = salt.payload.Serial(opts) serial.dump(grains_data, fp_) except TypeError as e: log.error('Failed to serialize grains cache: %s', e) raise # re-throw for cleanup except Exception as e: log.error('Unable to write to grains cache file %s: %s', cfn, e) # Based on the original exception, the file may or may not have been # created. If it was, we will remove it now, as the exception means # the serialized data is not to be trusted, no matter what the # exception is. if os.path.isfile(cfn): os.unlink(cfn) if grains_deep_merge: salt.utils.dictupdate.update(grains_data, opts['grains']) else: grains_data.update(opts['grains']) return salt.utils.data.decode(grains_data, preserve_tuples=True) # TODO: get rid of? Does anyone use this? You should use raw() instead def call(fun, **kwargs): ''' Directly call a function inside a loader directory ''' args = kwargs.get('args', []) dirs = kwargs.get('dirs', []) funcs = LazyLoader( [os.path.join(SALT_BASE_PATH, 'modules')] + dirs, None, tag='modules', virtual_enable=False, ) return funcs[fun](*args) def runner(opts, utils=None, context=None, whitelist=None): ''' Directly call a function inside a loader directory ''' if utils is None: utils = {} if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'runners', 'runner', ext_type_dirs='runner_dirs'), opts, tag='runners', pack={'__utils__': utils, '__context__': context}, whitelist=whitelist, ) # TODO: change from __salt__ to something else, we overload __salt__ too much ret.pack['__salt__'] = ret return ret def queues(opts): ''' Directly call a function inside a loader directory ''' return LazyLoader( _module_dirs(opts, 'queues', 'queue', ext_type_dirs='queue_dirs'), opts, tag='queues', ) def sdb(opts, functions=None, whitelist=None, utils=None): ''' Make a very small database call ''' if utils is None: utils = {} return LazyLoader( _module_dirs(opts, 'sdb'), opts, tag='sdb', pack={ '__sdb__': functions, '__opts__': opts, '__utils__': utils, '__salt__': minion_mods(opts, utils), }, whitelist=whitelist, ) def pkgdb(opts): ''' Return modules for SPM's package database .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgdb', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgdb' ) def pkgfiles(opts): ''' Return modules for SPM's file handling .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgfiles', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgfiles' ) def clouds(opts): ''' Return the cloud functions ''' # Let's bring __active_provider_name__, defaulting to None, to all cloud # drivers. This will get temporarily updated/overridden with a context # manager when needed. functions = LazyLoader( _module_dirs(opts, 'clouds', 'cloud', base_path=os.path.join(SALT_BASE_PATH, 'cloud'), int_type='clouds'), opts, tag='clouds', pack={'__utils__': salt.loader.utils(opts), '__active_provider_name__': None}, ) for funcname in LIBCLOUD_FUNCS_NOT_SUPPORTED: log.trace( '\'%s\' has been marked as not supported. Removing from the ' 'list of supported cloud functions', funcname ) functions.pop(funcname, None) return functions def netapi(opts): ''' Return the network api functions ''' return LazyLoader( _module_dirs(opts, 'netapi'), opts, tag='netapi', ) def executors(opts, functions=None, context=None, proxy=None): ''' Returns the executor modules ''' executors = LazyLoader( _module_dirs(opts, 'executors', 'executor'), opts, tag='executor', pack={'__salt__': functions, '__context__': context or {}, '__proxy__': proxy or {}}, ) executors.pack['__executors__'] = executors return executors def cache(opts, serial): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'cache', 'cache'), opts, tag='cache', pack={'__opts__': opts, '__context__': {'serial': serial}}, ) def _generate_module(name): if name in sys.modules: return code = "'''Salt loaded {0} parent module'''".format(name.split('.')[-1]) # ModuleType can't accept a unicode type on PY2 module = types.ModuleType(str(name)) # future lint: disable=blacklisted-function exec(code, module.__dict__) sys.modules[name] = module def _mod_type(module_path): if module_path.startswith(SALT_BASE_PATH): return 'int' return 'ext' def _inject_into_mod(mod, name, value, force_lock=False): ''' Inject a variable into a module. This is used to inject "globals" like ``__salt__``, ``__pillar``, or ``grains``. Instead of injecting the value directly, a ``ThreadLocalProxy`` is created. If such a proxy is already present under the specified name, it is updated with the new value. This update only affects the current thread, so that the same name can refer to different values depending on the thread of execution. This is important for data that is not truly global. For example, pillar data might be dynamically overriden through function parameters and thus the actual values available in pillar might depend on the thread that is calling a module. mod: module object into which the value is going to be injected. name: name of the variable that is injected into the module. value: value that is injected into the variable. The value is not injected directly, but instead set as the new reference of the proxy that has been created for the variable. force_lock: whether the lock should be acquired before checking whether a proxy object for the specified name has already been injected into the module. If ``False`` (the default), this function checks for the module's variable without acquiring the lock and only acquires the lock if a new proxy has to be created and injected. ''' old_value = getattr(mod, name, None) # We use a double-checked locking scheme in order to avoid taking the lock # when a proxy object has already been injected. # In most programming languages, double-checked locking is considered # unsafe when used without explicit memory barriers because one might read # an uninitialized value. In CPython it is safe due to the global # interpreter lock (GIL). In Python implementations that do not have the # GIL, it could be unsafe, but at least Jython also guarantees that (for # Python objects) memory is not corrupted when writing and reading without # explicit synchronization # (http://www.jython.org/jythonbook/en/1.0/Concurrency.html). # Please note that in order to make this code safe in a runtime environment # that does not make this guarantees, it is not sufficient. The # ThreadLocalProxy must also be created with fallback_to_shared set to # False or a lock must be added to the ThreadLocalProxy. if force_lock: with _inject_into_mod.lock: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: setattr(mod, name, ThreadLocalProxy(value, True)) else: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: _inject_into_mod(mod, name, value, True) # Lock used when injecting globals. This is needed to avoid a race condition # when two threads try to load the same module concurrently. This must be # outside the loader because there might be more than one loader for the same # namespace. _inject_into_mod.lock = threading.RLock() # TODO: move somewhere else? class FilterDictWrapper(MutableMapping): ''' Create a dict which wraps another dict with a specific key suffix on get This is to replace "filter_load" ''' def __init__(self, d, suffix): self._dict = d self.suffix = suffix def __setitem__(self, key, val): self._dict[key] = val def __delitem__(self, key): del self._dict[key] def __getitem__(self, key): return self._dict[key + self.suffix] def __len__(self): return len(self._dict) def __iter__(self): for key in self._dict: if key.endswith(self.suffix): yield key.replace(self.suffix, '') class LazyLoader(salt.utils.lazy.LazyDict): ''' A pseduo-dictionary which has a set of keys which are the name of the module and function, delimited by a dot. When the value of the key is accessed, the function is then loaded from disk and into memory. .. note:: Iterating over keys will cause all modules to be loaded. :param list module_dirs: A list of directories on disk to search for modules :param dict opts: The salt options dictionary. :param str tag: The tag for the type of module to load :param func mod_type_check: A function which can be used to verify files :param dict pack: A dictionary of function to be packed into modules as they are loaded :param list whitelist: A list of modules to whitelist :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules. :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality. If not true, the module will not load. :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values are function references themselves which are loaded on-demand. # TODO: - move modules_max_memory into here - singletons (per tag) ''' mod_dict_class = salt.utils.odict.OrderedDict def __init__(self, module_dirs, opts=None, tag='module', loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, proxy=None, virtual_funcs=None, ): # pylint: disable=W0231 ''' In pack, if any of the values are None they will be replaced with an empty context-specific dict ''' self.inject_globals = {} self.pack = {} if pack is None else pack if opts is None: opts = {} threadsafety = not opts.get('multiprocessing') self.context_dict = salt.utils.context.ContextDict(threadsafe=threadsafety) self.opts = self.__prep_mod_opts(opts) self.module_dirs = module_dirs self.tag = tag self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME self.mod_type_check = mod_type_check or _mod_type if '__context__' not in self.pack: self.pack['__context__'] = None for k, v in six.iteritems(self.pack): if v is None: # if the value of a pack is None, lets make an empty dict value = self.context_dict.get(k, {}) if isinstance(value, ThreadLocalProxy): value = ThreadLocalProxy.unproxy(value) self.context_dict[k] = value self.pack[k] = salt.utils.context.NamespacedDictWrapper(self.context_dict, k) self.whitelist = whitelist self.virtual_enable = virtual_enable self.initial_load = True # names of modules that we don't have (errors, __virtual__, etc.) self.missing_modules = {} # mapping of name -> error self.loaded_modules = {} # mapping of module_name -> dict_of_functions self.loaded_files = set() # TODO: just remove them from file_mapping? self.static_modules = static_modules if static_modules else [] if virtual_funcs is None: virtual_funcs = [] self.virtual_funcs = virtual_funcs self.disabled = set( self.opts.get( 'disable_{0}{1}'.format( self.tag, '' if self.tag[-1] == 's' else 's' ), [] ) ) # A map of suffix to description for imp self.suffix_map = {} # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [''] for (suffix, mode, kind) in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) self._lock = threading.RLock() self._refresh_file_mapping() super(LazyLoader, self).__init__() # late init the lazy loader # create all of the import namespaces _generate_module('{0}.int'.format(self.loaded_base_name)) _generate_module('{0}.int.{1}'.format(self.loaded_base_name, tag)) _generate_module('{0}.ext'.format(self.loaded_base_name)) _generate_module('{0}.ext.{1}'.format(self.loaded_base_name, tag)) def __getitem__(self, item): ''' Override the __getitem__ in order to decorate the returned function if we need to last-minute inject globals ''' func = super(LazyLoader, self).__getitem__(item) if self.inject_globals: return global_injector_decorator(self.inject_globals)(func) else: return func def __getattr__(self, mod_name): ''' Allow for "direct" attribute access-- this allows jinja templates to access things like `salt.test.ping()` ''' if mod_name in ('__getstate__', '__setstate__'): return object.__getattribute__(self, mod_name) # if we have an attribute named that, lets return it. try: return object.__getattr__(self, mod_name) # pylint: disable=no-member except AttributeError: pass # otherwise we assume its jinja template access if mod_name not in self.loaded_modules and not self.loaded: for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and mod_name in self.loaded_modules: break if mod_name in self.loaded_modules: return self.loaded_modules[mod_name] else: raise AttributeError(mod_name) def missing_fun_string(self, function_name): ''' Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ''' mod_name = function_name.split('.')[0] if mod_name in self.loaded_modules: return '\'{0}\' is not available.'.format(function_name) else: try: reason = self.missing_modules[mod_name] except KeyError: return '\'{0}\' is not available.'.format(function_name) else: if reason is not None: return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason) else: return '\'{0}\' __virtual__ returned False'.format(mod_name) def _refresh_file_mapping(self): ''' refresh the mapping of the FS on disk ''' # map of suffix to description for imp if self.opts.get('cython_enable', True) is True: try: global pyximport pyximport = __import__('pyximport') # pylint: disable=import-error pyximport.install() # add to suffix_map so file_mapping will pick it up self.suffix_map['.pyx'] = tuple() except ImportError: log.info('Cython is enabled in the options but not present ' 'in the system path. Skipping Cython modules.') # Allow for zipimport of modules if self.opts.get('enable_zip_modules', True) is True: self.suffix_map['.zip'] = tuple() # allow for module dirs if USE_IMPORTLIB: self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY) else: self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY) # create mapping of filename (without suffix) to (path, suffix) # The files are added in order of priority, so order *must* be retained. self.file_mapping = salt.utils.odict.OrderedDict() opt_match = [] def _replace_pre_ext(obj): ''' Hack so we can get the optimization level that we replaced (if any) out of the re.sub call below. We use a list here because it is a persistent data structure that we will be able to access after re.sub is called. ''' opt_match.append(obj) return '' for mod_dir in self.module_dirs: try: # Make sure we have a sorted listdir in order to have # expectable override results files = sorted( x for x in os.listdir(mod_dir) if x != '__pycache__' ) except OSError: continue # Next mod_dir if six.PY3: try: pycache_files = [ os.path.join('__pycache__', x) for x in sorted(os.listdir(os.path.join(mod_dir, '__pycache__'))) ] except OSError: pass else: files.extend(pycache_files) for filename in files: try: dirname, basename = os.path.split(filename) if basename.startswith('_'): # skip private modules # log messages omitted for obviousness continue # Next filename f_noext, ext = os.path.splitext(basename) if six.PY3: f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext) try: opt_level = int( opt_match.pop().group(1).rsplit('-', 1)[-1] ) except (AttributeError, IndexError, ValueError): # No regex match or no optimization level matched opt_level = 0 try: opt_index = self.opts['optimization_order'].index(opt_level) except KeyError: log.trace( 'Disallowed optimization level %d for module ' 'name \'%s\', skipping. Add %d to the ' '\'optimization_order\' config option if you ' 'do not want to ignore this optimization ' 'level.', opt_level, f_noext, opt_level ) continue else: # Optimization level not reflected in filename on PY2 opt_index = 0 # make sure it is a suffix we support if ext not in self.suffix_map: continue # Next filename if f_noext in self.disabled: log.trace( 'Skipping %s, it is disabled by configuration', filename ) continue # Next filename fpath = os.path.join(mod_dir, filename) # if its a directory, lets allow us to load that if ext == '': # is there something __init__? subfiles = os.listdir(fpath) for suffix in self.suffix_order: if '' == suffix: continue # Next suffix (__init__ must have a suffix) init_file = '__init__{0}'.format(suffix) if init_file in subfiles: break else: continue # Next filename try: curr_ext = self.file_mapping[f_noext][1] curr_opt_index = self.file_mapping[f_noext][2] except KeyError: pass else: if '' in (curr_ext, ext) and curr_ext != ext: log.error( 'Module/package collision: \'%s\' and \'%s\'', fpath, self.file_mapping[f_noext][0] ) if six.PY3 and ext == '.pyc' and curr_ext == '.pyc': # Check the optimization level if opt_index >= curr_opt_index: # Module name match, but a higher-priority # optimization level was already matched, skipping. continue elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext): # Match found but a higher-priorty match already # exists, so skip this. continue if six.PY3 and not dirname and ext == '.pyc': # On Python 3, we should only load .pyc files from the # __pycache__ subdirectory (i.e. when dirname is not an # empty string). continue # Made it this far - add it self.file_mapping[f_noext] = (fpath, ext, opt_index) except OSError: continue for smod in self.static_modules: f_noext = smod.split('.')[-1] self.file_mapping[f_noext] = (smod, '.o', 0) def clear(self): ''' Clear the dict ''' with self._lock: super(LazyLoader, self).clear() # clear the lazy loader self.loaded_files = set() self.missing_modules = {} self.loaded_modules = {} # if we have been loaded before, lets clear the file mapping since # we obviously want a re-do if hasattr(self, 'opts'): self._refresh_file_mapping() self.initial_load = False def __prep_mod_opts(self, opts): ''' Strip out of the opts any logger instance ''' if '__grains__' not in self.pack: grains = opts.get('grains', {}) if isinstance(grains, ThreadLocalProxy): grains = ThreadLocalProxy.unproxy(grains) self.context_dict['grains'] = grains self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains') if '__pillar__' not in self.pack: pillar = opts.get('pillar', {}) if isinstance(pillar, ThreadLocalProxy): pillar = ThreadLocalProxy.unproxy(pillar) self.context_dict['pillar'] = pillar self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar') mod_opts = {} for key, val in list(opts.items()): if key == 'logger': continue mod_opts[key] = val return mod_opts def _iter_files(self, mod_name): ''' Iterate over all file_mapping files in order of closeness to mod_name ''' # do we have an exact match? if mod_name in self.file_mapping: yield mod_name # do we have a partial match? for k in self.file_mapping: if mod_name in k: yield k # anyone else? Bueller? for k in self.file_mapping: if mod_name not in k: yield k def _reload_submodules(self, mod): submodules = ( getattr(mod, sname) for sname in dir(mod) if isinstance(getattr(mod, sname), mod.__class__) ) # reload only custom "sub"modules for submodule in submodules: # it is a submodule if the name is in a namespace under mod if submodule.__name__.startswith(mod.__name__ + '.'): reload_module(submodule) self._reload_submodules(submodule) def _load_module(self, name): mod = None fpath, suffix = self.file_mapping[name][:2] self.loaded_files.add(name) fpath_dirname = os.path.dirname(fpath) try: sys.path.append(fpath_dirname) if suffix == '.pyx': mod = pyximport.load_module(name, fpath, tempfile.gettempdir()) elif suffix == '.o': top_mod = __import__(fpath, globals(), locals(), []) comps = fpath.split('.') if len(comps) < 2: mod = top_mod else: mod = top_mod for subname in comps[1:]: mod = getattr(mod, subname) elif suffix == '.zip': mod = zipimporter(fpath).load_module(name) else: desc = self.suffix_map[suffix] # if it is a directory, we don't open a file try: mod_namespace = '.'.join(( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name)) except TypeError: mod_namespace = '{0}.{1}.{2}.{3}'.format( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name) if suffix == '': if USE_IMPORTLIB: # pylint: disable=no-member # Package directory, look for __init__ loader_details = [ (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES), (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES), (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), ] file_finder = importlib.machinery.FileFinder( fpath_dirname, *loader_details ) spec = file_finder.find_spec(mod_namespace) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: mod = imp.load_module(mod_namespace, None, fpath, desc) # reload all submodules if necessary if not self.initial_load: self._reload_submodules(mod) else: if USE_IMPORTLIB: # pylint: disable=no-member loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath) spec = importlib.util.spec_from_file_location( mod_namespace, fpath, loader=loader ) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() #mod = importlib.util.module_from_spec(spec) #spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: with salt.utils.files.fopen(fpath, desc[1]) as fn_: mod = imp.load_module(mod_namespace, fn_, fpath, desc) except IOError: raise except ImportError as exc: if 'magic number' in six.text_type(exc): error_msg = 'Failed to import {0} {1}. Bad magic number. If migrating from Python2 to Python3, remove all .pyc files and try again.'.format(self.tag, name) log.warning(error_msg) self.missing_modules[name] = error_msg log.debug( 'Failed to import %s %s:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = exc return False except Exception as error: log.error( 'Failed to import %s %s, this is due most likely to a ' 'syntax error:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False except SystemExit as error: try: fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1] except Exception: pass else: tgt_fn = os.path.join('salt', 'utils', 'process.py') if fn_.endswith(tgt_fn) and '_handle_signals' in caller: # Race conditon, SIGTERM or SIGINT received while loader # was in process of loading a module. Call sys.exit to # ensure that the process is killed. sys.exit(salt.defaults.exitcodes.EX_OK) log.error( 'Failed to import %s %s as the module called exit()\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False finally: sys.path.remove(fpath_dirname) if hasattr(mod, '__opts__'): mod.__opts__.update(self.opts) else: mod.__opts__ = self.opts # pack whatever other globals we were asked to for p_name, p_value in six.iteritems(self.pack): _inject_into_mod(mod, p_name, p_value) module_name = mod.__name__.rsplit('.', 1)[-1] # Call a module's initialization method if it exists module_init = getattr(mod, '__init__', None) if inspect.isfunction(module_init): try: module_init(self.opts) except TypeError as e: log.error(e) except Exception: err_string = '__init__ failed' log.debug( 'Error loading %s.%s: %s', self.tag, module_name, err_string, exc_info=True ) self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False # if virtual modules are enabled, we need to look for the # __virtual__() function inside that module and run it. if self.virtual_enable: virtual_funcs_to_process = ['__virtual__'] + self.virtual_funcs for virtual_func in virtual_funcs_to_process: virtual_ret, module_name, virtual_err, virtual_aliases = \ self._process_virtual(mod, module_name, virtual_func) if virtual_err is not None: log.trace( 'Error loading %s.%s: %s', self.tag, module_name, virtual_err ) # if _process_virtual returned a non-True value then we are # supposed to not process this module if virtual_ret is not True and module_name not in self.missing_modules: # If a module has information about why it could not be loaded, record it self.missing_modules[module_name] = virtual_err self.missing_modules[name] = virtual_err return False else: virtual_aliases = () # If this is a proxy minion then MOST modules cannot work. Therefore, require that # any module that does work with salt-proxy-minion define __proxyenabled__ as a list # containing the names of the proxy types that the module supports. # # Render modules and state modules are OK though if 'proxy' in self.opts: if self.tag in ['grains', 'proxy']: if not hasattr(mod, '__proxyenabled__') or \ (self.opts['proxy']['proxytype'] not in mod.__proxyenabled__ and '*' not in mod.__proxyenabled__): err_string = 'not a proxy_minion enabled module' self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False if getattr(mod, '__load__', False) is not False: log.info( 'The functions from module \'%s\' are being loaded from the ' 'provided __load__ attribute', module_name ) # If we had another module by the same virtual name, we should put any # new functions under the existing dictionary. mod_names = [module_name] + list(virtual_aliases) mod_dict = dict(( (x, self.loaded_modules.get(x, self.mod_dict_class())) for x in mod_names )) for attr in getattr(mod, '__load__', dir(mod)): if attr.startswith('_') and attr != '__call__': # private functions are skipped, # except __call__ which is default entrance # for multi-function batch-like state syntax continue func = getattr(mod, attr) if not inspect.isfunction(func) and not isinstance(func, functools.partial): # Not a function!? Skip it!!! continue # Let's get the function name. # If the module has the __func_alias__ attribute, it must be a # dictionary mapping in the form of(key -> value): # <real-func-name> -> <desired-func-name> # # It default's of course to the found callable attribute name # if no alias is defined. funcname = getattr(mod, '__func_alias__', {}).get(attr, attr) for tgt_mod in mod_names: try: full_funcname = '.'.join((tgt_mod, funcname)) except TypeError: full_funcname = '{0}.{1}'.format(tgt_mod, funcname) # Save many references for lookups # Careful not to overwrite existing (higher priority) functions if full_funcname not in self._dict: self._dict[full_funcname] = func if funcname not in mod_dict[tgt_mod]: setattr(mod_dict[tgt_mod], funcname, func) mod_dict[tgt_mod][funcname] = func self._apply_outputter(func, mod) # enforce depends try: Depends.enforce_dependencies(self._dict, self.tag) except RuntimeError as exc: log.info( 'Depends.enforce_dependencies() failed for the following ' 'reason: %s', exc ) for tgt_mod in mod_names: self.loaded_modules[tgt_mod] = mod_dict[tgt_mod] return True def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise KeyError('The key \'{0}\' should contain a \'.\''.format(key)) mod_name, _ = key.split('.', 1) with self._lock: # It is possible that the key is in the dictionary after # acquiring the lock due to another thread loading it. if mod_name in self.missing_modules or key in self._dict: return True # if the modulename isn't in the whitelist, don't bother if self.whitelist and mod_name not in self.whitelist: log.error( 'Failed to load function %s because its module (%s) is ' 'not in the whitelist: %s', key, mod_name, self.whitelist ) raise KeyError(key) def _inner_load(mod_name): for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and key in self._dict: return True return False # try to load the module ret = None reloaded = False # re-scan up to once, IOErrors or a failed load cause re-scans of the # filesystem while True: try: ret = _inner_load(mod_name) if not reloaded and ret is not True: self._refresh_file_mapping() reloaded = True continue break except IOError: if not reloaded: self._refresh_file_mapping() reloaded = True continue return ret def _load_all(self): ''' Load all of them ''' with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True def reload_modules(self): with self._lock: self.loaded_files = set() self._load_all() def _apply_outputter(self, func, mod): ''' Apply the __outputter__ variable to the functions ''' if hasattr(mod, '__outputter__'): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__] def _process_virtual(self, mod, module_name, virtual_func='__virtual__'): ''' Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1] ''' # The __virtual__ function will return either a True or False value. # If it returns a True value it can also set a module level attribute # named __virtualname__ with the name that the module should be # referred to as. # # This allows us to have things like the pkg module working on all # platforms under the name 'pkg'. It also allows for modules like # augeas_cfg to be referred to as 'augeas', which would otherwise have # namespace collisions. And finally it allows modules to return False # if they are not intended to run on the given platform or are missing # dependencies. virtual_aliases = getattr(mod, '__virtual_aliases__', tuple()) try: error_reason = None if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__): try: start = time.time() virtual = getattr(mod, virtual_func)() if isinstance(virtual, tuple): error_reason = virtual[1] virtual = virtual[0] if self.opts.get('virtual_timer', False): end = time.time() - start msg = 'Virtual function took {0} seconds for {1}'.format( end, module_name) log.warning(msg) except Exception as exc: error_reason = ( 'Exception raised when processing __virtual__ function' ' for {0}. Module will not be loaded: {1}'.format( mod.__name__, exc)) log.error(error_reason, exc_info_on_loglevel=logging.DEBUG) virtual = None # Get the module's virtual name virtualname = getattr(mod, '__virtualname__', virtual) if not virtual: # if __virtual__() evaluates to False then the module # wasn't meant for this platform or it's not supposed to # load for some other reason. # Some modules might accidentally return None and are # improperly loaded if virtual is None: log.warning( '%s.__virtual__() is wrongly returning `None`. ' 'It should either return `True`, `False` or a new ' 'name. If you\'re the developer of the module ' '\'%s\', please fix this.', mod.__name__, module_name ) return (False, module_name, error_reason, virtual_aliases) # At this point, __virtual__ did not return a # boolean value, let's check for deprecated usage # or module renames if virtual is not True and module_name != virtual: # The module is renaming itself. Updating the module name # with the new name log.trace('Loaded %s as virtual %s', module_name, virtual) if virtualname != virtual: # The __virtualname__ attribute does not match what's # being returned by the __virtual__() function. This # should be considered an error. log.error( 'The module \'%s\' is showing some bad usage. Its ' '__virtualname__ attribute is set to \'%s\' yet the ' '__virtual__() function is returning \'%s\'. These ' 'values should match!', mod.__name__, virtualname, virtual ) module_name = virtualname # If the __virtual__ function returns True and __virtualname__ # is set then use it elif virtual is True and virtualname != module_name: if virtualname is not True: module_name = virtualname except KeyError: # Key errors come out of the virtual function when passing # in incomplete grains sets, these can be safely ignored # and logged to debug, still, it includes the traceback to # help debugging. log.debug('KeyError when loading %s', module_name, exc_info=True) except Exception: # If the module throws an exception during __virtual__() # then log the information and continue to the next. log.error( 'Failed to read the virtual function for %s: %s', self.tag, module_name, exc_info=True ) return (False, module_name, error_reason, virtual_aliases) return (True, module_name, None, virtual_aliases) def global_injector_decorator(inject_globals): ''' Decorator used by the LazyLoader to inject globals into a function at execute time. globals Dictionary with global variables to inject ''' def inner_decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): with salt.utils.context.func_globals_inject(f, **inject_globals): return f(*args, **kwargs) return wrapper return inner_decorator
saltstack/salt
salt/loader.py
roster
python
def roster(opts, runner=None, utils=None, whitelist=None): ''' Returns the roster modules ''' return LazyLoader( _module_dirs(opts, 'roster'), opts, tag='roster', whitelist=whitelist, pack={ '__runner__': runner, '__utils__': utils, }, )
Returns the roster modules
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L515-L528
null
# -*- coding: utf-8 -*- ''' The Salt loader is the core to Salt's plugin system, the loader scans directories for python loadable code and organizes the code into the plugin interfaces used by Salt. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import sys import time import logging import inspect import tempfile import threading import functools import threading import traceback import types from zipimport import zipimporter # Import salt libs import salt.config import salt.defaults.events import salt.defaults.exitcodes import salt.syspaths import salt.utils.args import salt.utils.context import salt.utils.data import salt.utils.dictupdate import salt.utils.event import salt.utils.files import salt.utils.lazy import salt.utils.odict import salt.utils.platform import salt.utils.versions import salt.utils.stringutils from salt.exceptions import LoaderError from salt.template import check_render_pipe_str from salt.utils.decorators import Depends from salt.utils.thread_local_proxy import ThreadLocalProxy # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import reload_module if sys.version_info[:2] >= (3, 5): import importlib.machinery # pylint: disable=no-name-in-module,import-error import importlib.util # pylint: disable=no-name-in-module,import-error USE_IMPORTLIB = True else: import imp USE_IMPORTLIB = False try: from collections.abc import MutableMapping except ImportError: from collections import MutableMapping try: import pkg_resources HAS_PKG_RESOURCES = True except ImportError: HAS_PKG_RESOURCES = False log = logging.getLogger(__name__) SALT_BASE_PATH = os.path.abspath(salt.syspaths.INSTALL_DIR) LOADED_BASE_NAME = 'salt.loaded' if USE_IMPORTLIB: # pylint: disable=no-member MODULE_KIND_SOURCE = 1 MODULE_KIND_COMPILED = 2 MODULE_KIND_EXTENSION = 3 MODULE_KIND_PKG_DIRECTORY = 5 SUFFIXES = [] for suffix in importlib.machinery.EXTENSION_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_EXTENSION)) for suffix in importlib.machinery.SOURCE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_SOURCE)) for suffix in importlib.machinery.BYTECODE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_COMPILED)) MODULE_KIND_MAP = { MODULE_KIND_SOURCE: importlib.machinery.SourceFileLoader, MODULE_KIND_COMPILED: importlib.machinery.SourcelessFileLoader, MODULE_KIND_EXTENSION: importlib.machinery.ExtensionFileLoader } # pylint: enable=no-member else: SUFFIXES = imp.get_suffixes() PY3_PRE_EXT = \ re.compile(r'\.cpython-{0}{1}(\.opt-[1-9])?'.format(*sys.version_info[:2])) # Because on the cloud drivers we do `from salt.cloud.libcloudfuncs import *` # which simplifies code readability, it adds some unsupported functions into # the driver's module scope. # We list un-supported functions here. These will be removed from the loaded. # TODO: remove the need for this cross-module code. Maybe use NotImplemented LIBCLOUD_FUNCS_NOT_SUPPORTED = ( 'parallels.avail_sizes', 'parallels.avail_locations', 'proxmox.avail_sizes', ) # Will be set to pyximport module at runtime if cython is enabled in config. pyximport = None def static_loader( opts, ext_type, tag, pack=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, filter_name=None, ): funcs = LazyLoader( _module_dirs( opts, ext_type, tag, int_type, ext_dirs, ext_type_dirs, base_path, ), opts, tag=tag, pack=pack, ) ret = {} funcs._load_all() if filter_name: funcs = FilterDictWrapper(funcs, filter_name) for key in funcs: ret[key] = funcs[key] return ret def _format_entrypoint_target(ep): ''' Makes a string describing the target of an EntryPoint object. Base strongly on EntryPoint.__str__(). ''' s = ep.module_name if ep.attrs: s += ':' + '.'.join(ep.attrs) return s def _module_dirs( opts, ext_type, tag=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, ): if tag is None: tag = ext_type sys_types = os.path.join(base_path or SALT_BASE_PATH, int_type or ext_type) ext_types = os.path.join(opts['extension_modules'], ext_type) ext_type_types = [] if ext_dirs: if ext_type_dirs is None: ext_type_dirs = '{0}_dirs'.format(tag) if ext_type_dirs in opts: ext_type_types.extend(opts[ext_type_dirs]) if HAS_PKG_RESOURCES and ext_type_dirs: for entry_point in pkg_resources.iter_entry_points('salt.loader', ext_type_dirs): try: loaded_entry_point = entry_point.load() for path in loaded_entry_point(): ext_type_types.append(path) except Exception as exc: log.error("Error getting module directories from %s: %s", _format_entrypoint_target(entry_point), exc) log.debug("Full backtrace for module directories error", exc_info=True) cli_module_dirs = [] # The dirs can be any module dir, or a in-tree _{ext_type} dir for _dir in opts.get('module_dirs', []): # Prepend to the list to match cli argument ordering maybe_dir = os.path.join(_dir, ext_type) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) continue maybe_dir = os.path.join(_dir, '_{0}'.format(ext_type)) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) return cli_module_dirs + ext_type_types + [ext_types, sys_types] def minion_mods( opts, context=None, utils=None, whitelist=None, initial_load=False, loaded_base_name=None, notify=False, static_modules=None, proxy=None): ''' Load execution modules Returns a dictionary of execution modules appropriate for the current system by evaluating the __virtual__() function in each module. :param dict opts: The Salt options dictionary :param dict context: A Salt context that should be made present inside generated modules in __context__ :param dict utils: Utility functions which should be made available to Salt modules in __utils__. See `utils_dirs` in salt.config for additional information about configuration. :param list whitelist: A list of modules which should be whitelisted. :param bool initial_load: Deprecated flag! Unused. :param str loaded_base_name: A string marker for the loaded base name. :param bool notify: Flag indicating that an event should be fired upon completion of module loading. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) __opts__['grains'] = __grains__ __utils__ = salt.loader.utils(__opts__) __salt__ = salt.loader.minion_mods(__opts__, utils=__utils__) __salt__['test.ping']() ''' # TODO Publish documentation for module whitelisting if not whitelist: whitelist = opts.get('whitelist_modules', None) ret = LazyLoader( _module_dirs(opts, 'modules', 'module'), opts, tag='module', pack={'__context__': context, '__utils__': utils, '__proxy__': proxy}, whitelist=whitelist, loaded_base_name=loaded_base_name, static_modules=static_modules, ) ret.pack['__salt__'] = ret # Load any provider overrides from the configuration file providers option # Note: Providers can be pkg, service, user or group - not to be confused # with cloud providers. providers = opts.get('providers', False) if providers and isinstance(providers, dict): for mod in providers: # sometimes providers opts is not to diverge modules but # for other configuration try: funcs = raw_mod(opts, providers[mod], ret) except TypeError: break else: if funcs: for func in funcs: f_key = '{0}{1}'.format(mod, func[func.rindex('.'):]) ret[f_key] = funcs[func] if notify: evt = salt.utils.event.get_event('minion', opts=opts, listen=False) evt.fire_event({'complete': True}, tag=salt.defaults.events.MINION_MOD_COMPLETE) return ret def raw_mod(opts, name, functions, mod='modules'): ''' Returns a single module loaded raw and bypassing the __virtual__ function .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') testmod = salt.loader.raw_mod(__opts__, 'test', None) testmod['test.ping']() ''' loader = LazyLoader( _module_dirs(opts, mod, 'module'), opts, tag='rawmodule', virtual_enable=False, pack={'__salt__': functions}, ) # if we don't have the module, return an empty dict if name not in loader.file_mapping: return {} loader._load_module(name) # load a single module (the one passed in) return dict(loader._dict) # return a copy of *just* the funcs for `name` def metaproxy(opts): ''' Return functions used in the meta proxy ''' return LazyLoader( _module_dirs(opts, 'metaproxy'), opts, tag='metaproxy' ) def matchers(opts): ''' Return the matcher services plugins ''' return LazyLoader( _module_dirs(opts, 'matchers'), opts, tag='matchers' ) def engines(opts, functions, runners, utils, proxy=None): ''' Return the master services plugins ''' pack = {'__salt__': functions, '__runners__': runners, '__proxy__': proxy, '__utils__': utils} return LazyLoader( _module_dirs(opts, 'engines'), opts, tag='engines', pack=pack, ) def proxy(opts, functions=None, returners=None, whitelist=None, utils=None): ''' Returns the proxy module for this salt-proxy-minion ''' ret = LazyLoader( _module_dirs(opts, 'proxy'), opts, tag='proxy', pack={'__salt__': functions, '__ret__': returners, '__utils__': utils}, ) ret.pack['__proxy__'] = ret return ret def returners(opts, functions, whitelist=None, context=None, proxy=None): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'returners', 'returner'), opts, tag='returner', whitelist=whitelist, pack={'__salt__': functions, '__context__': context, '__proxy__': proxy or {}}, ) def utils(opts, whitelist=None, context=None, proxy=proxy): ''' Returns the utility modules ''' return LazyLoader( _module_dirs(opts, 'utils', ext_type_dirs='utils_dirs'), opts, tag='utils', whitelist=whitelist, pack={'__context__': context, '__proxy__': proxy or {}}, ) def pillars(opts, functions, context=None): ''' Returns the pillars modules ''' ret = LazyLoader(_module_dirs(opts, 'pillar'), opts, tag='pillar', pack={'__salt__': functions, '__context__': context, '__utils__': utils(opts)}) ret.pack['__ext_pillar__'] = ret return FilterDictWrapper(ret, '.ext_pillar') def tops(opts): ''' Returns the tops modules ''' if 'master_tops' not in opts: return {} whitelist = list(opts['master_tops'].keys()) ret = LazyLoader( _module_dirs(opts, 'tops', 'top'), opts, tag='top', whitelist=whitelist, ) return FilterDictWrapper(ret, '.top') def wheels(opts, whitelist=None, context=None): ''' Returns the wheels modules ''' if context is None: context = {} return LazyLoader( _module_dirs(opts, 'wheel'), opts, tag='wheel', whitelist=whitelist, pack={'__context__': context}, ) def outputters(opts): ''' Returns the outputters modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only outputters present in the keyspace ''' ret = LazyLoader( _module_dirs(opts, 'output', ext_type_dirs='outputter_dirs'), opts, tag='output', ) wrapped_ret = FilterDictWrapper(ret, '.output') # TODO: this name seems terrible... __salt__ should always be execution mods ret.pack['__salt__'] = wrapped_ret return wrapped_ret def serializers(opts): ''' Returns the serializers modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only serializers present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'serializers'), opts, tag='serializers', ) def eauth_tokens(opts): ''' Returns the tokens modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only token backends present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'tokens'), opts, tag='tokens', ) def auth(opts, whitelist=None): ''' Returns the auth modules :param dict opts: The Salt options dictionary :returns: LazyLoader ''' return LazyLoader( _module_dirs(opts, 'auth'), opts, tag='auth', whitelist=whitelist, pack={'__salt__': minion_mods(opts)}, ) def fileserver(opts, backends): ''' Returns the file server modules ''' return LazyLoader(_module_dirs(opts, 'fileserver'), opts, tag='fileserver', whitelist=backends, pack={'__utils__': utils(opts)}) def thorium(opts, functions, runners): ''' Load the thorium runtime modules ''' pack = {'__salt__': functions, '__runner__': runners, '__context__': {}} ret = LazyLoader(_module_dirs(opts, 'thorium'), opts, tag='thorium', pack=pack) ret.pack['__thorium__'] = ret return ret def states(opts, functions, utils, serializers, whitelist=None, proxy=None, context=None): ''' Returns the state modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') statemods = salt.loader.states(__opts__, None, None) ''' if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'states'), opts, tag='states', pack={'__salt__': functions, '__proxy__': proxy or {}}, whitelist=whitelist, ) ret.pack['__states__'] = ret ret.pack['__utils__'] = utils ret.pack['__serializers__'] = serializers ret.pack['__context__'] = context return ret def beacons(opts, functions, context=None, proxy=None): ''' Load the beacon modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. ''' return LazyLoader( _module_dirs(opts, 'beacons'), opts, tag='beacons', pack={'__context__': context, '__salt__': functions, '__proxy__': proxy or {}}, virtual_funcs=[], ) def log_handlers(opts): ''' Returns the custom logging handler modules :param dict opts: The Salt options dictionary ''' ret = LazyLoader( _module_dirs( opts, 'log_handlers', int_type='handlers', base_path=os.path.join(SALT_BASE_PATH, 'log'), ), opts, tag='log_handlers', ) return FilterDictWrapper(ret, '.setup_handlers') def ssh_wrapper(opts, functions=None, context=None): ''' Returns the custom logging handler modules ''' return LazyLoader( _module_dirs( opts, 'wrapper', base_path=os.path.join(SALT_BASE_PATH, os.path.join('client', 'ssh')), ), opts, tag='wrapper', pack={ '__salt__': functions, '__grains__': opts.get('grains', {}), '__pillar__': opts.get('pillar', {}), '__context__': context, }, ) def render(opts, functions, states=None, proxy=None, context=None): ''' Returns the render modules ''' if context is None: context = {} pack = {'__salt__': functions, '__grains__': opts.get('grains', {}), '__context__': context} if states: pack['__states__'] = states pack['__proxy__'] = proxy or {} ret = LazyLoader( _module_dirs( opts, 'renderers', 'render', ext_type_dirs='render_dirs', ), opts, tag='render', pack=pack, ) rend = FilterDictWrapper(ret, '.render') if not check_render_pipe_str(opts['renderer'], rend, opts['renderer_blacklist'], opts['renderer_whitelist']): err = ('The renderer {0} is unavailable, this error is often because ' 'the needed software is unavailable'.format(opts['renderer'])) log.critical(err) raise LoaderError(err) return rend def grain_funcs(opts, proxy=None): ''' Returns the grain functions .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') grainfuncs = salt.loader.grain_funcs(__opts__) ''' ret = LazyLoader( _module_dirs( opts, 'grains', 'grain', ext_type_dirs='grains_dirs', ), opts, tag='grains', ) ret.pack['__utils__'] = utils(opts, proxy=proxy) return ret def _load_cached_grains(opts, cfn): ''' Returns the grains cached in cfn, or None if the cache is too old or is corrupted. ''' if not os.path.isfile(cfn): log.debug('Grains cache file does not exist.') return None grains_cache_age = int(time.time() - os.path.getmtime(cfn)) if grains_cache_age > opts.get('grains_cache_expiration', 300): log.debug( 'Grains cache last modified %s seconds ago and cache ' 'expiration is set to %s. Grains cache expired. ' 'Refreshing.', grains_cache_age, opts.get('grains_cache_expiration', 300) ) return None if opts.get('refresh_grains_cache', False): log.debug('refresh_grains_cache requested, Refreshing.') return None log.debug('Retrieving grains from cache') try: serial = salt.payload.Serial(opts) with salt.utils.files.fopen(cfn, 'rb') as fp_: cached_grains = salt.utils.data.decode(serial.load(fp_), preserve_tuples=True) if not cached_grains: log.debug('Cached grains are empty, cache might be corrupted. Refreshing.') return None return cached_grains except (IOError, OSError): return None def grains(opts, force_refresh=False, proxy=None): ''' Return the functions for the dynamic grains and the values for the static grains. Since grains are computed early in the startup process, grains functions do not have __salt__ or __proxy__ available. At proxy-minion startup, this function is called with the proxymodule LazyLoader object so grains functions can communicate with their controlled device. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) print __grains__['id'] ''' # Need to re-import salt.config, somehow it got lost when a minion is starting import salt.config # if we have no grains, lets try loading from disk (TODO: move to decorator?) cfn = os.path.join( opts['cachedir'], 'grains.cache.p' ) if not force_refresh and opts.get('grains_cache', False): cached_grains = _load_cached_grains(opts, cfn) if cached_grains: return cached_grains else: log.debug('Grains refresh requested. Refreshing grains.') if opts.get('skip_grains', False): return {} grains_deep_merge = opts.get('grains_deep_merge', False) is True if 'conf_file' in opts: pre_opts = {} pre_opts.update(salt.config.load_config( opts['conf_file'], 'SALT_MINION_CONFIG', salt.config.DEFAULT_MINION_OPTS['conf_file'] )) default_include = pre_opts.get( 'default_include', opts['default_include'] ) include = pre_opts.get('include', []) pre_opts.update(salt.config.include_config( default_include, opts['conf_file'], verbose=False )) pre_opts.update(salt.config.include_config( include, opts['conf_file'], verbose=True )) if 'grains' in pre_opts: opts['grains'] = pre_opts['grains'] else: opts['grains'] = {} else: opts['grains'] = {} grains_data = {} blist = opts.get('grains_blacklist', []) funcs = grain_funcs(opts, proxy=proxy) if force_refresh: # if we refresh, lets reload grain modules funcs.clear() # Run core grains for key in funcs: if not key.startswith('core.'): continue log.trace('Loading %s grain', key) ret = funcs[key]() if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) # Run the rest of the grains for key in funcs: if key.startswith('core.') or key == '_errors': continue try: # Grains are loaded too early to take advantage of the injected # __proxy__ variable. Pass an instance of that LazyLoader # here instead to grains functions if the grains functions take # one parameter. Then the grains can have access to the # proxymodule for retrieving information from the connected # device. log.trace('Loading %s grain', key) parameters = salt.utils.args.get_function_argspec(funcs[key]).args kwargs = {} if 'proxy' in parameters: kwargs['proxy'] = proxy if 'grains' in parameters: kwargs['grains'] = grains_data ret = funcs[key](**kwargs) except Exception: if salt.utils.platform.is_proxy(): log.info('The following CRITICAL message may not be an error; the proxy may not be completely established yet.') log.critical( 'Failed to load grains defined in grain file %s in ' 'function %s, error:\n', key, funcs[key], exc_info=True ) continue if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) if opts.get('proxy_merge_grains_in_module', True) and proxy: try: proxytype = proxy.opts['proxy']['proxytype'] if proxytype + '.grains' in proxy: if proxytype + '.initialized' in proxy and proxy[proxytype + '.initialized'](): try: proxytype = proxy.opts['proxy']['proxytype'] ret = proxy[proxytype + '.grains']() if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) except Exception: log.critical('Failed to run proxy\'s grains function!', exc_info=True ) except KeyError: pass grains_data.update(opts['grains']) # Write cache if enabled if opts.get('grains_cache', False): with salt.utils.files.set_umask(0o077): try: if salt.utils.platform.is_windows(): # Late import import salt.modules.cmdmod # Make sure cache file isn't read-only salt.modules.cmdmod._run_quiet('attrib -R "{0}"'.format(cfn)) with salt.utils.files.fopen(cfn, 'w+b') as fp_: try: serial = salt.payload.Serial(opts) serial.dump(grains_data, fp_) except TypeError as e: log.error('Failed to serialize grains cache: %s', e) raise # re-throw for cleanup except Exception as e: log.error('Unable to write to grains cache file %s: %s', cfn, e) # Based on the original exception, the file may or may not have been # created. If it was, we will remove it now, as the exception means # the serialized data is not to be trusted, no matter what the # exception is. if os.path.isfile(cfn): os.unlink(cfn) if grains_deep_merge: salt.utils.dictupdate.update(grains_data, opts['grains']) else: grains_data.update(opts['grains']) return salt.utils.data.decode(grains_data, preserve_tuples=True) # TODO: get rid of? Does anyone use this? You should use raw() instead def call(fun, **kwargs): ''' Directly call a function inside a loader directory ''' args = kwargs.get('args', []) dirs = kwargs.get('dirs', []) funcs = LazyLoader( [os.path.join(SALT_BASE_PATH, 'modules')] + dirs, None, tag='modules', virtual_enable=False, ) return funcs[fun](*args) def runner(opts, utils=None, context=None, whitelist=None): ''' Directly call a function inside a loader directory ''' if utils is None: utils = {} if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'runners', 'runner', ext_type_dirs='runner_dirs'), opts, tag='runners', pack={'__utils__': utils, '__context__': context}, whitelist=whitelist, ) # TODO: change from __salt__ to something else, we overload __salt__ too much ret.pack['__salt__'] = ret return ret def queues(opts): ''' Directly call a function inside a loader directory ''' return LazyLoader( _module_dirs(opts, 'queues', 'queue', ext_type_dirs='queue_dirs'), opts, tag='queues', ) def sdb(opts, functions=None, whitelist=None, utils=None): ''' Make a very small database call ''' if utils is None: utils = {} return LazyLoader( _module_dirs(opts, 'sdb'), opts, tag='sdb', pack={ '__sdb__': functions, '__opts__': opts, '__utils__': utils, '__salt__': minion_mods(opts, utils), }, whitelist=whitelist, ) def pkgdb(opts): ''' Return modules for SPM's package database .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgdb', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgdb' ) def pkgfiles(opts): ''' Return modules for SPM's file handling .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgfiles', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgfiles' ) def clouds(opts): ''' Return the cloud functions ''' # Let's bring __active_provider_name__, defaulting to None, to all cloud # drivers. This will get temporarily updated/overridden with a context # manager when needed. functions = LazyLoader( _module_dirs(opts, 'clouds', 'cloud', base_path=os.path.join(SALT_BASE_PATH, 'cloud'), int_type='clouds'), opts, tag='clouds', pack={'__utils__': salt.loader.utils(opts), '__active_provider_name__': None}, ) for funcname in LIBCLOUD_FUNCS_NOT_SUPPORTED: log.trace( '\'%s\' has been marked as not supported. Removing from the ' 'list of supported cloud functions', funcname ) functions.pop(funcname, None) return functions def netapi(opts): ''' Return the network api functions ''' return LazyLoader( _module_dirs(opts, 'netapi'), opts, tag='netapi', ) def executors(opts, functions=None, context=None, proxy=None): ''' Returns the executor modules ''' executors = LazyLoader( _module_dirs(opts, 'executors', 'executor'), opts, tag='executor', pack={'__salt__': functions, '__context__': context or {}, '__proxy__': proxy or {}}, ) executors.pack['__executors__'] = executors return executors def cache(opts, serial): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'cache', 'cache'), opts, tag='cache', pack={'__opts__': opts, '__context__': {'serial': serial}}, ) def _generate_module(name): if name in sys.modules: return code = "'''Salt loaded {0} parent module'''".format(name.split('.')[-1]) # ModuleType can't accept a unicode type on PY2 module = types.ModuleType(str(name)) # future lint: disable=blacklisted-function exec(code, module.__dict__) sys.modules[name] = module def _mod_type(module_path): if module_path.startswith(SALT_BASE_PATH): return 'int' return 'ext' def _inject_into_mod(mod, name, value, force_lock=False): ''' Inject a variable into a module. This is used to inject "globals" like ``__salt__``, ``__pillar``, or ``grains``. Instead of injecting the value directly, a ``ThreadLocalProxy`` is created. If such a proxy is already present under the specified name, it is updated with the new value. This update only affects the current thread, so that the same name can refer to different values depending on the thread of execution. This is important for data that is not truly global. For example, pillar data might be dynamically overriden through function parameters and thus the actual values available in pillar might depend on the thread that is calling a module. mod: module object into which the value is going to be injected. name: name of the variable that is injected into the module. value: value that is injected into the variable. The value is not injected directly, but instead set as the new reference of the proxy that has been created for the variable. force_lock: whether the lock should be acquired before checking whether a proxy object for the specified name has already been injected into the module. If ``False`` (the default), this function checks for the module's variable without acquiring the lock and only acquires the lock if a new proxy has to be created and injected. ''' old_value = getattr(mod, name, None) # We use a double-checked locking scheme in order to avoid taking the lock # when a proxy object has already been injected. # In most programming languages, double-checked locking is considered # unsafe when used without explicit memory barriers because one might read # an uninitialized value. In CPython it is safe due to the global # interpreter lock (GIL). In Python implementations that do not have the # GIL, it could be unsafe, but at least Jython also guarantees that (for # Python objects) memory is not corrupted when writing and reading without # explicit synchronization # (http://www.jython.org/jythonbook/en/1.0/Concurrency.html). # Please note that in order to make this code safe in a runtime environment # that does not make this guarantees, it is not sufficient. The # ThreadLocalProxy must also be created with fallback_to_shared set to # False or a lock must be added to the ThreadLocalProxy. if force_lock: with _inject_into_mod.lock: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: setattr(mod, name, ThreadLocalProxy(value, True)) else: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: _inject_into_mod(mod, name, value, True) # Lock used when injecting globals. This is needed to avoid a race condition # when two threads try to load the same module concurrently. This must be # outside the loader because there might be more than one loader for the same # namespace. _inject_into_mod.lock = threading.RLock() # TODO: move somewhere else? class FilterDictWrapper(MutableMapping): ''' Create a dict which wraps another dict with a specific key suffix on get This is to replace "filter_load" ''' def __init__(self, d, suffix): self._dict = d self.suffix = suffix def __setitem__(self, key, val): self._dict[key] = val def __delitem__(self, key): del self._dict[key] def __getitem__(self, key): return self._dict[key + self.suffix] def __len__(self): return len(self._dict) def __iter__(self): for key in self._dict: if key.endswith(self.suffix): yield key.replace(self.suffix, '') class LazyLoader(salt.utils.lazy.LazyDict): ''' A pseduo-dictionary which has a set of keys which are the name of the module and function, delimited by a dot. When the value of the key is accessed, the function is then loaded from disk and into memory. .. note:: Iterating over keys will cause all modules to be loaded. :param list module_dirs: A list of directories on disk to search for modules :param dict opts: The salt options dictionary. :param str tag: The tag for the type of module to load :param func mod_type_check: A function which can be used to verify files :param dict pack: A dictionary of function to be packed into modules as they are loaded :param list whitelist: A list of modules to whitelist :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules. :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality. If not true, the module will not load. :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values are function references themselves which are loaded on-demand. # TODO: - move modules_max_memory into here - singletons (per tag) ''' mod_dict_class = salt.utils.odict.OrderedDict def __init__(self, module_dirs, opts=None, tag='module', loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, proxy=None, virtual_funcs=None, ): # pylint: disable=W0231 ''' In pack, if any of the values are None they will be replaced with an empty context-specific dict ''' self.inject_globals = {} self.pack = {} if pack is None else pack if opts is None: opts = {} threadsafety = not opts.get('multiprocessing') self.context_dict = salt.utils.context.ContextDict(threadsafe=threadsafety) self.opts = self.__prep_mod_opts(opts) self.module_dirs = module_dirs self.tag = tag self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME self.mod_type_check = mod_type_check or _mod_type if '__context__' not in self.pack: self.pack['__context__'] = None for k, v in six.iteritems(self.pack): if v is None: # if the value of a pack is None, lets make an empty dict value = self.context_dict.get(k, {}) if isinstance(value, ThreadLocalProxy): value = ThreadLocalProxy.unproxy(value) self.context_dict[k] = value self.pack[k] = salt.utils.context.NamespacedDictWrapper(self.context_dict, k) self.whitelist = whitelist self.virtual_enable = virtual_enable self.initial_load = True # names of modules that we don't have (errors, __virtual__, etc.) self.missing_modules = {} # mapping of name -> error self.loaded_modules = {} # mapping of module_name -> dict_of_functions self.loaded_files = set() # TODO: just remove them from file_mapping? self.static_modules = static_modules if static_modules else [] if virtual_funcs is None: virtual_funcs = [] self.virtual_funcs = virtual_funcs self.disabled = set( self.opts.get( 'disable_{0}{1}'.format( self.tag, '' if self.tag[-1] == 's' else 's' ), [] ) ) # A map of suffix to description for imp self.suffix_map = {} # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [''] for (suffix, mode, kind) in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) self._lock = threading.RLock() self._refresh_file_mapping() super(LazyLoader, self).__init__() # late init the lazy loader # create all of the import namespaces _generate_module('{0}.int'.format(self.loaded_base_name)) _generate_module('{0}.int.{1}'.format(self.loaded_base_name, tag)) _generate_module('{0}.ext'.format(self.loaded_base_name)) _generate_module('{0}.ext.{1}'.format(self.loaded_base_name, tag)) def __getitem__(self, item): ''' Override the __getitem__ in order to decorate the returned function if we need to last-minute inject globals ''' func = super(LazyLoader, self).__getitem__(item) if self.inject_globals: return global_injector_decorator(self.inject_globals)(func) else: return func def __getattr__(self, mod_name): ''' Allow for "direct" attribute access-- this allows jinja templates to access things like `salt.test.ping()` ''' if mod_name in ('__getstate__', '__setstate__'): return object.__getattribute__(self, mod_name) # if we have an attribute named that, lets return it. try: return object.__getattr__(self, mod_name) # pylint: disable=no-member except AttributeError: pass # otherwise we assume its jinja template access if mod_name not in self.loaded_modules and not self.loaded: for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and mod_name in self.loaded_modules: break if mod_name in self.loaded_modules: return self.loaded_modules[mod_name] else: raise AttributeError(mod_name) def missing_fun_string(self, function_name): ''' Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ''' mod_name = function_name.split('.')[0] if mod_name in self.loaded_modules: return '\'{0}\' is not available.'.format(function_name) else: try: reason = self.missing_modules[mod_name] except KeyError: return '\'{0}\' is not available.'.format(function_name) else: if reason is not None: return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason) else: return '\'{0}\' __virtual__ returned False'.format(mod_name) def _refresh_file_mapping(self): ''' refresh the mapping of the FS on disk ''' # map of suffix to description for imp if self.opts.get('cython_enable', True) is True: try: global pyximport pyximport = __import__('pyximport') # pylint: disable=import-error pyximport.install() # add to suffix_map so file_mapping will pick it up self.suffix_map['.pyx'] = tuple() except ImportError: log.info('Cython is enabled in the options but not present ' 'in the system path. Skipping Cython modules.') # Allow for zipimport of modules if self.opts.get('enable_zip_modules', True) is True: self.suffix_map['.zip'] = tuple() # allow for module dirs if USE_IMPORTLIB: self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY) else: self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY) # create mapping of filename (without suffix) to (path, suffix) # The files are added in order of priority, so order *must* be retained. self.file_mapping = salt.utils.odict.OrderedDict() opt_match = [] def _replace_pre_ext(obj): ''' Hack so we can get the optimization level that we replaced (if any) out of the re.sub call below. We use a list here because it is a persistent data structure that we will be able to access after re.sub is called. ''' opt_match.append(obj) return '' for mod_dir in self.module_dirs: try: # Make sure we have a sorted listdir in order to have # expectable override results files = sorted( x for x in os.listdir(mod_dir) if x != '__pycache__' ) except OSError: continue # Next mod_dir if six.PY3: try: pycache_files = [ os.path.join('__pycache__', x) for x in sorted(os.listdir(os.path.join(mod_dir, '__pycache__'))) ] except OSError: pass else: files.extend(pycache_files) for filename in files: try: dirname, basename = os.path.split(filename) if basename.startswith('_'): # skip private modules # log messages omitted for obviousness continue # Next filename f_noext, ext = os.path.splitext(basename) if six.PY3: f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext) try: opt_level = int( opt_match.pop().group(1).rsplit('-', 1)[-1] ) except (AttributeError, IndexError, ValueError): # No regex match or no optimization level matched opt_level = 0 try: opt_index = self.opts['optimization_order'].index(opt_level) except KeyError: log.trace( 'Disallowed optimization level %d for module ' 'name \'%s\', skipping. Add %d to the ' '\'optimization_order\' config option if you ' 'do not want to ignore this optimization ' 'level.', opt_level, f_noext, opt_level ) continue else: # Optimization level not reflected in filename on PY2 opt_index = 0 # make sure it is a suffix we support if ext not in self.suffix_map: continue # Next filename if f_noext in self.disabled: log.trace( 'Skipping %s, it is disabled by configuration', filename ) continue # Next filename fpath = os.path.join(mod_dir, filename) # if its a directory, lets allow us to load that if ext == '': # is there something __init__? subfiles = os.listdir(fpath) for suffix in self.suffix_order: if '' == suffix: continue # Next suffix (__init__ must have a suffix) init_file = '__init__{0}'.format(suffix) if init_file in subfiles: break else: continue # Next filename try: curr_ext = self.file_mapping[f_noext][1] curr_opt_index = self.file_mapping[f_noext][2] except KeyError: pass else: if '' in (curr_ext, ext) and curr_ext != ext: log.error( 'Module/package collision: \'%s\' and \'%s\'', fpath, self.file_mapping[f_noext][0] ) if six.PY3 and ext == '.pyc' and curr_ext == '.pyc': # Check the optimization level if opt_index >= curr_opt_index: # Module name match, but a higher-priority # optimization level was already matched, skipping. continue elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext): # Match found but a higher-priorty match already # exists, so skip this. continue if six.PY3 and not dirname and ext == '.pyc': # On Python 3, we should only load .pyc files from the # __pycache__ subdirectory (i.e. when dirname is not an # empty string). continue # Made it this far - add it self.file_mapping[f_noext] = (fpath, ext, opt_index) except OSError: continue for smod in self.static_modules: f_noext = smod.split('.')[-1] self.file_mapping[f_noext] = (smod, '.o', 0) def clear(self): ''' Clear the dict ''' with self._lock: super(LazyLoader, self).clear() # clear the lazy loader self.loaded_files = set() self.missing_modules = {} self.loaded_modules = {} # if we have been loaded before, lets clear the file mapping since # we obviously want a re-do if hasattr(self, 'opts'): self._refresh_file_mapping() self.initial_load = False def __prep_mod_opts(self, opts): ''' Strip out of the opts any logger instance ''' if '__grains__' not in self.pack: grains = opts.get('grains', {}) if isinstance(grains, ThreadLocalProxy): grains = ThreadLocalProxy.unproxy(grains) self.context_dict['grains'] = grains self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains') if '__pillar__' not in self.pack: pillar = opts.get('pillar', {}) if isinstance(pillar, ThreadLocalProxy): pillar = ThreadLocalProxy.unproxy(pillar) self.context_dict['pillar'] = pillar self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar') mod_opts = {} for key, val in list(opts.items()): if key == 'logger': continue mod_opts[key] = val return mod_opts def _iter_files(self, mod_name): ''' Iterate over all file_mapping files in order of closeness to mod_name ''' # do we have an exact match? if mod_name in self.file_mapping: yield mod_name # do we have a partial match? for k in self.file_mapping: if mod_name in k: yield k # anyone else? Bueller? for k in self.file_mapping: if mod_name not in k: yield k def _reload_submodules(self, mod): submodules = ( getattr(mod, sname) for sname in dir(mod) if isinstance(getattr(mod, sname), mod.__class__) ) # reload only custom "sub"modules for submodule in submodules: # it is a submodule if the name is in a namespace under mod if submodule.__name__.startswith(mod.__name__ + '.'): reload_module(submodule) self._reload_submodules(submodule) def _load_module(self, name): mod = None fpath, suffix = self.file_mapping[name][:2] self.loaded_files.add(name) fpath_dirname = os.path.dirname(fpath) try: sys.path.append(fpath_dirname) if suffix == '.pyx': mod = pyximport.load_module(name, fpath, tempfile.gettempdir()) elif suffix == '.o': top_mod = __import__(fpath, globals(), locals(), []) comps = fpath.split('.') if len(comps) < 2: mod = top_mod else: mod = top_mod for subname in comps[1:]: mod = getattr(mod, subname) elif suffix == '.zip': mod = zipimporter(fpath).load_module(name) else: desc = self.suffix_map[suffix] # if it is a directory, we don't open a file try: mod_namespace = '.'.join(( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name)) except TypeError: mod_namespace = '{0}.{1}.{2}.{3}'.format( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name) if suffix == '': if USE_IMPORTLIB: # pylint: disable=no-member # Package directory, look for __init__ loader_details = [ (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES), (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES), (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), ] file_finder = importlib.machinery.FileFinder( fpath_dirname, *loader_details ) spec = file_finder.find_spec(mod_namespace) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: mod = imp.load_module(mod_namespace, None, fpath, desc) # reload all submodules if necessary if not self.initial_load: self._reload_submodules(mod) else: if USE_IMPORTLIB: # pylint: disable=no-member loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath) spec = importlib.util.spec_from_file_location( mod_namespace, fpath, loader=loader ) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() #mod = importlib.util.module_from_spec(spec) #spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: with salt.utils.files.fopen(fpath, desc[1]) as fn_: mod = imp.load_module(mod_namespace, fn_, fpath, desc) except IOError: raise except ImportError as exc: if 'magic number' in six.text_type(exc): error_msg = 'Failed to import {0} {1}. Bad magic number. If migrating from Python2 to Python3, remove all .pyc files and try again.'.format(self.tag, name) log.warning(error_msg) self.missing_modules[name] = error_msg log.debug( 'Failed to import %s %s:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = exc return False except Exception as error: log.error( 'Failed to import %s %s, this is due most likely to a ' 'syntax error:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False except SystemExit as error: try: fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1] except Exception: pass else: tgt_fn = os.path.join('salt', 'utils', 'process.py') if fn_.endswith(tgt_fn) and '_handle_signals' in caller: # Race conditon, SIGTERM or SIGINT received while loader # was in process of loading a module. Call sys.exit to # ensure that the process is killed. sys.exit(salt.defaults.exitcodes.EX_OK) log.error( 'Failed to import %s %s as the module called exit()\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False finally: sys.path.remove(fpath_dirname) if hasattr(mod, '__opts__'): mod.__opts__.update(self.opts) else: mod.__opts__ = self.opts # pack whatever other globals we were asked to for p_name, p_value in six.iteritems(self.pack): _inject_into_mod(mod, p_name, p_value) module_name = mod.__name__.rsplit('.', 1)[-1] # Call a module's initialization method if it exists module_init = getattr(mod, '__init__', None) if inspect.isfunction(module_init): try: module_init(self.opts) except TypeError as e: log.error(e) except Exception: err_string = '__init__ failed' log.debug( 'Error loading %s.%s: %s', self.tag, module_name, err_string, exc_info=True ) self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False # if virtual modules are enabled, we need to look for the # __virtual__() function inside that module and run it. if self.virtual_enable: virtual_funcs_to_process = ['__virtual__'] + self.virtual_funcs for virtual_func in virtual_funcs_to_process: virtual_ret, module_name, virtual_err, virtual_aliases = \ self._process_virtual(mod, module_name, virtual_func) if virtual_err is not None: log.trace( 'Error loading %s.%s: %s', self.tag, module_name, virtual_err ) # if _process_virtual returned a non-True value then we are # supposed to not process this module if virtual_ret is not True and module_name not in self.missing_modules: # If a module has information about why it could not be loaded, record it self.missing_modules[module_name] = virtual_err self.missing_modules[name] = virtual_err return False else: virtual_aliases = () # If this is a proxy minion then MOST modules cannot work. Therefore, require that # any module that does work with salt-proxy-minion define __proxyenabled__ as a list # containing the names of the proxy types that the module supports. # # Render modules and state modules are OK though if 'proxy' in self.opts: if self.tag in ['grains', 'proxy']: if not hasattr(mod, '__proxyenabled__') or \ (self.opts['proxy']['proxytype'] not in mod.__proxyenabled__ and '*' not in mod.__proxyenabled__): err_string = 'not a proxy_minion enabled module' self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False if getattr(mod, '__load__', False) is not False: log.info( 'The functions from module \'%s\' are being loaded from the ' 'provided __load__ attribute', module_name ) # If we had another module by the same virtual name, we should put any # new functions under the existing dictionary. mod_names = [module_name] + list(virtual_aliases) mod_dict = dict(( (x, self.loaded_modules.get(x, self.mod_dict_class())) for x in mod_names )) for attr in getattr(mod, '__load__', dir(mod)): if attr.startswith('_') and attr != '__call__': # private functions are skipped, # except __call__ which is default entrance # for multi-function batch-like state syntax continue func = getattr(mod, attr) if not inspect.isfunction(func) and not isinstance(func, functools.partial): # Not a function!? Skip it!!! continue # Let's get the function name. # If the module has the __func_alias__ attribute, it must be a # dictionary mapping in the form of(key -> value): # <real-func-name> -> <desired-func-name> # # It default's of course to the found callable attribute name # if no alias is defined. funcname = getattr(mod, '__func_alias__', {}).get(attr, attr) for tgt_mod in mod_names: try: full_funcname = '.'.join((tgt_mod, funcname)) except TypeError: full_funcname = '{0}.{1}'.format(tgt_mod, funcname) # Save many references for lookups # Careful not to overwrite existing (higher priority) functions if full_funcname not in self._dict: self._dict[full_funcname] = func if funcname not in mod_dict[tgt_mod]: setattr(mod_dict[tgt_mod], funcname, func) mod_dict[tgt_mod][funcname] = func self._apply_outputter(func, mod) # enforce depends try: Depends.enforce_dependencies(self._dict, self.tag) except RuntimeError as exc: log.info( 'Depends.enforce_dependencies() failed for the following ' 'reason: %s', exc ) for tgt_mod in mod_names: self.loaded_modules[tgt_mod] = mod_dict[tgt_mod] return True def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise KeyError('The key \'{0}\' should contain a \'.\''.format(key)) mod_name, _ = key.split('.', 1) with self._lock: # It is possible that the key is in the dictionary after # acquiring the lock due to another thread loading it. if mod_name in self.missing_modules or key in self._dict: return True # if the modulename isn't in the whitelist, don't bother if self.whitelist and mod_name not in self.whitelist: log.error( 'Failed to load function %s because its module (%s) is ' 'not in the whitelist: %s', key, mod_name, self.whitelist ) raise KeyError(key) def _inner_load(mod_name): for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and key in self._dict: return True return False # try to load the module ret = None reloaded = False # re-scan up to once, IOErrors or a failed load cause re-scans of the # filesystem while True: try: ret = _inner_load(mod_name) if not reloaded and ret is not True: self._refresh_file_mapping() reloaded = True continue break except IOError: if not reloaded: self._refresh_file_mapping() reloaded = True continue return ret def _load_all(self): ''' Load all of them ''' with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True def reload_modules(self): with self._lock: self.loaded_files = set() self._load_all() def _apply_outputter(self, func, mod): ''' Apply the __outputter__ variable to the functions ''' if hasattr(mod, '__outputter__'): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__] def _process_virtual(self, mod, module_name, virtual_func='__virtual__'): ''' Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1] ''' # The __virtual__ function will return either a True or False value. # If it returns a True value it can also set a module level attribute # named __virtualname__ with the name that the module should be # referred to as. # # This allows us to have things like the pkg module working on all # platforms under the name 'pkg'. It also allows for modules like # augeas_cfg to be referred to as 'augeas', which would otherwise have # namespace collisions. And finally it allows modules to return False # if they are not intended to run on the given platform or are missing # dependencies. virtual_aliases = getattr(mod, '__virtual_aliases__', tuple()) try: error_reason = None if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__): try: start = time.time() virtual = getattr(mod, virtual_func)() if isinstance(virtual, tuple): error_reason = virtual[1] virtual = virtual[0] if self.opts.get('virtual_timer', False): end = time.time() - start msg = 'Virtual function took {0} seconds for {1}'.format( end, module_name) log.warning(msg) except Exception as exc: error_reason = ( 'Exception raised when processing __virtual__ function' ' for {0}. Module will not be loaded: {1}'.format( mod.__name__, exc)) log.error(error_reason, exc_info_on_loglevel=logging.DEBUG) virtual = None # Get the module's virtual name virtualname = getattr(mod, '__virtualname__', virtual) if not virtual: # if __virtual__() evaluates to False then the module # wasn't meant for this platform or it's not supposed to # load for some other reason. # Some modules might accidentally return None and are # improperly loaded if virtual is None: log.warning( '%s.__virtual__() is wrongly returning `None`. ' 'It should either return `True`, `False` or a new ' 'name. If you\'re the developer of the module ' '\'%s\', please fix this.', mod.__name__, module_name ) return (False, module_name, error_reason, virtual_aliases) # At this point, __virtual__ did not return a # boolean value, let's check for deprecated usage # or module renames if virtual is not True and module_name != virtual: # The module is renaming itself. Updating the module name # with the new name log.trace('Loaded %s as virtual %s', module_name, virtual) if virtualname != virtual: # The __virtualname__ attribute does not match what's # being returned by the __virtual__() function. This # should be considered an error. log.error( 'The module \'%s\' is showing some bad usage. Its ' '__virtualname__ attribute is set to \'%s\' yet the ' '__virtual__() function is returning \'%s\'. These ' 'values should match!', mod.__name__, virtualname, virtual ) module_name = virtualname # If the __virtual__ function returns True and __virtualname__ # is set then use it elif virtual is True and virtualname != module_name: if virtualname is not True: module_name = virtualname except KeyError: # Key errors come out of the virtual function when passing # in incomplete grains sets, these can be safely ignored # and logged to debug, still, it includes the traceback to # help debugging. log.debug('KeyError when loading %s', module_name, exc_info=True) except Exception: # If the module throws an exception during __virtual__() # then log the information and continue to the next. log.error( 'Failed to read the virtual function for %s: %s', self.tag, module_name, exc_info=True ) return (False, module_name, error_reason, virtual_aliases) return (True, module_name, None, virtual_aliases) def global_injector_decorator(inject_globals): ''' Decorator used by the LazyLoader to inject globals into a function at execute time. globals Dictionary with global variables to inject ''' def inner_decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): with salt.utils.context.func_globals_inject(f, **inject_globals): return f(*args, **kwargs) return wrapper return inner_decorator
saltstack/salt
salt/loader.py
thorium
python
def thorium(opts, functions, runners): ''' Load the thorium runtime modules ''' pack = {'__salt__': functions, '__runner__': runners, '__context__': {}} ret = LazyLoader(_module_dirs(opts, 'thorium'), opts, tag='thorium', pack=pack) ret.pack['__thorium__'] = ret return ret
Load the thorium runtime modules
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L531-L541
null
# -*- coding: utf-8 -*- ''' The Salt loader is the core to Salt's plugin system, the loader scans directories for python loadable code and organizes the code into the plugin interfaces used by Salt. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import sys import time import logging import inspect import tempfile import threading import functools import threading import traceback import types from zipimport import zipimporter # Import salt libs import salt.config import salt.defaults.events import salt.defaults.exitcodes import salt.syspaths import salt.utils.args import salt.utils.context import salt.utils.data import salt.utils.dictupdate import salt.utils.event import salt.utils.files import salt.utils.lazy import salt.utils.odict import salt.utils.platform import salt.utils.versions import salt.utils.stringutils from salt.exceptions import LoaderError from salt.template import check_render_pipe_str from salt.utils.decorators import Depends from salt.utils.thread_local_proxy import ThreadLocalProxy # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import reload_module if sys.version_info[:2] >= (3, 5): import importlib.machinery # pylint: disable=no-name-in-module,import-error import importlib.util # pylint: disable=no-name-in-module,import-error USE_IMPORTLIB = True else: import imp USE_IMPORTLIB = False try: from collections.abc import MutableMapping except ImportError: from collections import MutableMapping try: import pkg_resources HAS_PKG_RESOURCES = True except ImportError: HAS_PKG_RESOURCES = False log = logging.getLogger(__name__) SALT_BASE_PATH = os.path.abspath(salt.syspaths.INSTALL_DIR) LOADED_BASE_NAME = 'salt.loaded' if USE_IMPORTLIB: # pylint: disable=no-member MODULE_KIND_SOURCE = 1 MODULE_KIND_COMPILED = 2 MODULE_KIND_EXTENSION = 3 MODULE_KIND_PKG_DIRECTORY = 5 SUFFIXES = [] for suffix in importlib.machinery.EXTENSION_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_EXTENSION)) for suffix in importlib.machinery.SOURCE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_SOURCE)) for suffix in importlib.machinery.BYTECODE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_COMPILED)) MODULE_KIND_MAP = { MODULE_KIND_SOURCE: importlib.machinery.SourceFileLoader, MODULE_KIND_COMPILED: importlib.machinery.SourcelessFileLoader, MODULE_KIND_EXTENSION: importlib.machinery.ExtensionFileLoader } # pylint: enable=no-member else: SUFFIXES = imp.get_suffixes() PY3_PRE_EXT = \ re.compile(r'\.cpython-{0}{1}(\.opt-[1-9])?'.format(*sys.version_info[:2])) # Because on the cloud drivers we do `from salt.cloud.libcloudfuncs import *` # which simplifies code readability, it adds some unsupported functions into # the driver's module scope. # We list un-supported functions here. These will be removed from the loaded. # TODO: remove the need for this cross-module code. Maybe use NotImplemented LIBCLOUD_FUNCS_NOT_SUPPORTED = ( 'parallels.avail_sizes', 'parallels.avail_locations', 'proxmox.avail_sizes', ) # Will be set to pyximport module at runtime if cython is enabled in config. pyximport = None def static_loader( opts, ext_type, tag, pack=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, filter_name=None, ): funcs = LazyLoader( _module_dirs( opts, ext_type, tag, int_type, ext_dirs, ext_type_dirs, base_path, ), opts, tag=tag, pack=pack, ) ret = {} funcs._load_all() if filter_name: funcs = FilterDictWrapper(funcs, filter_name) for key in funcs: ret[key] = funcs[key] return ret def _format_entrypoint_target(ep): ''' Makes a string describing the target of an EntryPoint object. Base strongly on EntryPoint.__str__(). ''' s = ep.module_name if ep.attrs: s += ':' + '.'.join(ep.attrs) return s def _module_dirs( opts, ext_type, tag=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, ): if tag is None: tag = ext_type sys_types = os.path.join(base_path or SALT_BASE_PATH, int_type or ext_type) ext_types = os.path.join(opts['extension_modules'], ext_type) ext_type_types = [] if ext_dirs: if ext_type_dirs is None: ext_type_dirs = '{0}_dirs'.format(tag) if ext_type_dirs in opts: ext_type_types.extend(opts[ext_type_dirs]) if HAS_PKG_RESOURCES and ext_type_dirs: for entry_point in pkg_resources.iter_entry_points('salt.loader', ext_type_dirs): try: loaded_entry_point = entry_point.load() for path in loaded_entry_point(): ext_type_types.append(path) except Exception as exc: log.error("Error getting module directories from %s: %s", _format_entrypoint_target(entry_point), exc) log.debug("Full backtrace for module directories error", exc_info=True) cli_module_dirs = [] # The dirs can be any module dir, or a in-tree _{ext_type} dir for _dir in opts.get('module_dirs', []): # Prepend to the list to match cli argument ordering maybe_dir = os.path.join(_dir, ext_type) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) continue maybe_dir = os.path.join(_dir, '_{0}'.format(ext_type)) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) return cli_module_dirs + ext_type_types + [ext_types, sys_types] def minion_mods( opts, context=None, utils=None, whitelist=None, initial_load=False, loaded_base_name=None, notify=False, static_modules=None, proxy=None): ''' Load execution modules Returns a dictionary of execution modules appropriate for the current system by evaluating the __virtual__() function in each module. :param dict opts: The Salt options dictionary :param dict context: A Salt context that should be made present inside generated modules in __context__ :param dict utils: Utility functions which should be made available to Salt modules in __utils__. See `utils_dirs` in salt.config for additional information about configuration. :param list whitelist: A list of modules which should be whitelisted. :param bool initial_load: Deprecated flag! Unused. :param str loaded_base_name: A string marker for the loaded base name. :param bool notify: Flag indicating that an event should be fired upon completion of module loading. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) __opts__['grains'] = __grains__ __utils__ = salt.loader.utils(__opts__) __salt__ = salt.loader.minion_mods(__opts__, utils=__utils__) __salt__['test.ping']() ''' # TODO Publish documentation for module whitelisting if not whitelist: whitelist = opts.get('whitelist_modules', None) ret = LazyLoader( _module_dirs(opts, 'modules', 'module'), opts, tag='module', pack={'__context__': context, '__utils__': utils, '__proxy__': proxy}, whitelist=whitelist, loaded_base_name=loaded_base_name, static_modules=static_modules, ) ret.pack['__salt__'] = ret # Load any provider overrides from the configuration file providers option # Note: Providers can be pkg, service, user or group - not to be confused # with cloud providers. providers = opts.get('providers', False) if providers and isinstance(providers, dict): for mod in providers: # sometimes providers opts is not to diverge modules but # for other configuration try: funcs = raw_mod(opts, providers[mod], ret) except TypeError: break else: if funcs: for func in funcs: f_key = '{0}{1}'.format(mod, func[func.rindex('.'):]) ret[f_key] = funcs[func] if notify: evt = salt.utils.event.get_event('minion', opts=opts, listen=False) evt.fire_event({'complete': True}, tag=salt.defaults.events.MINION_MOD_COMPLETE) return ret def raw_mod(opts, name, functions, mod='modules'): ''' Returns a single module loaded raw and bypassing the __virtual__ function .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') testmod = salt.loader.raw_mod(__opts__, 'test', None) testmod['test.ping']() ''' loader = LazyLoader( _module_dirs(opts, mod, 'module'), opts, tag='rawmodule', virtual_enable=False, pack={'__salt__': functions}, ) # if we don't have the module, return an empty dict if name not in loader.file_mapping: return {} loader._load_module(name) # load a single module (the one passed in) return dict(loader._dict) # return a copy of *just* the funcs for `name` def metaproxy(opts): ''' Return functions used in the meta proxy ''' return LazyLoader( _module_dirs(opts, 'metaproxy'), opts, tag='metaproxy' ) def matchers(opts): ''' Return the matcher services plugins ''' return LazyLoader( _module_dirs(opts, 'matchers'), opts, tag='matchers' ) def engines(opts, functions, runners, utils, proxy=None): ''' Return the master services plugins ''' pack = {'__salt__': functions, '__runners__': runners, '__proxy__': proxy, '__utils__': utils} return LazyLoader( _module_dirs(opts, 'engines'), opts, tag='engines', pack=pack, ) def proxy(opts, functions=None, returners=None, whitelist=None, utils=None): ''' Returns the proxy module for this salt-proxy-minion ''' ret = LazyLoader( _module_dirs(opts, 'proxy'), opts, tag='proxy', pack={'__salt__': functions, '__ret__': returners, '__utils__': utils}, ) ret.pack['__proxy__'] = ret return ret def returners(opts, functions, whitelist=None, context=None, proxy=None): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'returners', 'returner'), opts, tag='returner', whitelist=whitelist, pack={'__salt__': functions, '__context__': context, '__proxy__': proxy or {}}, ) def utils(opts, whitelist=None, context=None, proxy=proxy): ''' Returns the utility modules ''' return LazyLoader( _module_dirs(opts, 'utils', ext_type_dirs='utils_dirs'), opts, tag='utils', whitelist=whitelist, pack={'__context__': context, '__proxy__': proxy or {}}, ) def pillars(opts, functions, context=None): ''' Returns the pillars modules ''' ret = LazyLoader(_module_dirs(opts, 'pillar'), opts, tag='pillar', pack={'__salt__': functions, '__context__': context, '__utils__': utils(opts)}) ret.pack['__ext_pillar__'] = ret return FilterDictWrapper(ret, '.ext_pillar') def tops(opts): ''' Returns the tops modules ''' if 'master_tops' not in opts: return {} whitelist = list(opts['master_tops'].keys()) ret = LazyLoader( _module_dirs(opts, 'tops', 'top'), opts, tag='top', whitelist=whitelist, ) return FilterDictWrapper(ret, '.top') def wheels(opts, whitelist=None, context=None): ''' Returns the wheels modules ''' if context is None: context = {} return LazyLoader( _module_dirs(opts, 'wheel'), opts, tag='wheel', whitelist=whitelist, pack={'__context__': context}, ) def outputters(opts): ''' Returns the outputters modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only outputters present in the keyspace ''' ret = LazyLoader( _module_dirs(opts, 'output', ext_type_dirs='outputter_dirs'), opts, tag='output', ) wrapped_ret = FilterDictWrapper(ret, '.output') # TODO: this name seems terrible... __salt__ should always be execution mods ret.pack['__salt__'] = wrapped_ret return wrapped_ret def serializers(opts): ''' Returns the serializers modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only serializers present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'serializers'), opts, tag='serializers', ) def eauth_tokens(opts): ''' Returns the tokens modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only token backends present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'tokens'), opts, tag='tokens', ) def auth(opts, whitelist=None): ''' Returns the auth modules :param dict opts: The Salt options dictionary :returns: LazyLoader ''' return LazyLoader( _module_dirs(opts, 'auth'), opts, tag='auth', whitelist=whitelist, pack={'__salt__': minion_mods(opts)}, ) def fileserver(opts, backends): ''' Returns the file server modules ''' return LazyLoader(_module_dirs(opts, 'fileserver'), opts, tag='fileserver', whitelist=backends, pack={'__utils__': utils(opts)}) def roster(opts, runner=None, utils=None, whitelist=None): ''' Returns the roster modules ''' return LazyLoader( _module_dirs(opts, 'roster'), opts, tag='roster', whitelist=whitelist, pack={ '__runner__': runner, '__utils__': utils, }, ) def states(opts, functions, utils, serializers, whitelist=None, proxy=None, context=None): ''' Returns the state modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') statemods = salt.loader.states(__opts__, None, None) ''' if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'states'), opts, tag='states', pack={'__salt__': functions, '__proxy__': proxy or {}}, whitelist=whitelist, ) ret.pack['__states__'] = ret ret.pack['__utils__'] = utils ret.pack['__serializers__'] = serializers ret.pack['__context__'] = context return ret def beacons(opts, functions, context=None, proxy=None): ''' Load the beacon modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. ''' return LazyLoader( _module_dirs(opts, 'beacons'), opts, tag='beacons', pack={'__context__': context, '__salt__': functions, '__proxy__': proxy or {}}, virtual_funcs=[], ) def log_handlers(opts): ''' Returns the custom logging handler modules :param dict opts: The Salt options dictionary ''' ret = LazyLoader( _module_dirs( opts, 'log_handlers', int_type='handlers', base_path=os.path.join(SALT_BASE_PATH, 'log'), ), opts, tag='log_handlers', ) return FilterDictWrapper(ret, '.setup_handlers') def ssh_wrapper(opts, functions=None, context=None): ''' Returns the custom logging handler modules ''' return LazyLoader( _module_dirs( opts, 'wrapper', base_path=os.path.join(SALT_BASE_PATH, os.path.join('client', 'ssh')), ), opts, tag='wrapper', pack={ '__salt__': functions, '__grains__': opts.get('grains', {}), '__pillar__': opts.get('pillar', {}), '__context__': context, }, ) def render(opts, functions, states=None, proxy=None, context=None): ''' Returns the render modules ''' if context is None: context = {} pack = {'__salt__': functions, '__grains__': opts.get('grains', {}), '__context__': context} if states: pack['__states__'] = states pack['__proxy__'] = proxy or {} ret = LazyLoader( _module_dirs( opts, 'renderers', 'render', ext_type_dirs='render_dirs', ), opts, tag='render', pack=pack, ) rend = FilterDictWrapper(ret, '.render') if not check_render_pipe_str(opts['renderer'], rend, opts['renderer_blacklist'], opts['renderer_whitelist']): err = ('The renderer {0} is unavailable, this error is often because ' 'the needed software is unavailable'.format(opts['renderer'])) log.critical(err) raise LoaderError(err) return rend def grain_funcs(opts, proxy=None): ''' Returns the grain functions .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') grainfuncs = salt.loader.grain_funcs(__opts__) ''' ret = LazyLoader( _module_dirs( opts, 'grains', 'grain', ext_type_dirs='grains_dirs', ), opts, tag='grains', ) ret.pack['__utils__'] = utils(opts, proxy=proxy) return ret def _load_cached_grains(opts, cfn): ''' Returns the grains cached in cfn, or None if the cache is too old or is corrupted. ''' if not os.path.isfile(cfn): log.debug('Grains cache file does not exist.') return None grains_cache_age = int(time.time() - os.path.getmtime(cfn)) if grains_cache_age > opts.get('grains_cache_expiration', 300): log.debug( 'Grains cache last modified %s seconds ago and cache ' 'expiration is set to %s. Grains cache expired. ' 'Refreshing.', grains_cache_age, opts.get('grains_cache_expiration', 300) ) return None if opts.get('refresh_grains_cache', False): log.debug('refresh_grains_cache requested, Refreshing.') return None log.debug('Retrieving grains from cache') try: serial = salt.payload.Serial(opts) with salt.utils.files.fopen(cfn, 'rb') as fp_: cached_grains = salt.utils.data.decode(serial.load(fp_), preserve_tuples=True) if not cached_grains: log.debug('Cached grains are empty, cache might be corrupted. Refreshing.') return None return cached_grains except (IOError, OSError): return None def grains(opts, force_refresh=False, proxy=None): ''' Return the functions for the dynamic grains and the values for the static grains. Since grains are computed early in the startup process, grains functions do not have __salt__ or __proxy__ available. At proxy-minion startup, this function is called with the proxymodule LazyLoader object so grains functions can communicate with their controlled device. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) print __grains__['id'] ''' # Need to re-import salt.config, somehow it got lost when a minion is starting import salt.config # if we have no grains, lets try loading from disk (TODO: move to decorator?) cfn = os.path.join( opts['cachedir'], 'grains.cache.p' ) if not force_refresh and opts.get('grains_cache', False): cached_grains = _load_cached_grains(opts, cfn) if cached_grains: return cached_grains else: log.debug('Grains refresh requested. Refreshing grains.') if opts.get('skip_grains', False): return {} grains_deep_merge = opts.get('grains_deep_merge', False) is True if 'conf_file' in opts: pre_opts = {} pre_opts.update(salt.config.load_config( opts['conf_file'], 'SALT_MINION_CONFIG', salt.config.DEFAULT_MINION_OPTS['conf_file'] )) default_include = pre_opts.get( 'default_include', opts['default_include'] ) include = pre_opts.get('include', []) pre_opts.update(salt.config.include_config( default_include, opts['conf_file'], verbose=False )) pre_opts.update(salt.config.include_config( include, opts['conf_file'], verbose=True )) if 'grains' in pre_opts: opts['grains'] = pre_opts['grains'] else: opts['grains'] = {} else: opts['grains'] = {} grains_data = {} blist = opts.get('grains_blacklist', []) funcs = grain_funcs(opts, proxy=proxy) if force_refresh: # if we refresh, lets reload grain modules funcs.clear() # Run core grains for key in funcs: if not key.startswith('core.'): continue log.trace('Loading %s grain', key) ret = funcs[key]() if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) # Run the rest of the grains for key in funcs: if key.startswith('core.') or key == '_errors': continue try: # Grains are loaded too early to take advantage of the injected # __proxy__ variable. Pass an instance of that LazyLoader # here instead to grains functions if the grains functions take # one parameter. Then the grains can have access to the # proxymodule for retrieving information from the connected # device. log.trace('Loading %s grain', key) parameters = salt.utils.args.get_function_argspec(funcs[key]).args kwargs = {} if 'proxy' in parameters: kwargs['proxy'] = proxy if 'grains' in parameters: kwargs['grains'] = grains_data ret = funcs[key](**kwargs) except Exception: if salt.utils.platform.is_proxy(): log.info('The following CRITICAL message may not be an error; the proxy may not be completely established yet.') log.critical( 'Failed to load grains defined in grain file %s in ' 'function %s, error:\n', key, funcs[key], exc_info=True ) continue if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) if opts.get('proxy_merge_grains_in_module', True) and proxy: try: proxytype = proxy.opts['proxy']['proxytype'] if proxytype + '.grains' in proxy: if proxytype + '.initialized' in proxy and proxy[proxytype + '.initialized'](): try: proxytype = proxy.opts['proxy']['proxytype'] ret = proxy[proxytype + '.grains']() if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) except Exception: log.critical('Failed to run proxy\'s grains function!', exc_info=True ) except KeyError: pass grains_data.update(opts['grains']) # Write cache if enabled if opts.get('grains_cache', False): with salt.utils.files.set_umask(0o077): try: if salt.utils.platform.is_windows(): # Late import import salt.modules.cmdmod # Make sure cache file isn't read-only salt.modules.cmdmod._run_quiet('attrib -R "{0}"'.format(cfn)) with salt.utils.files.fopen(cfn, 'w+b') as fp_: try: serial = salt.payload.Serial(opts) serial.dump(grains_data, fp_) except TypeError as e: log.error('Failed to serialize grains cache: %s', e) raise # re-throw for cleanup except Exception as e: log.error('Unable to write to grains cache file %s: %s', cfn, e) # Based on the original exception, the file may or may not have been # created. If it was, we will remove it now, as the exception means # the serialized data is not to be trusted, no matter what the # exception is. if os.path.isfile(cfn): os.unlink(cfn) if grains_deep_merge: salt.utils.dictupdate.update(grains_data, opts['grains']) else: grains_data.update(opts['grains']) return salt.utils.data.decode(grains_data, preserve_tuples=True) # TODO: get rid of? Does anyone use this? You should use raw() instead def call(fun, **kwargs): ''' Directly call a function inside a loader directory ''' args = kwargs.get('args', []) dirs = kwargs.get('dirs', []) funcs = LazyLoader( [os.path.join(SALT_BASE_PATH, 'modules')] + dirs, None, tag='modules', virtual_enable=False, ) return funcs[fun](*args) def runner(opts, utils=None, context=None, whitelist=None): ''' Directly call a function inside a loader directory ''' if utils is None: utils = {} if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'runners', 'runner', ext_type_dirs='runner_dirs'), opts, tag='runners', pack={'__utils__': utils, '__context__': context}, whitelist=whitelist, ) # TODO: change from __salt__ to something else, we overload __salt__ too much ret.pack['__salt__'] = ret return ret def queues(opts): ''' Directly call a function inside a loader directory ''' return LazyLoader( _module_dirs(opts, 'queues', 'queue', ext_type_dirs='queue_dirs'), opts, tag='queues', ) def sdb(opts, functions=None, whitelist=None, utils=None): ''' Make a very small database call ''' if utils is None: utils = {} return LazyLoader( _module_dirs(opts, 'sdb'), opts, tag='sdb', pack={ '__sdb__': functions, '__opts__': opts, '__utils__': utils, '__salt__': minion_mods(opts, utils), }, whitelist=whitelist, ) def pkgdb(opts): ''' Return modules for SPM's package database .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgdb', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgdb' ) def pkgfiles(opts): ''' Return modules for SPM's file handling .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgfiles', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgfiles' ) def clouds(opts): ''' Return the cloud functions ''' # Let's bring __active_provider_name__, defaulting to None, to all cloud # drivers. This will get temporarily updated/overridden with a context # manager when needed. functions = LazyLoader( _module_dirs(opts, 'clouds', 'cloud', base_path=os.path.join(SALT_BASE_PATH, 'cloud'), int_type='clouds'), opts, tag='clouds', pack={'__utils__': salt.loader.utils(opts), '__active_provider_name__': None}, ) for funcname in LIBCLOUD_FUNCS_NOT_SUPPORTED: log.trace( '\'%s\' has been marked as not supported. Removing from the ' 'list of supported cloud functions', funcname ) functions.pop(funcname, None) return functions def netapi(opts): ''' Return the network api functions ''' return LazyLoader( _module_dirs(opts, 'netapi'), opts, tag='netapi', ) def executors(opts, functions=None, context=None, proxy=None): ''' Returns the executor modules ''' executors = LazyLoader( _module_dirs(opts, 'executors', 'executor'), opts, tag='executor', pack={'__salt__': functions, '__context__': context or {}, '__proxy__': proxy or {}}, ) executors.pack['__executors__'] = executors return executors def cache(opts, serial): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'cache', 'cache'), opts, tag='cache', pack={'__opts__': opts, '__context__': {'serial': serial}}, ) def _generate_module(name): if name in sys.modules: return code = "'''Salt loaded {0} parent module'''".format(name.split('.')[-1]) # ModuleType can't accept a unicode type on PY2 module = types.ModuleType(str(name)) # future lint: disable=blacklisted-function exec(code, module.__dict__) sys.modules[name] = module def _mod_type(module_path): if module_path.startswith(SALT_BASE_PATH): return 'int' return 'ext' def _inject_into_mod(mod, name, value, force_lock=False): ''' Inject a variable into a module. This is used to inject "globals" like ``__salt__``, ``__pillar``, or ``grains``. Instead of injecting the value directly, a ``ThreadLocalProxy`` is created. If such a proxy is already present under the specified name, it is updated with the new value. This update only affects the current thread, so that the same name can refer to different values depending on the thread of execution. This is important for data that is not truly global. For example, pillar data might be dynamically overriden through function parameters and thus the actual values available in pillar might depend on the thread that is calling a module. mod: module object into which the value is going to be injected. name: name of the variable that is injected into the module. value: value that is injected into the variable. The value is not injected directly, but instead set as the new reference of the proxy that has been created for the variable. force_lock: whether the lock should be acquired before checking whether a proxy object for the specified name has already been injected into the module. If ``False`` (the default), this function checks for the module's variable without acquiring the lock and only acquires the lock if a new proxy has to be created and injected. ''' old_value = getattr(mod, name, None) # We use a double-checked locking scheme in order to avoid taking the lock # when a proxy object has already been injected. # In most programming languages, double-checked locking is considered # unsafe when used without explicit memory barriers because one might read # an uninitialized value. In CPython it is safe due to the global # interpreter lock (GIL). In Python implementations that do not have the # GIL, it could be unsafe, but at least Jython also guarantees that (for # Python objects) memory is not corrupted when writing and reading without # explicit synchronization # (http://www.jython.org/jythonbook/en/1.0/Concurrency.html). # Please note that in order to make this code safe in a runtime environment # that does not make this guarantees, it is not sufficient. The # ThreadLocalProxy must also be created with fallback_to_shared set to # False or a lock must be added to the ThreadLocalProxy. if force_lock: with _inject_into_mod.lock: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: setattr(mod, name, ThreadLocalProxy(value, True)) else: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: _inject_into_mod(mod, name, value, True) # Lock used when injecting globals. This is needed to avoid a race condition # when two threads try to load the same module concurrently. This must be # outside the loader because there might be more than one loader for the same # namespace. _inject_into_mod.lock = threading.RLock() # TODO: move somewhere else? class FilterDictWrapper(MutableMapping): ''' Create a dict which wraps another dict with a specific key suffix on get This is to replace "filter_load" ''' def __init__(self, d, suffix): self._dict = d self.suffix = suffix def __setitem__(self, key, val): self._dict[key] = val def __delitem__(self, key): del self._dict[key] def __getitem__(self, key): return self._dict[key + self.suffix] def __len__(self): return len(self._dict) def __iter__(self): for key in self._dict: if key.endswith(self.suffix): yield key.replace(self.suffix, '') class LazyLoader(salt.utils.lazy.LazyDict): ''' A pseduo-dictionary which has a set of keys which are the name of the module and function, delimited by a dot. When the value of the key is accessed, the function is then loaded from disk and into memory. .. note:: Iterating over keys will cause all modules to be loaded. :param list module_dirs: A list of directories on disk to search for modules :param dict opts: The salt options dictionary. :param str tag: The tag for the type of module to load :param func mod_type_check: A function which can be used to verify files :param dict pack: A dictionary of function to be packed into modules as they are loaded :param list whitelist: A list of modules to whitelist :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules. :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality. If not true, the module will not load. :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values are function references themselves which are loaded on-demand. # TODO: - move modules_max_memory into here - singletons (per tag) ''' mod_dict_class = salt.utils.odict.OrderedDict def __init__(self, module_dirs, opts=None, tag='module', loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, proxy=None, virtual_funcs=None, ): # pylint: disable=W0231 ''' In pack, if any of the values are None they will be replaced with an empty context-specific dict ''' self.inject_globals = {} self.pack = {} if pack is None else pack if opts is None: opts = {} threadsafety = not opts.get('multiprocessing') self.context_dict = salt.utils.context.ContextDict(threadsafe=threadsafety) self.opts = self.__prep_mod_opts(opts) self.module_dirs = module_dirs self.tag = tag self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME self.mod_type_check = mod_type_check or _mod_type if '__context__' not in self.pack: self.pack['__context__'] = None for k, v in six.iteritems(self.pack): if v is None: # if the value of a pack is None, lets make an empty dict value = self.context_dict.get(k, {}) if isinstance(value, ThreadLocalProxy): value = ThreadLocalProxy.unproxy(value) self.context_dict[k] = value self.pack[k] = salt.utils.context.NamespacedDictWrapper(self.context_dict, k) self.whitelist = whitelist self.virtual_enable = virtual_enable self.initial_load = True # names of modules that we don't have (errors, __virtual__, etc.) self.missing_modules = {} # mapping of name -> error self.loaded_modules = {} # mapping of module_name -> dict_of_functions self.loaded_files = set() # TODO: just remove them from file_mapping? self.static_modules = static_modules if static_modules else [] if virtual_funcs is None: virtual_funcs = [] self.virtual_funcs = virtual_funcs self.disabled = set( self.opts.get( 'disable_{0}{1}'.format( self.tag, '' if self.tag[-1] == 's' else 's' ), [] ) ) # A map of suffix to description for imp self.suffix_map = {} # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [''] for (suffix, mode, kind) in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) self._lock = threading.RLock() self._refresh_file_mapping() super(LazyLoader, self).__init__() # late init the lazy loader # create all of the import namespaces _generate_module('{0}.int'.format(self.loaded_base_name)) _generate_module('{0}.int.{1}'.format(self.loaded_base_name, tag)) _generate_module('{0}.ext'.format(self.loaded_base_name)) _generate_module('{0}.ext.{1}'.format(self.loaded_base_name, tag)) def __getitem__(self, item): ''' Override the __getitem__ in order to decorate the returned function if we need to last-minute inject globals ''' func = super(LazyLoader, self).__getitem__(item) if self.inject_globals: return global_injector_decorator(self.inject_globals)(func) else: return func def __getattr__(self, mod_name): ''' Allow for "direct" attribute access-- this allows jinja templates to access things like `salt.test.ping()` ''' if mod_name in ('__getstate__', '__setstate__'): return object.__getattribute__(self, mod_name) # if we have an attribute named that, lets return it. try: return object.__getattr__(self, mod_name) # pylint: disable=no-member except AttributeError: pass # otherwise we assume its jinja template access if mod_name not in self.loaded_modules and not self.loaded: for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and mod_name in self.loaded_modules: break if mod_name in self.loaded_modules: return self.loaded_modules[mod_name] else: raise AttributeError(mod_name) def missing_fun_string(self, function_name): ''' Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ''' mod_name = function_name.split('.')[0] if mod_name in self.loaded_modules: return '\'{0}\' is not available.'.format(function_name) else: try: reason = self.missing_modules[mod_name] except KeyError: return '\'{0}\' is not available.'.format(function_name) else: if reason is not None: return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason) else: return '\'{0}\' __virtual__ returned False'.format(mod_name) def _refresh_file_mapping(self): ''' refresh the mapping of the FS on disk ''' # map of suffix to description for imp if self.opts.get('cython_enable', True) is True: try: global pyximport pyximport = __import__('pyximport') # pylint: disable=import-error pyximport.install() # add to suffix_map so file_mapping will pick it up self.suffix_map['.pyx'] = tuple() except ImportError: log.info('Cython is enabled in the options but not present ' 'in the system path. Skipping Cython modules.') # Allow for zipimport of modules if self.opts.get('enable_zip_modules', True) is True: self.suffix_map['.zip'] = tuple() # allow for module dirs if USE_IMPORTLIB: self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY) else: self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY) # create mapping of filename (without suffix) to (path, suffix) # The files are added in order of priority, so order *must* be retained. self.file_mapping = salt.utils.odict.OrderedDict() opt_match = [] def _replace_pre_ext(obj): ''' Hack so we can get the optimization level that we replaced (if any) out of the re.sub call below. We use a list here because it is a persistent data structure that we will be able to access after re.sub is called. ''' opt_match.append(obj) return '' for mod_dir in self.module_dirs: try: # Make sure we have a sorted listdir in order to have # expectable override results files = sorted( x for x in os.listdir(mod_dir) if x != '__pycache__' ) except OSError: continue # Next mod_dir if six.PY3: try: pycache_files = [ os.path.join('__pycache__', x) for x in sorted(os.listdir(os.path.join(mod_dir, '__pycache__'))) ] except OSError: pass else: files.extend(pycache_files) for filename in files: try: dirname, basename = os.path.split(filename) if basename.startswith('_'): # skip private modules # log messages omitted for obviousness continue # Next filename f_noext, ext = os.path.splitext(basename) if six.PY3: f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext) try: opt_level = int( opt_match.pop().group(1).rsplit('-', 1)[-1] ) except (AttributeError, IndexError, ValueError): # No regex match or no optimization level matched opt_level = 0 try: opt_index = self.opts['optimization_order'].index(opt_level) except KeyError: log.trace( 'Disallowed optimization level %d for module ' 'name \'%s\', skipping. Add %d to the ' '\'optimization_order\' config option if you ' 'do not want to ignore this optimization ' 'level.', opt_level, f_noext, opt_level ) continue else: # Optimization level not reflected in filename on PY2 opt_index = 0 # make sure it is a suffix we support if ext not in self.suffix_map: continue # Next filename if f_noext in self.disabled: log.trace( 'Skipping %s, it is disabled by configuration', filename ) continue # Next filename fpath = os.path.join(mod_dir, filename) # if its a directory, lets allow us to load that if ext == '': # is there something __init__? subfiles = os.listdir(fpath) for suffix in self.suffix_order: if '' == suffix: continue # Next suffix (__init__ must have a suffix) init_file = '__init__{0}'.format(suffix) if init_file in subfiles: break else: continue # Next filename try: curr_ext = self.file_mapping[f_noext][1] curr_opt_index = self.file_mapping[f_noext][2] except KeyError: pass else: if '' in (curr_ext, ext) and curr_ext != ext: log.error( 'Module/package collision: \'%s\' and \'%s\'', fpath, self.file_mapping[f_noext][0] ) if six.PY3 and ext == '.pyc' and curr_ext == '.pyc': # Check the optimization level if opt_index >= curr_opt_index: # Module name match, but a higher-priority # optimization level was already matched, skipping. continue elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext): # Match found but a higher-priorty match already # exists, so skip this. continue if six.PY3 and not dirname and ext == '.pyc': # On Python 3, we should only load .pyc files from the # __pycache__ subdirectory (i.e. when dirname is not an # empty string). continue # Made it this far - add it self.file_mapping[f_noext] = (fpath, ext, opt_index) except OSError: continue for smod in self.static_modules: f_noext = smod.split('.')[-1] self.file_mapping[f_noext] = (smod, '.o', 0) def clear(self): ''' Clear the dict ''' with self._lock: super(LazyLoader, self).clear() # clear the lazy loader self.loaded_files = set() self.missing_modules = {} self.loaded_modules = {} # if we have been loaded before, lets clear the file mapping since # we obviously want a re-do if hasattr(self, 'opts'): self._refresh_file_mapping() self.initial_load = False def __prep_mod_opts(self, opts): ''' Strip out of the opts any logger instance ''' if '__grains__' not in self.pack: grains = opts.get('grains', {}) if isinstance(grains, ThreadLocalProxy): grains = ThreadLocalProxy.unproxy(grains) self.context_dict['grains'] = grains self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains') if '__pillar__' not in self.pack: pillar = opts.get('pillar', {}) if isinstance(pillar, ThreadLocalProxy): pillar = ThreadLocalProxy.unproxy(pillar) self.context_dict['pillar'] = pillar self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar') mod_opts = {} for key, val in list(opts.items()): if key == 'logger': continue mod_opts[key] = val return mod_opts def _iter_files(self, mod_name): ''' Iterate over all file_mapping files in order of closeness to mod_name ''' # do we have an exact match? if mod_name in self.file_mapping: yield mod_name # do we have a partial match? for k in self.file_mapping: if mod_name in k: yield k # anyone else? Bueller? for k in self.file_mapping: if mod_name not in k: yield k def _reload_submodules(self, mod): submodules = ( getattr(mod, sname) for sname in dir(mod) if isinstance(getattr(mod, sname), mod.__class__) ) # reload only custom "sub"modules for submodule in submodules: # it is a submodule if the name is in a namespace under mod if submodule.__name__.startswith(mod.__name__ + '.'): reload_module(submodule) self._reload_submodules(submodule) def _load_module(self, name): mod = None fpath, suffix = self.file_mapping[name][:2] self.loaded_files.add(name) fpath_dirname = os.path.dirname(fpath) try: sys.path.append(fpath_dirname) if suffix == '.pyx': mod = pyximport.load_module(name, fpath, tempfile.gettempdir()) elif suffix == '.o': top_mod = __import__(fpath, globals(), locals(), []) comps = fpath.split('.') if len(comps) < 2: mod = top_mod else: mod = top_mod for subname in comps[1:]: mod = getattr(mod, subname) elif suffix == '.zip': mod = zipimporter(fpath).load_module(name) else: desc = self.suffix_map[suffix] # if it is a directory, we don't open a file try: mod_namespace = '.'.join(( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name)) except TypeError: mod_namespace = '{0}.{1}.{2}.{3}'.format( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name) if suffix == '': if USE_IMPORTLIB: # pylint: disable=no-member # Package directory, look for __init__ loader_details = [ (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES), (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES), (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), ] file_finder = importlib.machinery.FileFinder( fpath_dirname, *loader_details ) spec = file_finder.find_spec(mod_namespace) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: mod = imp.load_module(mod_namespace, None, fpath, desc) # reload all submodules if necessary if not self.initial_load: self._reload_submodules(mod) else: if USE_IMPORTLIB: # pylint: disable=no-member loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath) spec = importlib.util.spec_from_file_location( mod_namespace, fpath, loader=loader ) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() #mod = importlib.util.module_from_spec(spec) #spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: with salt.utils.files.fopen(fpath, desc[1]) as fn_: mod = imp.load_module(mod_namespace, fn_, fpath, desc) except IOError: raise except ImportError as exc: if 'magic number' in six.text_type(exc): error_msg = 'Failed to import {0} {1}. Bad magic number. If migrating from Python2 to Python3, remove all .pyc files and try again.'.format(self.tag, name) log.warning(error_msg) self.missing_modules[name] = error_msg log.debug( 'Failed to import %s %s:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = exc return False except Exception as error: log.error( 'Failed to import %s %s, this is due most likely to a ' 'syntax error:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False except SystemExit as error: try: fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1] except Exception: pass else: tgt_fn = os.path.join('salt', 'utils', 'process.py') if fn_.endswith(tgt_fn) and '_handle_signals' in caller: # Race conditon, SIGTERM or SIGINT received while loader # was in process of loading a module. Call sys.exit to # ensure that the process is killed. sys.exit(salt.defaults.exitcodes.EX_OK) log.error( 'Failed to import %s %s as the module called exit()\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False finally: sys.path.remove(fpath_dirname) if hasattr(mod, '__opts__'): mod.__opts__.update(self.opts) else: mod.__opts__ = self.opts # pack whatever other globals we were asked to for p_name, p_value in six.iteritems(self.pack): _inject_into_mod(mod, p_name, p_value) module_name = mod.__name__.rsplit('.', 1)[-1] # Call a module's initialization method if it exists module_init = getattr(mod, '__init__', None) if inspect.isfunction(module_init): try: module_init(self.opts) except TypeError as e: log.error(e) except Exception: err_string = '__init__ failed' log.debug( 'Error loading %s.%s: %s', self.tag, module_name, err_string, exc_info=True ) self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False # if virtual modules are enabled, we need to look for the # __virtual__() function inside that module and run it. if self.virtual_enable: virtual_funcs_to_process = ['__virtual__'] + self.virtual_funcs for virtual_func in virtual_funcs_to_process: virtual_ret, module_name, virtual_err, virtual_aliases = \ self._process_virtual(mod, module_name, virtual_func) if virtual_err is not None: log.trace( 'Error loading %s.%s: %s', self.tag, module_name, virtual_err ) # if _process_virtual returned a non-True value then we are # supposed to not process this module if virtual_ret is not True and module_name not in self.missing_modules: # If a module has information about why it could not be loaded, record it self.missing_modules[module_name] = virtual_err self.missing_modules[name] = virtual_err return False else: virtual_aliases = () # If this is a proxy minion then MOST modules cannot work. Therefore, require that # any module that does work with salt-proxy-minion define __proxyenabled__ as a list # containing the names of the proxy types that the module supports. # # Render modules and state modules are OK though if 'proxy' in self.opts: if self.tag in ['grains', 'proxy']: if not hasattr(mod, '__proxyenabled__') or \ (self.opts['proxy']['proxytype'] not in mod.__proxyenabled__ and '*' not in mod.__proxyenabled__): err_string = 'not a proxy_minion enabled module' self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False if getattr(mod, '__load__', False) is not False: log.info( 'The functions from module \'%s\' are being loaded from the ' 'provided __load__ attribute', module_name ) # If we had another module by the same virtual name, we should put any # new functions under the existing dictionary. mod_names = [module_name] + list(virtual_aliases) mod_dict = dict(( (x, self.loaded_modules.get(x, self.mod_dict_class())) for x in mod_names )) for attr in getattr(mod, '__load__', dir(mod)): if attr.startswith('_') and attr != '__call__': # private functions are skipped, # except __call__ which is default entrance # for multi-function batch-like state syntax continue func = getattr(mod, attr) if not inspect.isfunction(func) and not isinstance(func, functools.partial): # Not a function!? Skip it!!! continue # Let's get the function name. # If the module has the __func_alias__ attribute, it must be a # dictionary mapping in the form of(key -> value): # <real-func-name> -> <desired-func-name> # # It default's of course to the found callable attribute name # if no alias is defined. funcname = getattr(mod, '__func_alias__', {}).get(attr, attr) for tgt_mod in mod_names: try: full_funcname = '.'.join((tgt_mod, funcname)) except TypeError: full_funcname = '{0}.{1}'.format(tgt_mod, funcname) # Save many references for lookups # Careful not to overwrite existing (higher priority) functions if full_funcname not in self._dict: self._dict[full_funcname] = func if funcname not in mod_dict[tgt_mod]: setattr(mod_dict[tgt_mod], funcname, func) mod_dict[tgt_mod][funcname] = func self._apply_outputter(func, mod) # enforce depends try: Depends.enforce_dependencies(self._dict, self.tag) except RuntimeError as exc: log.info( 'Depends.enforce_dependencies() failed for the following ' 'reason: %s', exc ) for tgt_mod in mod_names: self.loaded_modules[tgt_mod] = mod_dict[tgt_mod] return True def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise KeyError('The key \'{0}\' should contain a \'.\''.format(key)) mod_name, _ = key.split('.', 1) with self._lock: # It is possible that the key is in the dictionary after # acquiring the lock due to another thread loading it. if mod_name in self.missing_modules or key in self._dict: return True # if the modulename isn't in the whitelist, don't bother if self.whitelist and mod_name not in self.whitelist: log.error( 'Failed to load function %s because its module (%s) is ' 'not in the whitelist: %s', key, mod_name, self.whitelist ) raise KeyError(key) def _inner_load(mod_name): for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and key in self._dict: return True return False # try to load the module ret = None reloaded = False # re-scan up to once, IOErrors or a failed load cause re-scans of the # filesystem while True: try: ret = _inner_load(mod_name) if not reloaded and ret is not True: self._refresh_file_mapping() reloaded = True continue break except IOError: if not reloaded: self._refresh_file_mapping() reloaded = True continue return ret def _load_all(self): ''' Load all of them ''' with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True def reload_modules(self): with self._lock: self.loaded_files = set() self._load_all() def _apply_outputter(self, func, mod): ''' Apply the __outputter__ variable to the functions ''' if hasattr(mod, '__outputter__'): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__] def _process_virtual(self, mod, module_name, virtual_func='__virtual__'): ''' Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1] ''' # The __virtual__ function will return either a True or False value. # If it returns a True value it can also set a module level attribute # named __virtualname__ with the name that the module should be # referred to as. # # This allows us to have things like the pkg module working on all # platforms under the name 'pkg'. It also allows for modules like # augeas_cfg to be referred to as 'augeas', which would otherwise have # namespace collisions. And finally it allows modules to return False # if they are not intended to run on the given platform or are missing # dependencies. virtual_aliases = getattr(mod, '__virtual_aliases__', tuple()) try: error_reason = None if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__): try: start = time.time() virtual = getattr(mod, virtual_func)() if isinstance(virtual, tuple): error_reason = virtual[1] virtual = virtual[0] if self.opts.get('virtual_timer', False): end = time.time() - start msg = 'Virtual function took {0} seconds for {1}'.format( end, module_name) log.warning(msg) except Exception as exc: error_reason = ( 'Exception raised when processing __virtual__ function' ' for {0}. Module will not be loaded: {1}'.format( mod.__name__, exc)) log.error(error_reason, exc_info_on_loglevel=logging.DEBUG) virtual = None # Get the module's virtual name virtualname = getattr(mod, '__virtualname__', virtual) if not virtual: # if __virtual__() evaluates to False then the module # wasn't meant for this platform or it's not supposed to # load for some other reason. # Some modules might accidentally return None and are # improperly loaded if virtual is None: log.warning( '%s.__virtual__() is wrongly returning `None`. ' 'It should either return `True`, `False` or a new ' 'name. If you\'re the developer of the module ' '\'%s\', please fix this.', mod.__name__, module_name ) return (False, module_name, error_reason, virtual_aliases) # At this point, __virtual__ did not return a # boolean value, let's check for deprecated usage # or module renames if virtual is not True and module_name != virtual: # The module is renaming itself. Updating the module name # with the new name log.trace('Loaded %s as virtual %s', module_name, virtual) if virtualname != virtual: # The __virtualname__ attribute does not match what's # being returned by the __virtual__() function. This # should be considered an error. log.error( 'The module \'%s\' is showing some bad usage. Its ' '__virtualname__ attribute is set to \'%s\' yet the ' '__virtual__() function is returning \'%s\'. These ' 'values should match!', mod.__name__, virtualname, virtual ) module_name = virtualname # If the __virtual__ function returns True and __virtualname__ # is set then use it elif virtual is True and virtualname != module_name: if virtualname is not True: module_name = virtualname except KeyError: # Key errors come out of the virtual function when passing # in incomplete grains sets, these can be safely ignored # and logged to debug, still, it includes the traceback to # help debugging. log.debug('KeyError when loading %s', module_name, exc_info=True) except Exception: # If the module throws an exception during __virtual__() # then log the information and continue to the next. log.error( 'Failed to read the virtual function for %s: %s', self.tag, module_name, exc_info=True ) return (False, module_name, error_reason, virtual_aliases) return (True, module_name, None, virtual_aliases) def global_injector_decorator(inject_globals): ''' Decorator used by the LazyLoader to inject globals into a function at execute time. globals Dictionary with global variables to inject ''' def inner_decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): with salt.utils.context.func_globals_inject(f, **inject_globals): return f(*args, **kwargs) return wrapper return inner_decorator
saltstack/salt
salt/loader.py
states
python
def states(opts, functions, utils, serializers, whitelist=None, proxy=None, context=None): ''' Returns the state modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') statemods = salt.loader.states(__opts__, None, None) ''' if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'states'), opts, tag='states', pack={'__salt__': functions, '__proxy__': proxy or {}}, whitelist=whitelist, ) ret.pack['__states__'] = ret ret.pack['__utils__'] = utils ret.pack['__serializers__'] = serializers ret.pack['__context__'] = context return ret
Returns the state modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') statemods = salt.loader.states(__opts__, None, None)
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L544-L574
null
# -*- coding: utf-8 -*- ''' The Salt loader is the core to Salt's plugin system, the loader scans directories for python loadable code and organizes the code into the plugin interfaces used by Salt. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import sys import time import logging import inspect import tempfile import threading import functools import threading import traceback import types from zipimport import zipimporter # Import salt libs import salt.config import salt.defaults.events import salt.defaults.exitcodes import salt.syspaths import salt.utils.args import salt.utils.context import salt.utils.data import salt.utils.dictupdate import salt.utils.event import salt.utils.files import salt.utils.lazy import salt.utils.odict import salt.utils.platform import salt.utils.versions import salt.utils.stringutils from salt.exceptions import LoaderError from salt.template import check_render_pipe_str from salt.utils.decorators import Depends from salt.utils.thread_local_proxy import ThreadLocalProxy # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import reload_module if sys.version_info[:2] >= (3, 5): import importlib.machinery # pylint: disable=no-name-in-module,import-error import importlib.util # pylint: disable=no-name-in-module,import-error USE_IMPORTLIB = True else: import imp USE_IMPORTLIB = False try: from collections.abc import MutableMapping except ImportError: from collections import MutableMapping try: import pkg_resources HAS_PKG_RESOURCES = True except ImportError: HAS_PKG_RESOURCES = False log = logging.getLogger(__name__) SALT_BASE_PATH = os.path.abspath(salt.syspaths.INSTALL_DIR) LOADED_BASE_NAME = 'salt.loaded' if USE_IMPORTLIB: # pylint: disable=no-member MODULE_KIND_SOURCE = 1 MODULE_KIND_COMPILED = 2 MODULE_KIND_EXTENSION = 3 MODULE_KIND_PKG_DIRECTORY = 5 SUFFIXES = [] for suffix in importlib.machinery.EXTENSION_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_EXTENSION)) for suffix in importlib.machinery.SOURCE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_SOURCE)) for suffix in importlib.machinery.BYTECODE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_COMPILED)) MODULE_KIND_MAP = { MODULE_KIND_SOURCE: importlib.machinery.SourceFileLoader, MODULE_KIND_COMPILED: importlib.machinery.SourcelessFileLoader, MODULE_KIND_EXTENSION: importlib.machinery.ExtensionFileLoader } # pylint: enable=no-member else: SUFFIXES = imp.get_suffixes() PY3_PRE_EXT = \ re.compile(r'\.cpython-{0}{1}(\.opt-[1-9])?'.format(*sys.version_info[:2])) # Because on the cloud drivers we do `from salt.cloud.libcloudfuncs import *` # which simplifies code readability, it adds some unsupported functions into # the driver's module scope. # We list un-supported functions here. These will be removed from the loaded. # TODO: remove the need for this cross-module code. Maybe use NotImplemented LIBCLOUD_FUNCS_NOT_SUPPORTED = ( 'parallels.avail_sizes', 'parallels.avail_locations', 'proxmox.avail_sizes', ) # Will be set to pyximport module at runtime if cython is enabled in config. pyximport = None def static_loader( opts, ext_type, tag, pack=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, filter_name=None, ): funcs = LazyLoader( _module_dirs( opts, ext_type, tag, int_type, ext_dirs, ext_type_dirs, base_path, ), opts, tag=tag, pack=pack, ) ret = {} funcs._load_all() if filter_name: funcs = FilterDictWrapper(funcs, filter_name) for key in funcs: ret[key] = funcs[key] return ret def _format_entrypoint_target(ep): ''' Makes a string describing the target of an EntryPoint object. Base strongly on EntryPoint.__str__(). ''' s = ep.module_name if ep.attrs: s += ':' + '.'.join(ep.attrs) return s def _module_dirs( opts, ext_type, tag=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, ): if tag is None: tag = ext_type sys_types = os.path.join(base_path or SALT_BASE_PATH, int_type or ext_type) ext_types = os.path.join(opts['extension_modules'], ext_type) ext_type_types = [] if ext_dirs: if ext_type_dirs is None: ext_type_dirs = '{0}_dirs'.format(tag) if ext_type_dirs in opts: ext_type_types.extend(opts[ext_type_dirs]) if HAS_PKG_RESOURCES and ext_type_dirs: for entry_point in pkg_resources.iter_entry_points('salt.loader', ext_type_dirs): try: loaded_entry_point = entry_point.load() for path in loaded_entry_point(): ext_type_types.append(path) except Exception as exc: log.error("Error getting module directories from %s: %s", _format_entrypoint_target(entry_point), exc) log.debug("Full backtrace for module directories error", exc_info=True) cli_module_dirs = [] # The dirs can be any module dir, or a in-tree _{ext_type} dir for _dir in opts.get('module_dirs', []): # Prepend to the list to match cli argument ordering maybe_dir = os.path.join(_dir, ext_type) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) continue maybe_dir = os.path.join(_dir, '_{0}'.format(ext_type)) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) return cli_module_dirs + ext_type_types + [ext_types, sys_types] def minion_mods( opts, context=None, utils=None, whitelist=None, initial_load=False, loaded_base_name=None, notify=False, static_modules=None, proxy=None): ''' Load execution modules Returns a dictionary of execution modules appropriate for the current system by evaluating the __virtual__() function in each module. :param dict opts: The Salt options dictionary :param dict context: A Salt context that should be made present inside generated modules in __context__ :param dict utils: Utility functions which should be made available to Salt modules in __utils__. See `utils_dirs` in salt.config for additional information about configuration. :param list whitelist: A list of modules which should be whitelisted. :param bool initial_load: Deprecated flag! Unused. :param str loaded_base_name: A string marker for the loaded base name. :param bool notify: Flag indicating that an event should be fired upon completion of module loading. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) __opts__['grains'] = __grains__ __utils__ = salt.loader.utils(__opts__) __salt__ = salt.loader.minion_mods(__opts__, utils=__utils__) __salt__['test.ping']() ''' # TODO Publish documentation for module whitelisting if not whitelist: whitelist = opts.get('whitelist_modules', None) ret = LazyLoader( _module_dirs(opts, 'modules', 'module'), opts, tag='module', pack={'__context__': context, '__utils__': utils, '__proxy__': proxy}, whitelist=whitelist, loaded_base_name=loaded_base_name, static_modules=static_modules, ) ret.pack['__salt__'] = ret # Load any provider overrides from the configuration file providers option # Note: Providers can be pkg, service, user or group - not to be confused # with cloud providers. providers = opts.get('providers', False) if providers and isinstance(providers, dict): for mod in providers: # sometimes providers opts is not to diverge modules but # for other configuration try: funcs = raw_mod(opts, providers[mod], ret) except TypeError: break else: if funcs: for func in funcs: f_key = '{0}{1}'.format(mod, func[func.rindex('.'):]) ret[f_key] = funcs[func] if notify: evt = salt.utils.event.get_event('minion', opts=opts, listen=False) evt.fire_event({'complete': True}, tag=salt.defaults.events.MINION_MOD_COMPLETE) return ret def raw_mod(opts, name, functions, mod='modules'): ''' Returns a single module loaded raw and bypassing the __virtual__ function .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') testmod = salt.loader.raw_mod(__opts__, 'test', None) testmod['test.ping']() ''' loader = LazyLoader( _module_dirs(opts, mod, 'module'), opts, tag='rawmodule', virtual_enable=False, pack={'__salt__': functions}, ) # if we don't have the module, return an empty dict if name not in loader.file_mapping: return {} loader._load_module(name) # load a single module (the one passed in) return dict(loader._dict) # return a copy of *just* the funcs for `name` def metaproxy(opts): ''' Return functions used in the meta proxy ''' return LazyLoader( _module_dirs(opts, 'metaproxy'), opts, tag='metaproxy' ) def matchers(opts): ''' Return the matcher services plugins ''' return LazyLoader( _module_dirs(opts, 'matchers'), opts, tag='matchers' ) def engines(opts, functions, runners, utils, proxy=None): ''' Return the master services plugins ''' pack = {'__salt__': functions, '__runners__': runners, '__proxy__': proxy, '__utils__': utils} return LazyLoader( _module_dirs(opts, 'engines'), opts, tag='engines', pack=pack, ) def proxy(opts, functions=None, returners=None, whitelist=None, utils=None): ''' Returns the proxy module for this salt-proxy-minion ''' ret = LazyLoader( _module_dirs(opts, 'proxy'), opts, tag='proxy', pack={'__salt__': functions, '__ret__': returners, '__utils__': utils}, ) ret.pack['__proxy__'] = ret return ret def returners(opts, functions, whitelist=None, context=None, proxy=None): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'returners', 'returner'), opts, tag='returner', whitelist=whitelist, pack={'__salt__': functions, '__context__': context, '__proxy__': proxy or {}}, ) def utils(opts, whitelist=None, context=None, proxy=proxy): ''' Returns the utility modules ''' return LazyLoader( _module_dirs(opts, 'utils', ext_type_dirs='utils_dirs'), opts, tag='utils', whitelist=whitelist, pack={'__context__': context, '__proxy__': proxy or {}}, ) def pillars(opts, functions, context=None): ''' Returns the pillars modules ''' ret = LazyLoader(_module_dirs(opts, 'pillar'), opts, tag='pillar', pack={'__salt__': functions, '__context__': context, '__utils__': utils(opts)}) ret.pack['__ext_pillar__'] = ret return FilterDictWrapper(ret, '.ext_pillar') def tops(opts): ''' Returns the tops modules ''' if 'master_tops' not in opts: return {} whitelist = list(opts['master_tops'].keys()) ret = LazyLoader( _module_dirs(opts, 'tops', 'top'), opts, tag='top', whitelist=whitelist, ) return FilterDictWrapper(ret, '.top') def wheels(opts, whitelist=None, context=None): ''' Returns the wheels modules ''' if context is None: context = {} return LazyLoader( _module_dirs(opts, 'wheel'), opts, tag='wheel', whitelist=whitelist, pack={'__context__': context}, ) def outputters(opts): ''' Returns the outputters modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only outputters present in the keyspace ''' ret = LazyLoader( _module_dirs(opts, 'output', ext_type_dirs='outputter_dirs'), opts, tag='output', ) wrapped_ret = FilterDictWrapper(ret, '.output') # TODO: this name seems terrible... __salt__ should always be execution mods ret.pack['__salt__'] = wrapped_ret return wrapped_ret def serializers(opts): ''' Returns the serializers modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only serializers present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'serializers'), opts, tag='serializers', ) def eauth_tokens(opts): ''' Returns the tokens modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only token backends present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'tokens'), opts, tag='tokens', ) def auth(opts, whitelist=None): ''' Returns the auth modules :param dict opts: The Salt options dictionary :returns: LazyLoader ''' return LazyLoader( _module_dirs(opts, 'auth'), opts, tag='auth', whitelist=whitelist, pack={'__salt__': minion_mods(opts)}, ) def fileserver(opts, backends): ''' Returns the file server modules ''' return LazyLoader(_module_dirs(opts, 'fileserver'), opts, tag='fileserver', whitelist=backends, pack={'__utils__': utils(opts)}) def roster(opts, runner=None, utils=None, whitelist=None): ''' Returns the roster modules ''' return LazyLoader( _module_dirs(opts, 'roster'), opts, tag='roster', whitelist=whitelist, pack={ '__runner__': runner, '__utils__': utils, }, ) def thorium(opts, functions, runners): ''' Load the thorium runtime modules ''' pack = {'__salt__': functions, '__runner__': runners, '__context__': {}} ret = LazyLoader(_module_dirs(opts, 'thorium'), opts, tag='thorium', pack=pack) ret.pack['__thorium__'] = ret return ret def beacons(opts, functions, context=None, proxy=None): ''' Load the beacon modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. ''' return LazyLoader( _module_dirs(opts, 'beacons'), opts, tag='beacons', pack={'__context__': context, '__salt__': functions, '__proxy__': proxy or {}}, virtual_funcs=[], ) def log_handlers(opts): ''' Returns the custom logging handler modules :param dict opts: The Salt options dictionary ''' ret = LazyLoader( _module_dirs( opts, 'log_handlers', int_type='handlers', base_path=os.path.join(SALT_BASE_PATH, 'log'), ), opts, tag='log_handlers', ) return FilterDictWrapper(ret, '.setup_handlers') def ssh_wrapper(opts, functions=None, context=None): ''' Returns the custom logging handler modules ''' return LazyLoader( _module_dirs( opts, 'wrapper', base_path=os.path.join(SALT_BASE_PATH, os.path.join('client', 'ssh')), ), opts, tag='wrapper', pack={ '__salt__': functions, '__grains__': opts.get('grains', {}), '__pillar__': opts.get('pillar', {}), '__context__': context, }, ) def render(opts, functions, states=None, proxy=None, context=None): ''' Returns the render modules ''' if context is None: context = {} pack = {'__salt__': functions, '__grains__': opts.get('grains', {}), '__context__': context} if states: pack['__states__'] = states pack['__proxy__'] = proxy or {} ret = LazyLoader( _module_dirs( opts, 'renderers', 'render', ext_type_dirs='render_dirs', ), opts, tag='render', pack=pack, ) rend = FilterDictWrapper(ret, '.render') if not check_render_pipe_str(opts['renderer'], rend, opts['renderer_blacklist'], opts['renderer_whitelist']): err = ('The renderer {0} is unavailable, this error is often because ' 'the needed software is unavailable'.format(opts['renderer'])) log.critical(err) raise LoaderError(err) return rend def grain_funcs(opts, proxy=None): ''' Returns the grain functions .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') grainfuncs = salt.loader.grain_funcs(__opts__) ''' ret = LazyLoader( _module_dirs( opts, 'grains', 'grain', ext_type_dirs='grains_dirs', ), opts, tag='grains', ) ret.pack['__utils__'] = utils(opts, proxy=proxy) return ret def _load_cached_grains(opts, cfn): ''' Returns the grains cached in cfn, or None if the cache is too old or is corrupted. ''' if not os.path.isfile(cfn): log.debug('Grains cache file does not exist.') return None grains_cache_age = int(time.time() - os.path.getmtime(cfn)) if grains_cache_age > opts.get('grains_cache_expiration', 300): log.debug( 'Grains cache last modified %s seconds ago and cache ' 'expiration is set to %s. Grains cache expired. ' 'Refreshing.', grains_cache_age, opts.get('grains_cache_expiration', 300) ) return None if opts.get('refresh_grains_cache', False): log.debug('refresh_grains_cache requested, Refreshing.') return None log.debug('Retrieving grains from cache') try: serial = salt.payload.Serial(opts) with salt.utils.files.fopen(cfn, 'rb') as fp_: cached_grains = salt.utils.data.decode(serial.load(fp_), preserve_tuples=True) if not cached_grains: log.debug('Cached grains are empty, cache might be corrupted. Refreshing.') return None return cached_grains except (IOError, OSError): return None def grains(opts, force_refresh=False, proxy=None): ''' Return the functions for the dynamic grains and the values for the static grains. Since grains are computed early in the startup process, grains functions do not have __salt__ or __proxy__ available. At proxy-minion startup, this function is called with the proxymodule LazyLoader object so grains functions can communicate with their controlled device. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) print __grains__['id'] ''' # Need to re-import salt.config, somehow it got lost when a minion is starting import salt.config # if we have no grains, lets try loading from disk (TODO: move to decorator?) cfn = os.path.join( opts['cachedir'], 'grains.cache.p' ) if not force_refresh and opts.get('grains_cache', False): cached_grains = _load_cached_grains(opts, cfn) if cached_grains: return cached_grains else: log.debug('Grains refresh requested. Refreshing grains.') if opts.get('skip_grains', False): return {} grains_deep_merge = opts.get('grains_deep_merge', False) is True if 'conf_file' in opts: pre_opts = {} pre_opts.update(salt.config.load_config( opts['conf_file'], 'SALT_MINION_CONFIG', salt.config.DEFAULT_MINION_OPTS['conf_file'] )) default_include = pre_opts.get( 'default_include', opts['default_include'] ) include = pre_opts.get('include', []) pre_opts.update(salt.config.include_config( default_include, opts['conf_file'], verbose=False )) pre_opts.update(salt.config.include_config( include, opts['conf_file'], verbose=True )) if 'grains' in pre_opts: opts['grains'] = pre_opts['grains'] else: opts['grains'] = {} else: opts['grains'] = {} grains_data = {} blist = opts.get('grains_blacklist', []) funcs = grain_funcs(opts, proxy=proxy) if force_refresh: # if we refresh, lets reload grain modules funcs.clear() # Run core grains for key in funcs: if not key.startswith('core.'): continue log.trace('Loading %s grain', key) ret = funcs[key]() if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) # Run the rest of the grains for key in funcs: if key.startswith('core.') or key == '_errors': continue try: # Grains are loaded too early to take advantage of the injected # __proxy__ variable. Pass an instance of that LazyLoader # here instead to grains functions if the grains functions take # one parameter. Then the grains can have access to the # proxymodule for retrieving information from the connected # device. log.trace('Loading %s grain', key) parameters = salt.utils.args.get_function_argspec(funcs[key]).args kwargs = {} if 'proxy' in parameters: kwargs['proxy'] = proxy if 'grains' in parameters: kwargs['grains'] = grains_data ret = funcs[key](**kwargs) except Exception: if salt.utils.platform.is_proxy(): log.info('The following CRITICAL message may not be an error; the proxy may not be completely established yet.') log.critical( 'Failed to load grains defined in grain file %s in ' 'function %s, error:\n', key, funcs[key], exc_info=True ) continue if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) if opts.get('proxy_merge_grains_in_module', True) and proxy: try: proxytype = proxy.opts['proxy']['proxytype'] if proxytype + '.grains' in proxy: if proxytype + '.initialized' in proxy and proxy[proxytype + '.initialized'](): try: proxytype = proxy.opts['proxy']['proxytype'] ret = proxy[proxytype + '.grains']() if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) except Exception: log.critical('Failed to run proxy\'s grains function!', exc_info=True ) except KeyError: pass grains_data.update(opts['grains']) # Write cache if enabled if opts.get('grains_cache', False): with salt.utils.files.set_umask(0o077): try: if salt.utils.platform.is_windows(): # Late import import salt.modules.cmdmod # Make sure cache file isn't read-only salt.modules.cmdmod._run_quiet('attrib -R "{0}"'.format(cfn)) with salt.utils.files.fopen(cfn, 'w+b') as fp_: try: serial = salt.payload.Serial(opts) serial.dump(grains_data, fp_) except TypeError as e: log.error('Failed to serialize grains cache: %s', e) raise # re-throw for cleanup except Exception as e: log.error('Unable to write to grains cache file %s: %s', cfn, e) # Based on the original exception, the file may or may not have been # created. If it was, we will remove it now, as the exception means # the serialized data is not to be trusted, no matter what the # exception is. if os.path.isfile(cfn): os.unlink(cfn) if grains_deep_merge: salt.utils.dictupdate.update(grains_data, opts['grains']) else: grains_data.update(opts['grains']) return salt.utils.data.decode(grains_data, preserve_tuples=True) # TODO: get rid of? Does anyone use this? You should use raw() instead def call(fun, **kwargs): ''' Directly call a function inside a loader directory ''' args = kwargs.get('args', []) dirs = kwargs.get('dirs', []) funcs = LazyLoader( [os.path.join(SALT_BASE_PATH, 'modules')] + dirs, None, tag='modules', virtual_enable=False, ) return funcs[fun](*args) def runner(opts, utils=None, context=None, whitelist=None): ''' Directly call a function inside a loader directory ''' if utils is None: utils = {} if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'runners', 'runner', ext_type_dirs='runner_dirs'), opts, tag='runners', pack={'__utils__': utils, '__context__': context}, whitelist=whitelist, ) # TODO: change from __salt__ to something else, we overload __salt__ too much ret.pack['__salt__'] = ret return ret def queues(opts): ''' Directly call a function inside a loader directory ''' return LazyLoader( _module_dirs(opts, 'queues', 'queue', ext_type_dirs='queue_dirs'), opts, tag='queues', ) def sdb(opts, functions=None, whitelist=None, utils=None): ''' Make a very small database call ''' if utils is None: utils = {} return LazyLoader( _module_dirs(opts, 'sdb'), opts, tag='sdb', pack={ '__sdb__': functions, '__opts__': opts, '__utils__': utils, '__salt__': minion_mods(opts, utils), }, whitelist=whitelist, ) def pkgdb(opts): ''' Return modules for SPM's package database .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgdb', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgdb' ) def pkgfiles(opts): ''' Return modules for SPM's file handling .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgfiles', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgfiles' ) def clouds(opts): ''' Return the cloud functions ''' # Let's bring __active_provider_name__, defaulting to None, to all cloud # drivers. This will get temporarily updated/overridden with a context # manager when needed. functions = LazyLoader( _module_dirs(opts, 'clouds', 'cloud', base_path=os.path.join(SALT_BASE_PATH, 'cloud'), int_type='clouds'), opts, tag='clouds', pack={'__utils__': salt.loader.utils(opts), '__active_provider_name__': None}, ) for funcname in LIBCLOUD_FUNCS_NOT_SUPPORTED: log.trace( '\'%s\' has been marked as not supported. Removing from the ' 'list of supported cloud functions', funcname ) functions.pop(funcname, None) return functions def netapi(opts): ''' Return the network api functions ''' return LazyLoader( _module_dirs(opts, 'netapi'), opts, tag='netapi', ) def executors(opts, functions=None, context=None, proxy=None): ''' Returns the executor modules ''' executors = LazyLoader( _module_dirs(opts, 'executors', 'executor'), opts, tag='executor', pack={'__salt__': functions, '__context__': context or {}, '__proxy__': proxy or {}}, ) executors.pack['__executors__'] = executors return executors def cache(opts, serial): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'cache', 'cache'), opts, tag='cache', pack={'__opts__': opts, '__context__': {'serial': serial}}, ) def _generate_module(name): if name in sys.modules: return code = "'''Salt loaded {0} parent module'''".format(name.split('.')[-1]) # ModuleType can't accept a unicode type on PY2 module = types.ModuleType(str(name)) # future lint: disable=blacklisted-function exec(code, module.__dict__) sys.modules[name] = module def _mod_type(module_path): if module_path.startswith(SALT_BASE_PATH): return 'int' return 'ext' def _inject_into_mod(mod, name, value, force_lock=False): ''' Inject a variable into a module. This is used to inject "globals" like ``__salt__``, ``__pillar``, or ``grains``. Instead of injecting the value directly, a ``ThreadLocalProxy`` is created. If such a proxy is already present under the specified name, it is updated with the new value. This update only affects the current thread, so that the same name can refer to different values depending on the thread of execution. This is important for data that is not truly global. For example, pillar data might be dynamically overriden through function parameters and thus the actual values available in pillar might depend on the thread that is calling a module. mod: module object into which the value is going to be injected. name: name of the variable that is injected into the module. value: value that is injected into the variable. The value is not injected directly, but instead set as the new reference of the proxy that has been created for the variable. force_lock: whether the lock should be acquired before checking whether a proxy object for the specified name has already been injected into the module. If ``False`` (the default), this function checks for the module's variable without acquiring the lock and only acquires the lock if a new proxy has to be created and injected. ''' old_value = getattr(mod, name, None) # We use a double-checked locking scheme in order to avoid taking the lock # when a proxy object has already been injected. # In most programming languages, double-checked locking is considered # unsafe when used without explicit memory barriers because one might read # an uninitialized value. In CPython it is safe due to the global # interpreter lock (GIL). In Python implementations that do not have the # GIL, it could be unsafe, but at least Jython also guarantees that (for # Python objects) memory is not corrupted when writing and reading without # explicit synchronization # (http://www.jython.org/jythonbook/en/1.0/Concurrency.html). # Please note that in order to make this code safe in a runtime environment # that does not make this guarantees, it is not sufficient. The # ThreadLocalProxy must also be created with fallback_to_shared set to # False or a lock must be added to the ThreadLocalProxy. if force_lock: with _inject_into_mod.lock: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: setattr(mod, name, ThreadLocalProxy(value, True)) else: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: _inject_into_mod(mod, name, value, True) # Lock used when injecting globals. This is needed to avoid a race condition # when two threads try to load the same module concurrently. This must be # outside the loader because there might be more than one loader for the same # namespace. _inject_into_mod.lock = threading.RLock() # TODO: move somewhere else? class FilterDictWrapper(MutableMapping): ''' Create a dict which wraps another dict with a specific key suffix on get This is to replace "filter_load" ''' def __init__(self, d, suffix): self._dict = d self.suffix = suffix def __setitem__(self, key, val): self._dict[key] = val def __delitem__(self, key): del self._dict[key] def __getitem__(self, key): return self._dict[key + self.suffix] def __len__(self): return len(self._dict) def __iter__(self): for key in self._dict: if key.endswith(self.suffix): yield key.replace(self.suffix, '') class LazyLoader(salt.utils.lazy.LazyDict): ''' A pseduo-dictionary which has a set of keys which are the name of the module and function, delimited by a dot. When the value of the key is accessed, the function is then loaded from disk and into memory. .. note:: Iterating over keys will cause all modules to be loaded. :param list module_dirs: A list of directories on disk to search for modules :param dict opts: The salt options dictionary. :param str tag: The tag for the type of module to load :param func mod_type_check: A function which can be used to verify files :param dict pack: A dictionary of function to be packed into modules as they are loaded :param list whitelist: A list of modules to whitelist :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules. :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality. If not true, the module will not load. :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values are function references themselves which are loaded on-demand. # TODO: - move modules_max_memory into here - singletons (per tag) ''' mod_dict_class = salt.utils.odict.OrderedDict def __init__(self, module_dirs, opts=None, tag='module', loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, proxy=None, virtual_funcs=None, ): # pylint: disable=W0231 ''' In pack, if any of the values are None they will be replaced with an empty context-specific dict ''' self.inject_globals = {} self.pack = {} if pack is None else pack if opts is None: opts = {} threadsafety = not opts.get('multiprocessing') self.context_dict = salt.utils.context.ContextDict(threadsafe=threadsafety) self.opts = self.__prep_mod_opts(opts) self.module_dirs = module_dirs self.tag = tag self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME self.mod_type_check = mod_type_check or _mod_type if '__context__' not in self.pack: self.pack['__context__'] = None for k, v in six.iteritems(self.pack): if v is None: # if the value of a pack is None, lets make an empty dict value = self.context_dict.get(k, {}) if isinstance(value, ThreadLocalProxy): value = ThreadLocalProxy.unproxy(value) self.context_dict[k] = value self.pack[k] = salt.utils.context.NamespacedDictWrapper(self.context_dict, k) self.whitelist = whitelist self.virtual_enable = virtual_enable self.initial_load = True # names of modules that we don't have (errors, __virtual__, etc.) self.missing_modules = {} # mapping of name -> error self.loaded_modules = {} # mapping of module_name -> dict_of_functions self.loaded_files = set() # TODO: just remove them from file_mapping? self.static_modules = static_modules if static_modules else [] if virtual_funcs is None: virtual_funcs = [] self.virtual_funcs = virtual_funcs self.disabled = set( self.opts.get( 'disable_{0}{1}'.format( self.tag, '' if self.tag[-1] == 's' else 's' ), [] ) ) # A map of suffix to description for imp self.suffix_map = {} # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [''] for (suffix, mode, kind) in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) self._lock = threading.RLock() self._refresh_file_mapping() super(LazyLoader, self).__init__() # late init the lazy loader # create all of the import namespaces _generate_module('{0}.int'.format(self.loaded_base_name)) _generate_module('{0}.int.{1}'.format(self.loaded_base_name, tag)) _generate_module('{0}.ext'.format(self.loaded_base_name)) _generate_module('{0}.ext.{1}'.format(self.loaded_base_name, tag)) def __getitem__(self, item): ''' Override the __getitem__ in order to decorate the returned function if we need to last-minute inject globals ''' func = super(LazyLoader, self).__getitem__(item) if self.inject_globals: return global_injector_decorator(self.inject_globals)(func) else: return func def __getattr__(self, mod_name): ''' Allow for "direct" attribute access-- this allows jinja templates to access things like `salt.test.ping()` ''' if mod_name in ('__getstate__', '__setstate__'): return object.__getattribute__(self, mod_name) # if we have an attribute named that, lets return it. try: return object.__getattr__(self, mod_name) # pylint: disable=no-member except AttributeError: pass # otherwise we assume its jinja template access if mod_name not in self.loaded_modules and not self.loaded: for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and mod_name in self.loaded_modules: break if mod_name in self.loaded_modules: return self.loaded_modules[mod_name] else: raise AttributeError(mod_name) def missing_fun_string(self, function_name): ''' Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ''' mod_name = function_name.split('.')[0] if mod_name in self.loaded_modules: return '\'{0}\' is not available.'.format(function_name) else: try: reason = self.missing_modules[mod_name] except KeyError: return '\'{0}\' is not available.'.format(function_name) else: if reason is not None: return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason) else: return '\'{0}\' __virtual__ returned False'.format(mod_name) def _refresh_file_mapping(self): ''' refresh the mapping of the FS on disk ''' # map of suffix to description for imp if self.opts.get('cython_enable', True) is True: try: global pyximport pyximport = __import__('pyximport') # pylint: disable=import-error pyximport.install() # add to suffix_map so file_mapping will pick it up self.suffix_map['.pyx'] = tuple() except ImportError: log.info('Cython is enabled in the options but not present ' 'in the system path. Skipping Cython modules.') # Allow for zipimport of modules if self.opts.get('enable_zip_modules', True) is True: self.suffix_map['.zip'] = tuple() # allow for module dirs if USE_IMPORTLIB: self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY) else: self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY) # create mapping of filename (without suffix) to (path, suffix) # The files are added in order of priority, so order *must* be retained. self.file_mapping = salt.utils.odict.OrderedDict() opt_match = [] def _replace_pre_ext(obj): ''' Hack so we can get the optimization level that we replaced (if any) out of the re.sub call below. We use a list here because it is a persistent data structure that we will be able to access after re.sub is called. ''' opt_match.append(obj) return '' for mod_dir in self.module_dirs: try: # Make sure we have a sorted listdir in order to have # expectable override results files = sorted( x for x in os.listdir(mod_dir) if x != '__pycache__' ) except OSError: continue # Next mod_dir if six.PY3: try: pycache_files = [ os.path.join('__pycache__', x) for x in sorted(os.listdir(os.path.join(mod_dir, '__pycache__'))) ] except OSError: pass else: files.extend(pycache_files) for filename in files: try: dirname, basename = os.path.split(filename) if basename.startswith('_'): # skip private modules # log messages omitted for obviousness continue # Next filename f_noext, ext = os.path.splitext(basename) if six.PY3: f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext) try: opt_level = int( opt_match.pop().group(1).rsplit('-', 1)[-1] ) except (AttributeError, IndexError, ValueError): # No regex match or no optimization level matched opt_level = 0 try: opt_index = self.opts['optimization_order'].index(opt_level) except KeyError: log.trace( 'Disallowed optimization level %d for module ' 'name \'%s\', skipping. Add %d to the ' '\'optimization_order\' config option if you ' 'do not want to ignore this optimization ' 'level.', opt_level, f_noext, opt_level ) continue else: # Optimization level not reflected in filename on PY2 opt_index = 0 # make sure it is a suffix we support if ext not in self.suffix_map: continue # Next filename if f_noext in self.disabled: log.trace( 'Skipping %s, it is disabled by configuration', filename ) continue # Next filename fpath = os.path.join(mod_dir, filename) # if its a directory, lets allow us to load that if ext == '': # is there something __init__? subfiles = os.listdir(fpath) for suffix in self.suffix_order: if '' == suffix: continue # Next suffix (__init__ must have a suffix) init_file = '__init__{0}'.format(suffix) if init_file in subfiles: break else: continue # Next filename try: curr_ext = self.file_mapping[f_noext][1] curr_opt_index = self.file_mapping[f_noext][2] except KeyError: pass else: if '' in (curr_ext, ext) and curr_ext != ext: log.error( 'Module/package collision: \'%s\' and \'%s\'', fpath, self.file_mapping[f_noext][0] ) if six.PY3 and ext == '.pyc' and curr_ext == '.pyc': # Check the optimization level if opt_index >= curr_opt_index: # Module name match, but a higher-priority # optimization level was already matched, skipping. continue elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext): # Match found but a higher-priorty match already # exists, so skip this. continue if six.PY3 and not dirname and ext == '.pyc': # On Python 3, we should only load .pyc files from the # __pycache__ subdirectory (i.e. when dirname is not an # empty string). continue # Made it this far - add it self.file_mapping[f_noext] = (fpath, ext, opt_index) except OSError: continue for smod in self.static_modules: f_noext = smod.split('.')[-1] self.file_mapping[f_noext] = (smod, '.o', 0) def clear(self): ''' Clear the dict ''' with self._lock: super(LazyLoader, self).clear() # clear the lazy loader self.loaded_files = set() self.missing_modules = {} self.loaded_modules = {} # if we have been loaded before, lets clear the file mapping since # we obviously want a re-do if hasattr(self, 'opts'): self._refresh_file_mapping() self.initial_load = False def __prep_mod_opts(self, opts): ''' Strip out of the opts any logger instance ''' if '__grains__' not in self.pack: grains = opts.get('grains', {}) if isinstance(grains, ThreadLocalProxy): grains = ThreadLocalProxy.unproxy(grains) self.context_dict['grains'] = grains self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains') if '__pillar__' not in self.pack: pillar = opts.get('pillar', {}) if isinstance(pillar, ThreadLocalProxy): pillar = ThreadLocalProxy.unproxy(pillar) self.context_dict['pillar'] = pillar self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar') mod_opts = {} for key, val in list(opts.items()): if key == 'logger': continue mod_opts[key] = val return mod_opts def _iter_files(self, mod_name): ''' Iterate over all file_mapping files in order of closeness to mod_name ''' # do we have an exact match? if mod_name in self.file_mapping: yield mod_name # do we have a partial match? for k in self.file_mapping: if mod_name in k: yield k # anyone else? Bueller? for k in self.file_mapping: if mod_name not in k: yield k def _reload_submodules(self, mod): submodules = ( getattr(mod, sname) for sname in dir(mod) if isinstance(getattr(mod, sname), mod.__class__) ) # reload only custom "sub"modules for submodule in submodules: # it is a submodule if the name is in a namespace under mod if submodule.__name__.startswith(mod.__name__ + '.'): reload_module(submodule) self._reload_submodules(submodule) def _load_module(self, name): mod = None fpath, suffix = self.file_mapping[name][:2] self.loaded_files.add(name) fpath_dirname = os.path.dirname(fpath) try: sys.path.append(fpath_dirname) if suffix == '.pyx': mod = pyximport.load_module(name, fpath, tempfile.gettempdir()) elif suffix == '.o': top_mod = __import__(fpath, globals(), locals(), []) comps = fpath.split('.') if len(comps) < 2: mod = top_mod else: mod = top_mod for subname in comps[1:]: mod = getattr(mod, subname) elif suffix == '.zip': mod = zipimporter(fpath).load_module(name) else: desc = self.suffix_map[suffix] # if it is a directory, we don't open a file try: mod_namespace = '.'.join(( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name)) except TypeError: mod_namespace = '{0}.{1}.{2}.{3}'.format( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name) if suffix == '': if USE_IMPORTLIB: # pylint: disable=no-member # Package directory, look for __init__ loader_details = [ (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES), (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES), (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), ] file_finder = importlib.machinery.FileFinder( fpath_dirname, *loader_details ) spec = file_finder.find_spec(mod_namespace) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: mod = imp.load_module(mod_namespace, None, fpath, desc) # reload all submodules if necessary if not self.initial_load: self._reload_submodules(mod) else: if USE_IMPORTLIB: # pylint: disable=no-member loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath) spec = importlib.util.spec_from_file_location( mod_namespace, fpath, loader=loader ) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() #mod = importlib.util.module_from_spec(spec) #spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: with salt.utils.files.fopen(fpath, desc[1]) as fn_: mod = imp.load_module(mod_namespace, fn_, fpath, desc) except IOError: raise except ImportError as exc: if 'magic number' in six.text_type(exc): error_msg = 'Failed to import {0} {1}. Bad magic number. If migrating from Python2 to Python3, remove all .pyc files and try again.'.format(self.tag, name) log.warning(error_msg) self.missing_modules[name] = error_msg log.debug( 'Failed to import %s %s:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = exc return False except Exception as error: log.error( 'Failed to import %s %s, this is due most likely to a ' 'syntax error:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False except SystemExit as error: try: fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1] except Exception: pass else: tgt_fn = os.path.join('salt', 'utils', 'process.py') if fn_.endswith(tgt_fn) and '_handle_signals' in caller: # Race conditon, SIGTERM or SIGINT received while loader # was in process of loading a module. Call sys.exit to # ensure that the process is killed. sys.exit(salt.defaults.exitcodes.EX_OK) log.error( 'Failed to import %s %s as the module called exit()\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False finally: sys.path.remove(fpath_dirname) if hasattr(mod, '__opts__'): mod.__opts__.update(self.opts) else: mod.__opts__ = self.opts # pack whatever other globals we were asked to for p_name, p_value in six.iteritems(self.pack): _inject_into_mod(mod, p_name, p_value) module_name = mod.__name__.rsplit('.', 1)[-1] # Call a module's initialization method if it exists module_init = getattr(mod, '__init__', None) if inspect.isfunction(module_init): try: module_init(self.opts) except TypeError as e: log.error(e) except Exception: err_string = '__init__ failed' log.debug( 'Error loading %s.%s: %s', self.tag, module_name, err_string, exc_info=True ) self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False # if virtual modules are enabled, we need to look for the # __virtual__() function inside that module and run it. if self.virtual_enable: virtual_funcs_to_process = ['__virtual__'] + self.virtual_funcs for virtual_func in virtual_funcs_to_process: virtual_ret, module_name, virtual_err, virtual_aliases = \ self._process_virtual(mod, module_name, virtual_func) if virtual_err is not None: log.trace( 'Error loading %s.%s: %s', self.tag, module_name, virtual_err ) # if _process_virtual returned a non-True value then we are # supposed to not process this module if virtual_ret is not True and module_name not in self.missing_modules: # If a module has information about why it could not be loaded, record it self.missing_modules[module_name] = virtual_err self.missing_modules[name] = virtual_err return False else: virtual_aliases = () # If this is a proxy minion then MOST modules cannot work. Therefore, require that # any module that does work with salt-proxy-minion define __proxyenabled__ as a list # containing the names of the proxy types that the module supports. # # Render modules and state modules are OK though if 'proxy' in self.opts: if self.tag in ['grains', 'proxy']: if not hasattr(mod, '__proxyenabled__') or \ (self.opts['proxy']['proxytype'] not in mod.__proxyenabled__ and '*' not in mod.__proxyenabled__): err_string = 'not a proxy_minion enabled module' self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False if getattr(mod, '__load__', False) is not False: log.info( 'The functions from module \'%s\' are being loaded from the ' 'provided __load__ attribute', module_name ) # If we had another module by the same virtual name, we should put any # new functions under the existing dictionary. mod_names = [module_name] + list(virtual_aliases) mod_dict = dict(( (x, self.loaded_modules.get(x, self.mod_dict_class())) for x in mod_names )) for attr in getattr(mod, '__load__', dir(mod)): if attr.startswith('_') and attr != '__call__': # private functions are skipped, # except __call__ which is default entrance # for multi-function batch-like state syntax continue func = getattr(mod, attr) if not inspect.isfunction(func) and not isinstance(func, functools.partial): # Not a function!? Skip it!!! continue # Let's get the function name. # If the module has the __func_alias__ attribute, it must be a # dictionary mapping in the form of(key -> value): # <real-func-name> -> <desired-func-name> # # It default's of course to the found callable attribute name # if no alias is defined. funcname = getattr(mod, '__func_alias__', {}).get(attr, attr) for tgt_mod in mod_names: try: full_funcname = '.'.join((tgt_mod, funcname)) except TypeError: full_funcname = '{0}.{1}'.format(tgt_mod, funcname) # Save many references for lookups # Careful not to overwrite existing (higher priority) functions if full_funcname not in self._dict: self._dict[full_funcname] = func if funcname not in mod_dict[tgt_mod]: setattr(mod_dict[tgt_mod], funcname, func) mod_dict[tgt_mod][funcname] = func self._apply_outputter(func, mod) # enforce depends try: Depends.enforce_dependencies(self._dict, self.tag) except RuntimeError as exc: log.info( 'Depends.enforce_dependencies() failed for the following ' 'reason: %s', exc ) for tgt_mod in mod_names: self.loaded_modules[tgt_mod] = mod_dict[tgt_mod] return True def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise KeyError('The key \'{0}\' should contain a \'.\''.format(key)) mod_name, _ = key.split('.', 1) with self._lock: # It is possible that the key is in the dictionary after # acquiring the lock due to another thread loading it. if mod_name in self.missing_modules or key in self._dict: return True # if the modulename isn't in the whitelist, don't bother if self.whitelist and mod_name not in self.whitelist: log.error( 'Failed to load function %s because its module (%s) is ' 'not in the whitelist: %s', key, mod_name, self.whitelist ) raise KeyError(key) def _inner_load(mod_name): for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and key in self._dict: return True return False # try to load the module ret = None reloaded = False # re-scan up to once, IOErrors or a failed load cause re-scans of the # filesystem while True: try: ret = _inner_load(mod_name) if not reloaded and ret is not True: self._refresh_file_mapping() reloaded = True continue break except IOError: if not reloaded: self._refresh_file_mapping() reloaded = True continue return ret def _load_all(self): ''' Load all of them ''' with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True def reload_modules(self): with self._lock: self.loaded_files = set() self._load_all() def _apply_outputter(self, func, mod): ''' Apply the __outputter__ variable to the functions ''' if hasattr(mod, '__outputter__'): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__] def _process_virtual(self, mod, module_name, virtual_func='__virtual__'): ''' Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1] ''' # The __virtual__ function will return either a True or False value. # If it returns a True value it can also set a module level attribute # named __virtualname__ with the name that the module should be # referred to as. # # This allows us to have things like the pkg module working on all # platforms under the name 'pkg'. It also allows for modules like # augeas_cfg to be referred to as 'augeas', which would otherwise have # namespace collisions. And finally it allows modules to return False # if they are not intended to run on the given platform or are missing # dependencies. virtual_aliases = getattr(mod, '__virtual_aliases__', tuple()) try: error_reason = None if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__): try: start = time.time() virtual = getattr(mod, virtual_func)() if isinstance(virtual, tuple): error_reason = virtual[1] virtual = virtual[0] if self.opts.get('virtual_timer', False): end = time.time() - start msg = 'Virtual function took {0} seconds for {1}'.format( end, module_name) log.warning(msg) except Exception as exc: error_reason = ( 'Exception raised when processing __virtual__ function' ' for {0}. Module will not be loaded: {1}'.format( mod.__name__, exc)) log.error(error_reason, exc_info_on_loglevel=logging.DEBUG) virtual = None # Get the module's virtual name virtualname = getattr(mod, '__virtualname__', virtual) if not virtual: # if __virtual__() evaluates to False then the module # wasn't meant for this platform or it's not supposed to # load for some other reason. # Some modules might accidentally return None and are # improperly loaded if virtual is None: log.warning( '%s.__virtual__() is wrongly returning `None`. ' 'It should either return `True`, `False` or a new ' 'name. If you\'re the developer of the module ' '\'%s\', please fix this.', mod.__name__, module_name ) return (False, module_name, error_reason, virtual_aliases) # At this point, __virtual__ did not return a # boolean value, let's check for deprecated usage # or module renames if virtual is not True and module_name != virtual: # The module is renaming itself. Updating the module name # with the new name log.trace('Loaded %s as virtual %s', module_name, virtual) if virtualname != virtual: # The __virtualname__ attribute does not match what's # being returned by the __virtual__() function. This # should be considered an error. log.error( 'The module \'%s\' is showing some bad usage. Its ' '__virtualname__ attribute is set to \'%s\' yet the ' '__virtual__() function is returning \'%s\'. These ' 'values should match!', mod.__name__, virtualname, virtual ) module_name = virtualname # If the __virtual__ function returns True and __virtualname__ # is set then use it elif virtual is True and virtualname != module_name: if virtualname is not True: module_name = virtualname except KeyError: # Key errors come out of the virtual function when passing # in incomplete grains sets, these can be safely ignored # and logged to debug, still, it includes the traceback to # help debugging. log.debug('KeyError when loading %s', module_name, exc_info=True) except Exception: # If the module throws an exception during __virtual__() # then log the information and continue to the next. log.error( 'Failed to read the virtual function for %s: %s', self.tag, module_name, exc_info=True ) return (False, module_name, error_reason, virtual_aliases) return (True, module_name, None, virtual_aliases) def global_injector_decorator(inject_globals): ''' Decorator used by the LazyLoader to inject globals into a function at execute time. globals Dictionary with global variables to inject ''' def inner_decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): with salt.utils.context.func_globals_inject(f, **inject_globals): return f(*args, **kwargs) return wrapper return inner_decorator
saltstack/salt
salt/loader.py
beacons
python
def beacons(opts, functions, context=None, proxy=None): ''' Load the beacon modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. ''' return LazyLoader( _module_dirs(opts, 'beacons'), opts, tag='beacons', pack={'__context__': context, '__salt__': functions, '__proxy__': proxy or {}}, virtual_funcs=[], )
Load the beacon modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L577-L591
null
# -*- coding: utf-8 -*- ''' The Salt loader is the core to Salt's plugin system, the loader scans directories for python loadable code and organizes the code into the plugin interfaces used by Salt. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import sys import time import logging import inspect import tempfile import threading import functools import threading import traceback import types from zipimport import zipimporter # Import salt libs import salt.config import salt.defaults.events import salt.defaults.exitcodes import salt.syspaths import salt.utils.args import salt.utils.context import salt.utils.data import salt.utils.dictupdate import salt.utils.event import salt.utils.files import salt.utils.lazy import salt.utils.odict import salt.utils.platform import salt.utils.versions import salt.utils.stringutils from salt.exceptions import LoaderError from salt.template import check_render_pipe_str from salt.utils.decorators import Depends from salt.utils.thread_local_proxy import ThreadLocalProxy # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import reload_module if sys.version_info[:2] >= (3, 5): import importlib.machinery # pylint: disable=no-name-in-module,import-error import importlib.util # pylint: disable=no-name-in-module,import-error USE_IMPORTLIB = True else: import imp USE_IMPORTLIB = False try: from collections.abc import MutableMapping except ImportError: from collections import MutableMapping try: import pkg_resources HAS_PKG_RESOURCES = True except ImportError: HAS_PKG_RESOURCES = False log = logging.getLogger(__name__) SALT_BASE_PATH = os.path.abspath(salt.syspaths.INSTALL_DIR) LOADED_BASE_NAME = 'salt.loaded' if USE_IMPORTLIB: # pylint: disable=no-member MODULE_KIND_SOURCE = 1 MODULE_KIND_COMPILED = 2 MODULE_KIND_EXTENSION = 3 MODULE_KIND_PKG_DIRECTORY = 5 SUFFIXES = [] for suffix in importlib.machinery.EXTENSION_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_EXTENSION)) for suffix in importlib.machinery.SOURCE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_SOURCE)) for suffix in importlib.machinery.BYTECODE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_COMPILED)) MODULE_KIND_MAP = { MODULE_KIND_SOURCE: importlib.machinery.SourceFileLoader, MODULE_KIND_COMPILED: importlib.machinery.SourcelessFileLoader, MODULE_KIND_EXTENSION: importlib.machinery.ExtensionFileLoader } # pylint: enable=no-member else: SUFFIXES = imp.get_suffixes() PY3_PRE_EXT = \ re.compile(r'\.cpython-{0}{1}(\.opt-[1-9])?'.format(*sys.version_info[:2])) # Because on the cloud drivers we do `from salt.cloud.libcloudfuncs import *` # which simplifies code readability, it adds some unsupported functions into # the driver's module scope. # We list un-supported functions here. These will be removed from the loaded. # TODO: remove the need for this cross-module code. Maybe use NotImplemented LIBCLOUD_FUNCS_NOT_SUPPORTED = ( 'parallels.avail_sizes', 'parallels.avail_locations', 'proxmox.avail_sizes', ) # Will be set to pyximport module at runtime if cython is enabled in config. pyximport = None def static_loader( opts, ext_type, tag, pack=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, filter_name=None, ): funcs = LazyLoader( _module_dirs( opts, ext_type, tag, int_type, ext_dirs, ext_type_dirs, base_path, ), opts, tag=tag, pack=pack, ) ret = {} funcs._load_all() if filter_name: funcs = FilterDictWrapper(funcs, filter_name) for key in funcs: ret[key] = funcs[key] return ret def _format_entrypoint_target(ep): ''' Makes a string describing the target of an EntryPoint object. Base strongly on EntryPoint.__str__(). ''' s = ep.module_name if ep.attrs: s += ':' + '.'.join(ep.attrs) return s def _module_dirs( opts, ext_type, tag=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, ): if tag is None: tag = ext_type sys_types = os.path.join(base_path or SALT_BASE_PATH, int_type or ext_type) ext_types = os.path.join(opts['extension_modules'], ext_type) ext_type_types = [] if ext_dirs: if ext_type_dirs is None: ext_type_dirs = '{0}_dirs'.format(tag) if ext_type_dirs in opts: ext_type_types.extend(opts[ext_type_dirs]) if HAS_PKG_RESOURCES and ext_type_dirs: for entry_point in pkg_resources.iter_entry_points('salt.loader', ext_type_dirs): try: loaded_entry_point = entry_point.load() for path in loaded_entry_point(): ext_type_types.append(path) except Exception as exc: log.error("Error getting module directories from %s: %s", _format_entrypoint_target(entry_point), exc) log.debug("Full backtrace for module directories error", exc_info=True) cli_module_dirs = [] # The dirs can be any module dir, or a in-tree _{ext_type} dir for _dir in opts.get('module_dirs', []): # Prepend to the list to match cli argument ordering maybe_dir = os.path.join(_dir, ext_type) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) continue maybe_dir = os.path.join(_dir, '_{0}'.format(ext_type)) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) return cli_module_dirs + ext_type_types + [ext_types, sys_types] def minion_mods( opts, context=None, utils=None, whitelist=None, initial_load=False, loaded_base_name=None, notify=False, static_modules=None, proxy=None): ''' Load execution modules Returns a dictionary of execution modules appropriate for the current system by evaluating the __virtual__() function in each module. :param dict opts: The Salt options dictionary :param dict context: A Salt context that should be made present inside generated modules in __context__ :param dict utils: Utility functions which should be made available to Salt modules in __utils__. See `utils_dirs` in salt.config for additional information about configuration. :param list whitelist: A list of modules which should be whitelisted. :param bool initial_load: Deprecated flag! Unused. :param str loaded_base_name: A string marker for the loaded base name. :param bool notify: Flag indicating that an event should be fired upon completion of module loading. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) __opts__['grains'] = __grains__ __utils__ = salt.loader.utils(__opts__) __salt__ = salt.loader.minion_mods(__opts__, utils=__utils__) __salt__['test.ping']() ''' # TODO Publish documentation for module whitelisting if not whitelist: whitelist = opts.get('whitelist_modules', None) ret = LazyLoader( _module_dirs(opts, 'modules', 'module'), opts, tag='module', pack={'__context__': context, '__utils__': utils, '__proxy__': proxy}, whitelist=whitelist, loaded_base_name=loaded_base_name, static_modules=static_modules, ) ret.pack['__salt__'] = ret # Load any provider overrides from the configuration file providers option # Note: Providers can be pkg, service, user or group - not to be confused # with cloud providers. providers = opts.get('providers', False) if providers and isinstance(providers, dict): for mod in providers: # sometimes providers opts is not to diverge modules but # for other configuration try: funcs = raw_mod(opts, providers[mod], ret) except TypeError: break else: if funcs: for func in funcs: f_key = '{0}{1}'.format(mod, func[func.rindex('.'):]) ret[f_key] = funcs[func] if notify: evt = salt.utils.event.get_event('minion', opts=opts, listen=False) evt.fire_event({'complete': True}, tag=salt.defaults.events.MINION_MOD_COMPLETE) return ret def raw_mod(opts, name, functions, mod='modules'): ''' Returns a single module loaded raw and bypassing the __virtual__ function .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') testmod = salt.loader.raw_mod(__opts__, 'test', None) testmod['test.ping']() ''' loader = LazyLoader( _module_dirs(opts, mod, 'module'), opts, tag='rawmodule', virtual_enable=False, pack={'__salt__': functions}, ) # if we don't have the module, return an empty dict if name not in loader.file_mapping: return {} loader._load_module(name) # load a single module (the one passed in) return dict(loader._dict) # return a copy of *just* the funcs for `name` def metaproxy(opts): ''' Return functions used in the meta proxy ''' return LazyLoader( _module_dirs(opts, 'metaproxy'), opts, tag='metaproxy' ) def matchers(opts): ''' Return the matcher services plugins ''' return LazyLoader( _module_dirs(opts, 'matchers'), opts, tag='matchers' ) def engines(opts, functions, runners, utils, proxy=None): ''' Return the master services plugins ''' pack = {'__salt__': functions, '__runners__': runners, '__proxy__': proxy, '__utils__': utils} return LazyLoader( _module_dirs(opts, 'engines'), opts, tag='engines', pack=pack, ) def proxy(opts, functions=None, returners=None, whitelist=None, utils=None): ''' Returns the proxy module for this salt-proxy-minion ''' ret = LazyLoader( _module_dirs(opts, 'proxy'), opts, tag='proxy', pack={'__salt__': functions, '__ret__': returners, '__utils__': utils}, ) ret.pack['__proxy__'] = ret return ret def returners(opts, functions, whitelist=None, context=None, proxy=None): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'returners', 'returner'), opts, tag='returner', whitelist=whitelist, pack={'__salt__': functions, '__context__': context, '__proxy__': proxy or {}}, ) def utils(opts, whitelist=None, context=None, proxy=proxy): ''' Returns the utility modules ''' return LazyLoader( _module_dirs(opts, 'utils', ext_type_dirs='utils_dirs'), opts, tag='utils', whitelist=whitelist, pack={'__context__': context, '__proxy__': proxy or {}}, ) def pillars(opts, functions, context=None): ''' Returns the pillars modules ''' ret = LazyLoader(_module_dirs(opts, 'pillar'), opts, tag='pillar', pack={'__salt__': functions, '__context__': context, '__utils__': utils(opts)}) ret.pack['__ext_pillar__'] = ret return FilterDictWrapper(ret, '.ext_pillar') def tops(opts): ''' Returns the tops modules ''' if 'master_tops' not in opts: return {} whitelist = list(opts['master_tops'].keys()) ret = LazyLoader( _module_dirs(opts, 'tops', 'top'), opts, tag='top', whitelist=whitelist, ) return FilterDictWrapper(ret, '.top') def wheels(opts, whitelist=None, context=None): ''' Returns the wheels modules ''' if context is None: context = {} return LazyLoader( _module_dirs(opts, 'wheel'), opts, tag='wheel', whitelist=whitelist, pack={'__context__': context}, ) def outputters(opts): ''' Returns the outputters modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only outputters present in the keyspace ''' ret = LazyLoader( _module_dirs(opts, 'output', ext_type_dirs='outputter_dirs'), opts, tag='output', ) wrapped_ret = FilterDictWrapper(ret, '.output') # TODO: this name seems terrible... __salt__ should always be execution mods ret.pack['__salt__'] = wrapped_ret return wrapped_ret def serializers(opts): ''' Returns the serializers modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only serializers present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'serializers'), opts, tag='serializers', ) def eauth_tokens(opts): ''' Returns the tokens modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only token backends present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'tokens'), opts, tag='tokens', ) def auth(opts, whitelist=None): ''' Returns the auth modules :param dict opts: The Salt options dictionary :returns: LazyLoader ''' return LazyLoader( _module_dirs(opts, 'auth'), opts, tag='auth', whitelist=whitelist, pack={'__salt__': minion_mods(opts)}, ) def fileserver(opts, backends): ''' Returns the file server modules ''' return LazyLoader(_module_dirs(opts, 'fileserver'), opts, tag='fileserver', whitelist=backends, pack={'__utils__': utils(opts)}) def roster(opts, runner=None, utils=None, whitelist=None): ''' Returns the roster modules ''' return LazyLoader( _module_dirs(opts, 'roster'), opts, tag='roster', whitelist=whitelist, pack={ '__runner__': runner, '__utils__': utils, }, ) def thorium(opts, functions, runners): ''' Load the thorium runtime modules ''' pack = {'__salt__': functions, '__runner__': runners, '__context__': {}} ret = LazyLoader(_module_dirs(opts, 'thorium'), opts, tag='thorium', pack=pack) ret.pack['__thorium__'] = ret return ret def states(opts, functions, utils, serializers, whitelist=None, proxy=None, context=None): ''' Returns the state modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') statemods = salt.loader.states(__opts__, None, None) ''' if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'states'), opts, tag='states', pack={'__salt__': functions, '__proxy__': proxy or {}}, whitelist=whitelist, ) ret.pack['__states__'] = ret ret.pack['__utils__'] = utils ret.pack['__serializers__'] = serializers ret.pack['__context__'] = context return ret def log_handlers(opts): ''' Returns the custom logging handler modules :param dict opts: The Salt options dictionary ''' ret = LazyLoader( _module_dirs( opts, 'log_handlers', int_type='handlers', base_path=os.path.join(SALT_BASE_PATH, 'log'), ), opts, tag='log_handlers', ) return FilterDictWrapper(ret, '.setup_handlers') def ssh_wrapper(opts, functions=None, context=None): ''' Returns the custom logging handler modules ''' return LazyLoader( _module_dirs( opts, 'wrapper', base_path=os.path.join(SALT_BASE_PATH, os.path.join('client', 'ssh')), ), opts, tag='wrapper', pack={ '__salt__': functions, '__grains__': opts.get('grains', {}), '__pillar__': opts.get('pillar', {}), '__context__': context, }, ) def render(opts, functions, states=None, proxy=None, context=None): ''' Returns the render modules ''' if context is None: context = {} pack = {'__salt__': functions, '__grains__': opts.get('grains', {}), '__context__': context} if states: pack['__states__'] = states pack['__proxy__'] = proxy or {} ret = LazyLoader( _module_dirs( opts, 'renderers', 'render', ext_type_dirs='render_dirs', ), opts, tag='render', pack=pack, ) rend = FilterDictWrapper(ret, '.render') if not check_render_pipe_str(opts['renderer'], rend, opts['renderer_blacklist'], opts['renderer_whitelist']): err = ('The renderer {0} is unavailable, this error is often because ' 'the needed software is unavailable'.format(opts['renderer'])) log.critical(err) raise LoaderError(err) return rend def grain_funcs(opts, proxy=None): ''' Returns the grain functions .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') grainfuncs = salt.loader.grain_funcs(__opts__) ''' ret = LazyLoader( _module_dirs( opts, 'grains', 'grain', ext_type_dirs='grains_dirs', ), opts, tag='grains', ) ret.pack['__utils__'] = utils(opts, proxy=proxy) return ret def _load_cached_grains(opts, cfn): ''' Returns the grains cached in cfn, or None if the cache is too old or is corrupted. ''' if not os.path.isfile(cfn): log.debug('Grains cache file does not exist.') return None grains_cache_age = int(time.time() - os.path.getmtime(cfn)) if grains_cache_age > opts.get('grains_cache_expiration', 300): log.debug( 'Grains cache last modified %s seconds ago and cache ' 'expiration is set to %s. Grains cache expired. ' 'Refreshing.', grains_cache_age, opts.get('grains_cache_expiration', 300) ) return None if opts.get('refresh_grains_cache', False): log.debug('refresh_grains_cache requested, Refreshing.') return None log.debug('Retrieving grains from cache') try: serial = salt.payload.Serial(opts) with salt.utils.files.fopen(cfn, 'rb') as fp_: cached_grains = salt.utils.data.decode(serial.load(fp_), preserve_tuples=True) if not cached_grains: log.debug('Cached grains are empty, cache might be corrupted. Refreshing.') return None return cached_grains except (IOError, OSError): return None def grains(opts, force_refresh=False, proxy=None): ''' Return the functions for the dynamic grains and the values for the static grains. Since grains are computed early in the startup process, grains functions do not have __salt__ or __proxy__ available. At proxy-minion startup, this function is called with the proxymodule LazyLoader object so grains functions can communicate with their controlled device. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) print __grains__['id'] ''' # Need to re-import salt.config, somehow it got lost when a minion is starting import salt.config # if we have no grains, lets try loading from disk (TODO: move to decorator?) cfn = os.path.join( opts['cachedir'], 'grains.cache.p' ) if not force_refresh and opts.get('grains_cache', False): cached_grains = _load_cached_grains(opts, cfn) if cached_grains: return cached_grains else: log.debug('Grains refresh requested. Refreshing grains.') if opts.get('skip_grains', False): return {} grains_deep_merge = opts.get('grains_deep_merge', False) is True if 'conf_file' in opts: pre_opts = {} pre_opts.update(salt.config.load_config( opts['conf_file'], 'SALT_MINION_CONFIG', salt.config.DEFAULT_MINION_OPTS['conf_file'] )) default_include = pre_opts.get( 'default_include', opts['default_include'] ) include = pre_opts.get('include', []) pre_opts.update(salt.config.include_config( default_include, opts['conf_file'], verbose=False )) pre_opts.update(salt.config.include_config( include, opts['conf_file'], verbose=True )) if 'grains' in pre_opts: opts['grains'] = pre_opts['grains'] else: opts['grains'] = {} else: opts['grains'] = {} grains_data = {} blist = opts.get('grains_blacklist', []) funcs = grain_funcs(opts, proxy=proxy) if force_refresh: # if we refresh, lets reload grain modules funcs.clear() # Run core grains for key in funcs: if not key.startswith('core.'): continue log.trace('Loading %s grain', key) ret = funcs[key]() if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) # Run the rest of the grains for key in funcs: if key.startswith('core.') or key == '_errors': continue try: # Grains are loaded too early to take advantage of the injected # __proxy__ variable. Pass an instance of that LazyLoader # here instead to grains functions if the grains functions take # one parameter. Then the grains can have access to the # proxymodule for retrieving information from the connected # device. log.trace('Loading %s grain', key) parameters = salt.utils.args.get_function_argspec(funcs[key]).args kwargs = {} if 'proxy' in parameters: kwargs['proxy'] = proxy if 'grains' in parameters: kwargs['grains'] = grains_data ret = funcs[key](**kwargs) except Exception: if salt.utils.platform.is_proxy(): log.info('The following CRITICAL message may not be an error; the proxy may not be completely established yet.') log.critical( 'Failed to load grains defined in grain file %s in ' 'function %s, error:\n', key, funcs[key], exc_info=True ) continue if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) if opts.get('proxy_merge_grains_in_module', True) and proxy: try: proxytype = proxy.opts['proxy']['proxytype'] if proxytype + '.grains' in proxy: if proxytype + '.initialized' in proxy and proxy[proxytype + '.initialized'](): try: proxytype = proxy.opts['proxy']['proxytype'] ret = proxy[proxytype + '.grains']() if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) except Exception: log.critical('Failed to run proxy\'s grains function!', exc_info=True ) except KeyError: pass grains_data.update(opts['grains']) # Write cache if enabled if opts.get('grains_cache', False): with salt.utils.files.set_umask(0o077): try: if salt.utils.platform.is_windows(): # Late import import salt.modules.cmdmod # Make sure cache file isn't read-only salt.modules.cmdmod._run_quiet('attrib -R "{0}"'.format(cfn)) with salt.utils.files.fopen(cfn, 'w+b') as fp_: try: serial = salt.payload.Serial(opts) serial.dump(grains_data, fp_) except TypeError as e: log.error('Failed to serialize grains cache: %s', e) raise # re-throw for cleanup except Exception as e: log.error('Unable to write to grains cache file %s: %s', cfn, e) # Based on the original exception, the file may or may not have been # created. If it was, we will remove it now, as the exception means # the serialized data is not to be trusted, no matter what the # exception is. if os.path.isfile(cfn): os.unlink(cfn) if grains_deep_merge: salt.utils.dictupdate.update(grains_data, opts['grains']) else: grains_data.update(opts['grains']) return salt.utils.data.decode(grains_data, preserve_tuples=True) # TODO: get rid of? Does anyone use this? You should use raw() instead def call(fun, **kwargs): ''' Directly call a function inside a loader directory ''' args = kwargs.get('args', []) dirs = kwargs.get('dirs', []) funcs = LazyLoader( [os.path.join(SALT_BASE_PATH, 'modules')] + dirs, None, tag='modules', virtual_enable=False, ) return funcs[fun](*args) def runner(opts, utils=None, context=None, whitelist=None): ''' Directly call a function inside a loader directory ''' if utils is None: utils = {} if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'runners', 'runner', ext_type_dirs='runner_dirs'), opts, tag='runners', pack={'__utils__': utils, '__context__': context}, whitelist=whitelist, ) # TODO: change from __salt__ to something else, we overload __salt__ too much ret.pack['__salt__'] = ret return ret def queues(opts): ''' Directly call a function inside a loader directory ''' return LazyLoader( _module_dirs(opts, 'queues', 'queue', ext_type_dirs='queue_dirs'), opts, tag='queues', ) def sdb(opts, functions=None, whitelist=None, utils=None): ''' Make a very small database call ''' if utils is None: utils = {} return LazyLoader( _module_dirs(opts, 'sdb'), opts, tag='sdb', pack={ '__sdb__': functions, '__opts__': opts, '__utils__': utils, '__salt__': minion_mods(opts, utils), }, whitelist=whitelist, ) def pkgdb(opts): ''' Return modules for SPM's package database .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgdb', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgdb' ) def pkgfiles(opts): ''' Return modules for SPM's file handling .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgfiles', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgfiles' ) def clouds(opts): ''' Return the cloud functions ''' # Let's bring __active_provider_name__, defaulting to None, to all cloud # drivers. This will get temporarily updated/overridden with a context # manager when needed. functions = LazyLoader( _module_dirs(opts, 'clouds', 'cloud', base_path=os.path.join(SALT_BASE_PATH, 'cloud'), int_type='clouds'), opts, tag='clouds', pack={'__utils__': salt.loader.utils(opts), '__active_provider_name__': None}, ) for funcname in LIBCLOUD_FUNCS_NOT_SUPPORTED: log.trace( '\'%s\' has been marked as not supported. Removing from the ' 'list of supported cloud functions', funcname ) functions.pop(funcname, None) return functions def netapi(opts): ''' Return the network api functions ''' return LazyLoader( _module_dirs(opts, 'netapi'), opts, tag='netapi', ) def executors(opts, functions=None, context=None, proxy=None): ''' Returns the executor modules ''' executors = LazyLoader( _module_dirs(opts, 'executors', 'executor'), opts, tag='executor', pack={'__salt__': functions, '__context__': context or {}, '__proxy__': proxy or {}}, ) executors.pack['__executors__'] = executors return executors def cache(opts, serial): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'cache', 'cache'), opts, tag='cache', pack={'__opts__': opts, '__context__': {'serial': serial}}, ) def _generate_module(name): if name in sys.modules: return code = "'''Salt loaded {0} parent module'''".format(name.split('.')[-1]) # ModuleType can't accept a unicode type on PY2 module = types.ModuleType(str(name)) # future lint: disable=blacklisted-function exec(code, module.__dict__) sys.modules[name] = module def _mod_type(module_path): if module_path.startswith(SALT_BASE_PATH): return 'int' return 'ext' def _inject_into_mod(mod, name, value, force_lock=False): ''' Inject a variable into a module. This is used to inject "globals" like ``__salt__``, ``__pillar``, or ``grains``. Instead of injecting the value directly, a ``ThreadLocalProxy`` is created. If such a proxy is already present under the specified name, it is updated with the new value. This update only affects the current thread, so that the same name can refer to different values depending on the thread of execution. This is important for data that is not truly global. For example, pillar data might be dynamically overriden through function parameters and thus the actual values available in pillar might depend on the thread that is calling a module. mod: module object into which the value is going to be injected. name: name of the variable that is injected into the module. value: value that is injected into the variable. The value is not injected directly, but instead set as the new reference of the proxy that has been created for the variable. force_lock: whether the lock should be acquired before checking whether a proxy object for the specified name has already been injected into the module. If ``False`` (the default), this function checks for the module's variable without acquiring the lock and only acquires the lock if a new proxy has to be created and injected. ''' old_value = getattr(mod, name, None) # We use a double-checked locking scheme in order to avoid taking the lock # when a proxy object has already been injected. # In most programming languages, double-checked locking is considered # unsafe when used without explicit memory barriers because one might read # an uninitialized value. In CPython it is safe due to the global # interpreter lock (GIL). In Python implementations that do not have the # GIL, it could be unsafe, but at least Jython also guarantees that (for # Python objects) memory is not corrupted when writing and reading without # explicit synchronization # (http://www.jython.org/jythonbook/en/1.0/Concurrency.html). # Please note that in order to make this code safe in a runtime environment # that does not make this guarantees, it is not sufficient. The # ThreadLocalProxy must also be created with fallback_to_shared set to # False or a lock must be added to the ThreadLocalProxy. if force_lock: with _inject_into_mod.lock: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: setattr(mod, name, ThreadLocalProxy(value, True)) else: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: _inject_into_mod(mod, name, value, True) # Lock used when injecting globals. This is needed to avoid a race condition # when two threads try to load the same module concurrently. This must be # outside the loader because there might be more than one loader for the same # namespace. _inject_into_mod.lock = threading.RLock() # TODO: move somewhere else? class FilterDictWrapper(MutableMapping): ''' Create a dict which wraps another dict with a specific key suffix on get This is to replace "filter_load" ''' def __init__(self, d, suffix): self._dict = d self.suffix = suffix def __setitem__(self, key, val): self._dict[key] = val def __delitem__(self, key): del self._dict[key] def __getitem__(self, key): return self._dict[key + self.suffix] def __len__(self): return len(self._dict) def __iter__(self): for key in self._dict: if key.endswith(self.suffix): yield key.replace(self.suffix, '') class LazyLoader(salt.utils.lazy.LazyDict): ''' A pseduo-dictionary which has a set of keys which are the name of the module and function, delimited by a dot. When the value of the key is accessed, the function is then loaded from disk and into memory. .. note:: Iterating over keys will cause all modules to be loaded. :param list module_dirs: A list of directories on disk to search for modules :param dict opts: The salt options dictionary. :param str tag: The tag for the type of module to load :param func mod_type_check: A function which can be used to verify files :param dict pack: A dictionary of function to be packed into modules as they are loaded :param list whitelist: A list of modules to whitelist :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules. :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality. If not true, the module will not load. :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values are function references themselves which are loaded on-demand. # TODO: - move modules_max_memory into here - singletons (per tag) ''' mod_dict_class = salt.utils.odict.OrderedDict def __init__(self, module_dirs, opts=None, tag='module', loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, proxy=None, virtual_funcs=None, ): # pylint: disable=W0231 ''' In pack, if any of the values are None they will be replaced with an empty context-specific dict ''' self.inject_globals = {} self.pack = {} if pack is None else pack if opts is None: opts = {} threadsafety = not opts.get('multiprocessing') self.context_dict = salt.utils.context.ContextDict(threadsafe=threadsafety) self.opts = self.__prep_mod_opts(opts) self.module_dirs = module_dirs self.tag = tag self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME self.mod_type_check = mod_type_check or _mod_type if '__context__' not in self.pack: self.pack['__context__'] = None for k, v in six.iteritems(self.pack): if v is None: # if the value of a pack is None, lets make an empty dict value = self.context_dict.get(k, {}) if isinstance(value, ThreadLocalProxy): value = ThreadLocalProxy.unproxy(value) self.context_dict[k] = value self.pack[k] = salt.utils.context.NamespacedDictWrapper(self.context_dict, k) self.whitelist = whitelist self.virtual_enable = virtual_enable self.initial_load = True # names of modules that we don't have (errors, __virtual__, etc.) self.missing_modules = {} # mapping of name -> error self.loaded_modules = {} # mapping of module_name -> dict_of_functions self.loaded_files = set() # TODO: just remove them from file_mapping? self.static_modules = static_modules if static_modules else [] if virtual_funcs is None: virtual_funcs = [] self.virtual_funcs = virtual_funcs self.disabled = set( self.opts.get( 'disable_{0}{1}'.format( self.tag, '' if self.tag[-1] == 's' else 's' ), [] ) ) # A map of suffix to description for imp self.suffix_map = {} # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [''] for (suffix, mode, kind) in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) self._lock = threading.RLock() self._refresh_file_mapping() super(LazyLoader, self).__init__() # late init the lazy loader # create all of the import namespaces _generate_module('{0}.int'.format(self.loaded_base_name)) _generate_module('{0}.int.{1}'.format(self.loaded_base_name, tag)) _generate_module('{0}.ext'.format(self.loaded_base_name)) _generate_module('{0}.ext.{1}'.format(self.loaded_base_name, tag)) def __getitem__(self, item): ''' Override the __getitem__ in order to decorate the returned function if we need to last-minute inject globals ''' func = super(LazyLoader, self).__getitem__(item) if self.inject_globals: return global_injector_decorator(self.inject_globals)(func) else: return func def __getattr__(self, mod_name): ''' Allow for "direct" attribute access-- this allows jinja templates to access things like `salt.test.ping()` ''' if mod_name in ('__getstate__', '__setstate__'): return object.__getattribute__(self, mod_name) # if we have an attribute named that, lets return it. try: return object.__getattr__(self, mod_name) # pylint: disable=no-member except AttributeError: pass # otherwise we assume its jinja template access if mod_name not in self.loaded_modules and not self.loaded: for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and mod_name in self.loaded_modules: break if mod_name in self.loaded_modules: return self.loaded_modules[mod_name] else: raise AttributeError(mod_name) def missing_fun_string(self, function_name): ''' Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ''' mod_name = function_name.split('.')[0] if mod_name in self.loaded_modules: return '\'{0}\' is not available.'.format(function_name) else: try: reason = self.missing_modules[mod_name] except KeyError: return '\'{0}\' is not available.'.format(function_name) else: if reason is not None: return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason) else: return '\'{0}\' __virtual__ returned False'.format(mod_name) def _refresh_file_mapping(self): ''' refresh the mapping of the FS on disk ''' # map of suffix to description for imp if self.opts.get('cython_enable', True) is True: try: global pyximport pyximport = __import__('pyximport') # pylint: disable=import-error pyximport.install() # add to suffix_map so file_mapping will pick it up self.suffix_map['.pyx'] = tuple() except ImportError: log.info('Cython is enabled in the options but not present ' 'in the system path. Skipping Cython modules.') # Allow for zipimport of modules if self.opts.get('enable_zip_modules', True) is True: self.suffix_map['.zip'] = tuple() # allow for module dirs if USE_IMPORTLIB: self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY) else: self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY) # create mapping of filename (without suffix) to (path, suffix) # The files are added in order of priority, so order *must* be retained. self.file_mapping = salt.utils.odict.OrderedDict() opt_match = [] def _replace_pre_ext(obj): ''' Hack so we can get the optimization level that we replaced (if any) out of the re.sub call below. We use a list here because it is a persistent data structure that we will be able to access after re.sub is called. ''' opt_match.append(obj) return '' for mod_dir in self.module_dirs: try: # Make sure we have a sorted listdir in order to have # expectable override results files = sorted( x for x in os.listdir(mod_dir) if x != '__pycache__' ) except OSError: continue # Next mod_dir if six.PY3: try: pycache_files = [ os.path.join('__pycache__', x) for x in sorted(os.listdir(os.path.join(mod_dir, '__pycache__'))) ] except OSError: pass else: files.extend(pycache_files) for filename in files: try: dirname, basename = os.path.split(filename) if basename.startswith('_'): # skip private modules # log messages omitted for obviousness continue # Next filename f_noext, ext = os.path.splitext(basename) if six.PY3: f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext) try: opt_level = int( opt_match.pop().group(1).rsplit('-', 1)[-1] ) except (AttributeError, IndexError, ValueError): # No regex match or no optimization level matched opt_level = 0 try: opt_index = self.opts['optimization_order'].index(opt_level) except KeyError: log.trace( 'Disallowed optimization level %d for module ' 'name \'%s\', skipping. Add %d to the ' '\'optimization_order\' config option if you ' 'do not want to ignore this optimization ' 'level.', opt_level, f_noext, opt_level ) continue else: # Optimization level not reflected in filename on PY2 opt_index = 0 # make sure it is a suffix we support if ext not in self.suffix_map: continue # Next filename if f_noext in self.disabled: log.trace( 'Skipping %s, it is disabled by configuration', filename ) continue # Next filename fpath = os.path.join(mod_dir, filename) # if its a directory, lets allow us to load that if ext == '': # is there something __init__? subfiles = os.listdir(fpath) for suffix in self.suffix_order: if '' == suffix: continue # Next suffix (__init__ must have a suffix) init_file = '__init__{0}'.format(suffix) if init_file in subfiles: break else: continue # Next filename try: curr_ext = self.file_mapping[f_noext][1] curr_opt_index = self.file_mapping[f_noext][2] except KeyError: pass else: if '' in (curr_ext, ext) and curr_ext != ext: log.error( 'Module/package collision: \'%s\' and \'%s\'', fpath, self.file_mapping[f_noext][0] ) if six.PY3 and ext == '.pyc' and curr_ext == '.pyc': # Check the optimization level if opt_index >= curr_opt_index: # Module name match, but a higher-priority # optimization level was already matched, skipping. continue elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext): # Match found but a higher-priorty match already # exists, so skip this. continue if six.PY3 and not dirname and ext == '.pyc': # On Python 3, we should only load .pyc files from the # __pycache__ subdirectory (i.e. when dirname is not an # empty string). continue # Made it this far - add it self.file_mapping[f_noext] = (fpath, ext, opt_index) except OSError: continue for smod in self.static_modules: f_noext = smod.split('.')[-1] self.file_mapping[f_noext] = (smod, '.o', 0) def clear(self): ''' Clear the dict ''' with self._lock: super(LazyLoader, self).clear() # clear the lazy loader self.loaded_files = set() self.missing_modules = {} self.loaded_modules = {} # if we have been loaded before, lets clear the file mapping since # we obviously want a re-do if hasattr(self, 'opts'): self._refresh_file_mapping() self.initial_load = False def __prep_mod_opts(self, opts): ''' Strip out of the opts any logger instance ''' if '__grains__' not in self.pack: grains = opts.get('grains', {}) if isinstance(grains, ThreadLocalProxy): grains = ThreadLocalProxy.unproxy(grains) self.context_dict['grains'] = grains self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains') if '__pillar__' not in self.pack: pillar = opts.get('pillar', {}) if isinstance(pillar, ThreadLocalProxy): pillar = ThreadLocalProxy.unproxy(pillar) self.context_dict['pillar'] = pillar self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar') mod_opts = {} for key, val in list(opts.items()): if key == 'logger': continue mod_opts[key] = val return mod_opts def _iter_files(self, mod_name): ''' Iterate over all file_mapping files in order of closeness to mod_name ''' # do we have an exact match? if mod_name in self.file_mapping: yield mod_name # do we have a partial match? for k in self.file_mapping: if mod_name in k: yield k # anyone else? Bueller? for k in self.file_mapping: if mod_name not in k: yield k def _reload_submodules(self, mod): submodules = ( getattr(mod, sname) for sname in dir(mod) if isinstance(getattr(mod, sname), mod.__class__) ) # reload only custom "sub"modules for submodule in submodules: # it is a submodule if the name is in a namespace under mod if submodule.__name__.startswith(mod.__name__ + '.'): reload_module(submodule) self._reload_submodules(submodule) def _load_module(self, name): mod = None fpath, suffix = self.file_mapping[name][:2] self.loaded_files.add(name) fpath_dirname = os.path.dirname(fpath) try: sys.path.append(fpath_dirname) if suffix == '.pyx': mod = pyximport.load_module(name, fpath, tempfile.gettempdir()) elif suffix == '.o': top_mod = __import__(fpath, globals(), locals(), []) comps = fpath.split('.') if len(comps) < 2: mod = top_mod else: mod = top_mod for subname in comps[1:]: mod = getattr(mod, subname) elif suffix == '.zip': mod = zipimporter(fpath).load_module(name) else: desc = self.suffix_map[suffix] # if it is a directory, we don't open a file try: mod_namespace = '.'.join(( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name)) except TypeError: mod_namespace = '{0}.{1}.{2}.{3}'.format( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name) if suffix == '': if USE_IMPORTLIB: # pylint: disable=no-member # Package directory, look for __init__ loader_details = [ (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES), (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES), (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), ] file_finder = importlib.machinery.FileFinder( fpath_dirname, *loader_details ) spec = file_finder.find_spec(mod_namespace) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: mod = imp.load_module(mod_namespace, None, fpath, desc) # reload all submodules if necessary if not self.initial_load: self._reload_submodules(mod) else: if USE_IMPORTLIB: # pylint: disable=no-member loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath) spec = importlib.util.spec_from_file_location( mod_namespace, fpath, loader=loader ) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() #mod = importlib.util.module_from_spec(spec) #spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: with salt.utils.files.fopen(fpath, desc[1]) as fn_: mod = imp.load_module(mod_namespace, fn_, fpath, desc) except IOError: raise except ImportError as exc: if 'magic number' in six.text_type(exc): error_msg = 'Failed to import {0} {1}. Bad magic number. If migrating from Python2 to Python3, remove all .pyc files and try again.'.format(self.tag, name) log.warning(error_msg) self.missing_modules[name] = error_msg log.debug( 'Failed to import %s %s:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = exc return False except Exception as error: log.error( 'Failed to import %s %s, this is due most likely to a ' 'syntax error:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False except SystemExit as error: try: fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1] except Exception: pass else: tgt_fn = os.path.join('salt', 'utils', 'process.py') if fn_.endswith(tgt_fn) and '_handle_signals' in caller: # Race conditon, SIGTERM or SIGINT received while loader # was in process of loading a module. Call sys.exit to # ensure that the process is killed. sys.exit(salt.defaults.exitcodes.EX_OK) log.error( 'Failed to import %s %s as the module called exit()\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False finally: sys.path.remove(fpath_dirname) if hasattr(mod, '__opts__'): mod.__opts__.update(self.opts) else: mod.__opts__ = self.opts # pack whatever other globals we were asked to for p_name, p_value in six.iteritems(self.pack): _inject_into_mod(mod, p_name, p_value) module_name = mod.__name__.rsplit('.', 1)[-1] # Call a module's initialization method if it exists module_init = getattr(mod, '__init__', None) if inspect.isfunction(module_init): try: module_init(self.opts) except TypeError as e: log.error(e) except Exception: err_string = '__init__ failed' log.debug( 'Error loading %s.%s: %s', self.tag, module_name, err_string, exc_info=True ) self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False # if virtual modules are enabled, we need to look for the # __virtual__() function inside that module and run it. if self.virtual_enable: virtual_funcs_to_process = ['__virtual__'] + self.virtual_funcs for virtual_func in virtual_funcs_to_process: virtual_ret, module_name, virtual_err, virtual_aliases = \ self._process_virtual(mod, module_name, virtual_func) if virtual_err is not None: log.trace( 'Error loading %s.%s: %s', self.tag, module_name, virtual_err ) # if _process_virtual returned a non-True value then we are # supposed to not process this module if virtual_ret is not True and module_name not in self.missing_modules: # If a module has information about why it could not be loaded, record it self.missing_modules[module_name] = virtual_err self.missing_modules[name] = virtual_err return False else: virtual_aliases = () # If this is a proxy minion then MOST modules cannot work. Therefore, require that # any module that does work with salt-proxy-minion define __proxyenabled__ as a list # containing the names of the proxy types that the module supports. # # Render modules and state modules are OK though if 'proxy' in self.opts: if self.tag in ['grains', 'proxy']: if not hasattr(mod, '__proxyenabled__') or \ (self.opts['proxy']['proxytype'] not in mod.__proxyenabled__ and '*' not in mod.__proxyenabled__): err_string = 'not a proxy_minion enabled module' self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False if getattr(mod, '__load__', False) is not False: log.info( 'The functions from module \'%s\' are being loaded from the ' 'provided __load__ attribute', module_name ) # If we had another module by the same virtual name, we should put any # new functions under the existing dictionary. mod_names = [module_name] + list(virtual_aliases) mod_dict = dict(( (x, self.loaded_modules.get(x, self.mod_dict_class())) for x in mod_names )) for attr in getattr(mod, '__load__', dir(mod)): if attr.startswith('_') and attr != '__call__': # private functions are skipped, # except __call__ which is default entrance # for multi-function batch-like state syntax continue func = getattr(mod, attr) if not inspect.isfunction(func) and not isinstance(func, functools.partial): # Not a function!? Skip it!!! continue # Let's get the function name. # If the module has the __func_alias__ attribute, it must be a # dictionary mapping in the form of(key -> value): # <real-func-name> -> <desired-func-name> # # It default's of course to the found callable attribute name # if no alias is defined. funcname = getattr(mod, '__func_alias__', {}).get(attr, attr) for tgt_mod in mod_names: try: full_funcname = '.'.join((tgt_mod, funcname)) except TypeError: full_funcname = '{0}.{1}'.format(tgt_mod, funcname) # Save many references for lookups # Careful not to overwrite existing (higher priority) functions if full_funcname not in self._dict: self._dict[full_funcname] = func if funcname not in mod_dict[tgt_mod]: setattr(mod_dict[tgt_mod], funcname, func) mod_dict[tgt_mod][funcname] = func self._apply_outputter(func, mod) # enforce depends try: Depends.enforce_dependencies(self._dict, self.tag) except RuntimeError as exc: log.info( 'Depends.enforce_dependencies() failed for the following ' 'reason: %s', exc ) for tgt_mod in mod_names: self.loaded_modules[tgt_mod] = mod_dict[tgt_mod] return True def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise KeyError('The key \'{0}\' should contain a \'.\''.format(key)) mod_name, _ = key.split('.', 1) with self._lock: # It is possible that the key is in the dictionary after # acquiring the lock due to another thread loading it. if mod_name in self.missing_modules or key in self._dict: return True # if the modulename isn't in the whitelist, don't bother if self.whitelist and mod_name not in self.whitelist: log.error( 'Failed to load function %s because its module (%s) is ' 'not in the whitelist: %s', key, mod_name, self.whitelist ) raise KeyError(key) def _inner_load(mod_name): for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and key in self._dict: return True return False # try to load the module ret = None reloaded = False # re-scan up to once, IOErrors or a failed load cause re-scans of the # filesystem while True: try: ret = _inner_load(mod_name) if not reloaded and ret is not True: self._refresh_file_mapping() reloaded = True continue break except IOError: if not reloaded: self._refresh_file_mapping() reloaded = True continue return ret def _load_all(self): ''' Load all of them ''' with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True def reload_modules(self): with self._lock: self.loaded_files = set() self._load_all() def _apply_outputter(self, func, mod): ''' Apply the __outputter__ variable to the functions ''' if hasattr(mod, '__outputter__'): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__] def _process_virtual(self, mod, module_name, virtual_func='__virtual__'): ''' Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1] ''' # The __virtual__ function will return either a True or False value. # If it returns a True value it can also set a module level attribute # named __virtualname__ with the name that the module should be # referred to as. # # This allows us to have things like the pkg module working on all # platforms under the name 'pkg'. It also allows for modules like # augeas_cfg to be referred to as 'augeas', which would otherwise have # namespace collisions. And finally it allows modules to return False # if they are not intended to run on the given platform or are missing # dependencies. virtual_aliases = getattr(mod, '__virtual_aliases__', tuple()) try: error_reason = None if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__): try: start = time.time() virtual = getattr(mod, virtual_func)() if isinstance(virtual, tuple): error_reason = virtual[1] virtual = virtual[0] if self.opts.get('virtual_timer', False): end = time.time() - start msg = 'Virtual function took {0} seconds for {1}'.format( end, module_name) log.warning(msg) except Exception as exc: error_reason = ( 'Exception raised when processing __virtual__ function' ' for {0}. Module will not be loaded: {1}'.format( mod.__name__, exc)) log.error(error_reason, exc_info_on_loglevel=logging.DEBUG) virtual = None # Get the module's virtual name virtualname = getattr(mod, '__virtualname__', virtual) if not virtual: # if __virtual__() evaluates to False then the module # wasn't meant for this platform or it's not supposed to # load for some other reason. # Some modules might accidentally return None and are # improperly loaded if virtual is None: log.warning( '%s.__virtual__() is wrongly returning `None`. ' 'It should either return `True`, `False` or a new ' 'name. If you\'re the developer of the module ' '\'%s\', please fix this.', mod.__name__, module_name ) return (False, module_name, error_reason, virtual_aliases) # At this point, __virtual__ did not return a # boolean value, let's check for deprecated usage # or module renames if virtual is not True and module_name != virtual: # The module is renaming itself. Updating the module name # with the new name log.trace('Loaded %s as virtual %s', module_name, virtual) if virtualname != virtual: # The __virtualname__ attribute does not match what's # being returned by the __virtual__() function. This # should be considered an error. log.error( 'The module \'%s\' is showing some bad usage. Its ' '__virtualname__ attribute is set to \'%s\' yet the ' '__virtual__() function is returning \'%s\'. These ' 'values should match!', mod.__name__, virtualname, virtual ) module_name = virtualname # If the __virtual__ function returns True and __virtualname__ # is set then use it elif virtual is True and virtualname != module_name: if virtualname is not True: module_name = virtualname except KeyError: # Key errors come out of the virtual function when passing # in incomplete grains sets, these can be safely ignored # and logged to debug, still, it includes the traceback to # help debugging. log.debug('KeyError when loading %s', module_name, exc_info=True) except Exception: # If the module throws an exception during __virtual__() # then log the information and continue to the next. log.error( 'Failed to read the virtual function for %s: %s', self.tag, module_name, exc_info=True ) return (False, module_name, error_reason, virtual_aliases) return (True, module_name, None, virtual_aliases) def global_injector_decorator(inject_globals): ''' Decorator used by the LazyLoader to inject globals into a function at execute time. globals Dictionary with global variables to inject ''' def inner_decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): with salt.utils.context.func_globals_inject(f, **inject_globals): return f(*args, **kwargs) return wrapper return inner_decorator
saltstack/salt
salt/loader.py
log_handlers
python
def log_handlers(opts): ''' Returns the custom logging handler modules :param dict opts: The Salt options dictionary ''' ret = LazyLoader( _module_dirs( opts, 'log_handlers', int_type='handlers', base_path=os.path.join(SALT_BASE_PATH, 'log'), ), opts, tag='log_handlers', ) return FilterDictWrapper(ret, '.setup_handlers')
Returns the custom logging handler modules :param dict opts: The Salt options dictionary
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L594-L610
null
# -*- coding: utf-8 -*- ''' The Salt loader is the core to Salt's plugin system, the loader scans directories for python loadable code and organizes the code into the plugin interfaces used by Salt. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import sys import time import logging import inspect import tempfile import threading import functools import threading import traceback import types from zipimport import zipimporter # Import salt libs import salt.config import salt.defaults.events import salt.defaults.exitcodes import salt.syspaths import salt.utils.args import salt.utils.context import salt.utils.data import salt.utils.dictupdate import salt.utils.event import salt.utils.files import salt.utils.lazy import salt.utils.odict import salt.utils.platform import salt.utils.versions import salt.utils.stringutils from salt.exceptions import LoaderError from salt.template import check_render_pipe_str from salt.utils.decorators import Depends from salt.utils.thread_local_proxy import ThreadLocalProxy # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import reload_module if sys.version_info[:2] >= (3, 5): import importlib.machinery # pylint: disable=no-name-in-module,import-error import importlib.util # pylint: disable=no-name-in-module,import-error USE_IMPORTLIB = True else: import imp USE_IMPORTLIB = False try: from collections.abc import MutableMapping except ImportError: from collections import MutableMapping try: import pkg_resources HAS_PKG_RESOURCES = True except ImportError: HAS_PKG_RESOURCES = False log = logging.getLogger(__name__) SALT_BASE_PATH = os.path.abspath(salt.syspaths.INSTALL_DIR) LOADED_BASE_NAME = 'salt.loaded' if USE_IMPORTLIB: # pylint: disable=no-member MODULE_KIND_SOURCE = 1 MODULE_KIND_COMPILED = 2 MODULE_KIND_EXTENSION = 3 MODULE_KIND_PKG_DIRECTORY = 5 SUFFIXES = [] for suffix in importlib.machinery.EXTENSION_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_EXTENSION)) for suffix in importlib.machinery.SOURCE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_SOURCE)) for suffix in importlib.machinery.BYTECODE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_COMPILED)) MODULE_KIND_MAP = { MODULE_KIND_SOURCE: importlib.machinery.SourceFileLoader, MODULE_KIND_COMPILED: importlib.machinery.SourcelessFileLoader, MODULE_KIND_EXTENSION: importlib.machinery.ExtensionFileLoader } # pylint: enable=no-member else: SUFFIXES = imp.get_suffixes() PY3_PRE_EXT = \ re.compile(r'\.cpython-{0}{1}(\.opt-[1-9])?'.format(*sys.version_info[:2])) # Because on the cloud drivers we do `from salt.cloud.libcloudfuncs import *` # which simplifies code readability, it adds some unsupported functions into # the driver's module scope. # We list un-supported functions here. These will be removed from the loaded. # TODO: remove the need for this cross-module code. Maybe use NotImplemented LIBCLOUD_FUNCS_NOT_SUPPORTED = ( 'parallels.avail_sizes', 'parallels.avail_locations', 'proxmox.avail_sizes', ) # Will be set to pyximport module at runtime if cython is enabled in config. pyximport = None def static_loader( opts, ext_type, tag, pack=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, filter_name=None, ): funcs = LazyLoader( _module_dirs( opts, ext_type, tag, int_type, ext_dirs, ext_type_dirs, base_path, ), opts, tag=tag, pack=pack, ) ret = {} funcs._load_all() if filter_name: funcs = FilterDictWrapper(funcs, filter_name) for key in funcs: ret[key] = funcs[key] return ret def _format_entrypoint_target(ep): ''' Makes a string describing the target of an EntryPoint object. Base strongly on EntryPoint.__str__(). ''' s = ep.module_name if ep.attrs: s += ':' + '.'.join(ep.attrs) return s def _module_dirs( opts, ext_type, tag=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, ): if tag is None: tag = ext_type sys_types = os.path.join(base_path or SALT_BASE_PATH, int_type or ext_type) ext_types = os.path.join(opts['extension_modules'], ext_type) ext_type_types = [] if ext_dirs: if ext_type_dirs is None: ext_type_dirs = '{0}_dirs'.format(tag) if ext_type_dirs in opts: ext_type_types.extend(opts[ext_type_dirs]) if HAS_PKG_RESOURCES and ext_type_dirs: for entry_point in pkg_resources.iter_entry_points('salt.loader', ext_type_dirs): try: loaded_entry_point = entry_point.load() for path in loaded_entry_point(): ext_type_types.append(path) except Exception as exc: log.error("Error getting module directories from %s: %s", _format_entrypoint_target(entry_point), exc) log.debug("Full backtrace for module directories error", exc_info=True) cli_module_dirs = [] # The dirs can be any module dir, or a in-tree _{ext_type} dir for _dir in opts.get('module_dirs', []): # Prepend to the list to match cli argument ordering maybe_dir = os.path.join(_dir, ext_type) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) continue maybe_dir = os.path.join(_dir, '_{0}'.format(ext_type)) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) return cli_module_dirs + ext_type_types + [ext_types, sys_types] def minion_mods( opts, context=None, utils=None, whitelist=None, initial_load=False, loaded_base_name=None, notify=False, static_modules=None, proxy=None): ''' Load execution modules Returns a dictionary of execution modules appropriate for the current system by evaluating the __virtual__() function in each module. :param dict opts: The Salt options dictionary :param dict context: A Salt context that should be made present inside generated modules in __context__ :param dict utils: Utility functions which should be made available to Salt modules in __utils__. See `utils_dirs` in salt.config for additional information about configuration. :param list whitelist: A list of modules which should be whitelisted. :param bool initial_load: Deprecated flag! Unused. :param str loaded_base_name: A string marker for the loaded base name. :param bool notify: Flag indicating that an event should be fired upon completion of module loading. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) __opts__['grains'] = __grains__ __utils__ = salt.loader.utils(__opts__) __salt__ = salt.loader.minion_mods(__opts__, utils=__utils__) __salt__['test.ping']() ''' # TODO Publish documentation for module whitelisting if not whitelist: whitelist = opts.get('whitelist_modules', None) ret = LazyLoader( _module_dirs(opts, 'modules', 'module'), opts, tag='module', pack={'__context__': context, '__utils__': utils, '__proxy__': proxy}, whitelist=whitelist, loaded_base_name=loaded_base_name, static_modules=static_modules, ) ret.pack['__salt__'] = ret # Load any provider overrides from the configuration file providers option # Note: Providers can be pkg, service, user or group - not to be confused # with cloud providers. providers = opts.get('providers', False) if providers and isinstance(providers, dict): for mod in providers: # sometimes providers opts is not to diverge modules but # for other configuration try: funcs = raw_mod(opts, providers[mod], ret) except TypeError: break else: if funcs: for func in funcs: f_key = '{0}{1}'.format(mod, func[func.rindex('.'):]) ret[f_key] = funcs[func] if notify: evt = salt.utils.event.get_event('minion', opts=opts, listen=False) evt.fire_event({'complete': True}, tag=salt.defaults.events.MINION_MOD_COMPLETE) return ret def raw_mod(opts, name, functions, mod='modules'): ''' Returns a single module loaded raw and bypassing the __virtual__ function .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') testmod = salt.loader.raw_mod(__opts__, 'test', None) testmod['test.ping']() ''' loader = LazyLoader( _module_dirs(opts, mod, 'module'), opts, tag='rawmodule', virtual_enable=False, pack={'__salt__': functions}, ) # if we don't have the module, return an empty dict if name not in loader.file_mapping: return {} loader._load_module(name) # load a single module (the one passed in) return dict(loader._dict) # return a copy of *just* the funcs for `name` def metaproxy(opts): ''' Return functions used in the meta proxy ''' return LazyLoader( _module_dirs(opts, 'metaproxy'), opts, tag='metaproxy' ) def matchers(opts): ''' Return the matcher services plugins ''' return LazyLoader( _module_dirs(opts, 'matchers'), opts, tag='matchers' ) def engines(opts, functions, runners, utils, proxy=None): ''' Return the master services plugins ''' pack = {'__salt__': functions, '__runners__': runners, '__proxy__': proxy, '__utils__': utils} return LazyLoader( _module_dirs(opts, 'engines'), opts, tag='engines', pack=pack, ) def proxy(opts, functions=None, returners=None, whitelist=None, utils=None): ''' Returns the proxy module for this salt-proxy-minion ''' ret = LazyLoader( _module_dirs(opts, 'proxy'), opts, tag='proxy', pack={'__salt__': functions, '__ret__': returners, '__utils__': utils}, ) ret.pack['__proxy__'] = ret return ret def returners(opts, functions, whitelist=None, context=None, proxy=None): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'returners', 'returner'), opts, tag='returner', whitelist=whitelist, pack={'__salt__': functions, '__context__': context, '__proxy__': proxy or {}}, ) def utils(opts, whitelist=None, context=None, proxy=proxy): ''' Returns the utility modules ''' return LazyLoader( _module_dirs(opts, 'utils', ext_type_dirs='utils_dirs'), opts, tag='utils', whitelist=whitelist, pack={'__context__': context, '__proxy__': proxy or {}}, ) def pillars(opts, functions, context=None): ''' Returns the pillars modules ''' ret = LazyLoader(_module_dirs(opts, 'pillar'), opts, tag='pillar', pack={'__salt__': functions, '__context__': context, '__utils__': utils(opts)}) ret.pack['__ext_pillar__'] = ret return FilterDictWrapper(ret, '.ext_pillar') def tops(opts): ''' Returns the tops modules ''' if 'master_tops' not in opts: return {} whitelist = list(opts['master_tops'].keys()) ret = LazyLoader( _module_dirs(opts, 'tops', 'top'), opts, tag='top', whitelist=whitelist, ) return FilterDictWrapper(ret, '.top') def wheels(opts, whitelist=None, context=None): ''' Returns the wheels modules ''' if context is None: context = {} return LazyLoader( _module_dirs(opts, 'wheel'), opts, tag='wheel', whitelist=whitelist, pack={'__context__': context}, ) def outputters(opts): ''' Returns the outputters modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only outputters present in the keyspace ''' ret = LazyLoader( _module_dirs(opts, 'output', ext_type_dirs='outputter_dirs'), opts, tag='output', ) wrapped_ret = FilterDictWrapper(ret, '.output') # TODO: this name seems terrible... __salt__ should always be execution mods ret.pack['__salt__'] = wrapped_ret return wrapped_ret def serializers(opts): ''' Returns the serializers modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only serializers present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'serializers'), opts, tag='serializers', ) def eauth_tokens(opts): ''' Returns the tokens modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only token backends present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'tokens'), opts, tag='tokens', ) def auth(opts, whitelist=None): ''' Returns the auth modules :param dict opts: The Salt options dictionary :returns: LazyLoader ''' return LazyLoader( _module_dirs(opts, 'auth'), opts, tag='auth', whitelist=whitelist, pack={'__salt__': minion_mods(opts)}, ) def fileserver(opts, backends): ''' Returns the file server modules ''' return LazyLoader(_module_dirs(opts, 'fileserver'), opts, tag='fileserver', whitelist=backends, pack={'__utils__': utils(opts)}) def roster(opts, runner=None, utils=None, whitelist=None): ''' Returns the roster modules ''' return LazyLoader( _module_dirs(opts, 'roster'), opts, tag='roster', whitelist=whitelist, pack={ '__runner__': runner, '__utils__': utils, }, ) def thorium(opts, functions, runners): ''' Load the thorium runtime modules ''' pack = {'__salt__': functions, '__runner__': runners, '__context__': {}} ret = LazyLoader(_module_dirs(opts, 'thorium'), opts, tag='thorium', pack=pack) ret.pack['__thorium__'] = ret return ret def states(opts, functions, utils, serializers, whitelist=None, proxy=None, context=None): ''' Returns the state modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') statemods = salt.loader.states(__opts__, None, None) ''' if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'states'), opts, tag='states', pack={'__salt__': functions, '__proxy__': proxy or {}}, whitelist=whitelist, ) ret.pack['__states__'] = ret ret.pack['__utils__'] = utils ret.pack['__serializers__'] = serializers ret.pack['__context__'] = context return ret def beacons(opts, functions, context=None, proxy=None): ''' Load the beacon modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. ''' return LazyLoader( _module_dirs(opts, 'beacons'), opts, tag='beacons', pack={'__context__': context, '__salt__': functions, '__proxy__': proxy or {}}, virtual_funcs=[], ) def ssh_wrapper(opts, functions=None, context=None): ''' Returns the custom logging handler modules ''' return LazyLoader( _module_dirs( opts, 'wrapper', base_path=os.path.join(SALT_BASE_PATH, os.path.join('client', 'ssh')), ), opts, tag='wrapper', pack={ '__salt__': functions, '__grains__': opts.get('grains', {}), '__pillar__': opts.get('pillar', {}), '__context__': context, }, ) def render(opts, functions, states=None, proxy=None, context=None): ''' Returns the render modules ''' if context is None: context = {} pack = {'__salt__': functions, '__grains__': opts.get('grains', {}), '__context__': context} if states: pack['__states__'] = states pack['__proxy__'] = proxy or {} ret = LazyLoader( _module_dirs( opts, 'renderers', 'render', ext_type_dirs='render_dirs', ), opts, tag='render', pack=pack, ) rend = FilterDictWrapper(ret, '.render') if not check_render_pipe_str(opts['renderer'], rend, opts['renderer_blacklist'], opts['renderer_whitelist']): err = ('The renderer {0} is unavailable, this error is often because ' 'the needed software is unavailable'.format(opts['renderer'])) log.critical(err) raise LoaderError(err) return rend def grain_funcs(opts, proxy=None): ''' Returns the grain functions .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') grainfuncs = salt.loader.grain_funcs(__opts__) ''' ret = LazyLoader( _module_dirs( opts, 'grains', 'grain', ext_type_dirs='grains_dirs', ), opts, tag='grains', ) ret.pack['__utils__'] = utils(opts, proxy=proxy) return ret def _load_cached_grains(opts, cfn): ''' Returns the grains cached in cfn, or None if the cache is too old or is corrupted. ''' if not os.path.isfile(cfn): log.debug('Grains cache file does not exist.') return None grains_cache_age = int(time.time() - os.path.getmtime(cfn)) if grains_cache_age > opts.get('grains_cache_expiration', 300): log.debug( 'Grains cache last modified %s seconds ago and cache ' 'expiration is set to %s. Grains cache expired. ' 'Refreshing.', grains_cache_age, opts.get('grains_cache_expiration', 300) ) return None if opts.get('refresh_grains_cache', False): log.debug('refresh_grains_cache requested, Refreshing.') return None log.debug('Retrieving grains from cache') try: serial = salt.payload.Serial(opts) with salt.utils.files.fopen(cfn, 'rb') as fp_: cached_grains = salt.utils.data.decode(serial.load(fp_), preserve_tuples=True) if not cached_grains: log.debug('Cached grains are empty, cache might be corrupted. Refreshing.') return None return cached_grains except (IOError, OSError): return None def grains(opts, force_refresh=False, proxy=None): ''' Return the functions for the dynamic grains and the values for the static grains. Since grains are computed early in the startup process, grains functions do not have __salt__ or __proxy__ available. At proxy-minion startup, this function is called with the proxymodule LazyLoader object so grains functions can communicate with their controlled device. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) print __grains__['id'] ''' # Need to re-import salt.config, somehow it got lost when a minion is starting import salt.config # if we have no grains, lets try loading from disk (TODO: move to decorator?) cfn = os.path.join( opts['cachedir'], 'grains.cache.p' ) if not force_refresh and opts.get('grains_cache', False): cached_grains = _load_cached_grains(opts, cfn) if cached_grains: return cached_grains else: log.debug('Grains refresh requested. Refreshing grains.') if opts.get('skip_grains', False): return {} grains_deep_merge = opts.get('grains_deep_merge', False) is True if 'conf_file' in opts: pre_opts = {} pre_opts.update(salt.config.load_config( opts['conf_file'], 'SALT_MINION_CONFIG', salt.config.DEFAULT_MINION_OPTS['conf_file'] )) default_include = pre_opts.get( 'default_include', opts['default_include'] ) include = pre_opts.get('include', []) pre_opts.update(salt.config.include_config( default_include, opts['conf_file'], verbose=False )) pre_opts.update(salt.config.include_config( include, opts['conf_file'], verbose=True )) if 'grains' in pre_opts: opts['grains'] = pre_opts['grains'] else: opts['grains'] = {} else: opts['grains'] = {} grains_data = {} blist = opts.get('grains_blacklist', []) funcs = grain_funcs(opts, proxy=proxy) if force_refresh: # if we refresh, lets reload grain modules funcs.clear() # Run core grains for key in funcs: if not key.startswith('core.'): continue log.trace('Loading %s grain', key) ret = funcs[key]() if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) # Run the rest of the grains for key in funcs: if key.startswith('core.') or key == '_errors': continue try: # Grains are loaded too early to take advantage of the injected # __proxy__ variable. Pass an instance of that LazyLoader # here instead to grains functions if the grains functions take # one parameter. Then the grains can have access to the # proxymodule for retrieving information from the connected # device. log.trace('Loading %s grain', key) parameters = salt.utils.args.get_function_argspec(funcs[key]).args kwargs = {} if 'proxy' in parameters: kwargs['proxy'] = proxy if 'grains' in parameters: kwargs['grains'] = grains_data ret = funcs[key](**kwargs) except Exception: if salt.utils.platform.is_proxy(): log.info('The following CRITICAL message may not be an error; the proxy may not be completely established yet.') log.critical( 'Failed to load grains defined in grain file %s in ' 'function %s, error:\n', key, funcs[key], exc_info=True ) continue if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) if opts.get('proxy_merge_grains_in_module', True) and proxy: try: proxytype = proxy.opts['proxy']['proxytype'] if proxytype + '.grains' in proxy: if proxytype + '.initialized' in proxy and proxy[proxytype + '.initialized'](): try: proxytype = proxy.opts['proxy']['proxytype'] ret = proxy[proxytype + '.grains']() if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) except Exception: log.critical('Failed to run proxy\'s grains function!', exc_info=True ) except KeyError: pass grains_data.update(opts['grains']) # Write cache if enabled if opts.get('grains_cache', False): with salt.utils.files.set_umask(0o077): try: if salt.utils.platform.is_windows(): # Late import import salt.modules.cmdmod # Make sure cache file isn't read-only salt.modules.cmdmod._run_quiet('attrib -R "{0}"'.format(cfn)) with salt.utils.files.fopen(cfn, 'w+b') as fp_: try: serial = salt.payload.Serial(opts) serial.dump(grains_data, fp_) except TypeError as e: log.error('Failed to serialize grains cache: %s', e) raise # re-throw for cleanup except Exception as e: log.error('Unable to write to grains cache file %s: %s', cfn, e) # Based on the original exception, the file may or may not have been # created. If it was, we will remove it now, as the exception means # the serialized data is not to be trusted, no matter what the # exception is. if os.path.isfile(cfn): os.unlink(cfn) if grains_deep_merge: salt.utils.dictupdate.update(grains_data, opts['grains']) else: grains_data.update(opts['grains']) return salt.utils.data.decode(grains_data, preserve_tuples=True) # TODO: get rid of? Does anyone use this? You should use raw() instead def call(fun, **kwargs): ''' Directly call a function inside a loader directory ''' args = kwargs.get('args', []) dirs = kwargs.get('dirs', []) funcs = LazyLoader( [os.path.join(SALT_BASE_PATH, 'modules')] + dirs, None, tag='modules', virtual_enable=False, ) return funcs[fun](*args) def runner(opts, utils=None, context=None, whitelist=None): ''' Directly call a function inside a loader directory ''' if utils is None: utils = {} if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'runners', 'runner', ext_type_dirs='runner_dirs'), opts, tag='runners', pack={'__utils__': utils, '__context__': context}, whitelist=whitelist, ) # TODO: change from __salt__ to something else, we overload __salt__ too much ret.pack['__salt__'] = ret return ret def queues(opts): ''' Directly call a function inside a loader directory ''' return LazyLoader( _module_dirs(opts, 'queues', 'queue', ext_type_dirs='queue_dirs'), opts, tag='queues', ) def sdb(opts, functions=None, whitelist=None, utils=None): ''' Make a very small database call ''' if utils is None: utils = {} return LazyLoader( _module_dirs(opts, 'sdb'), opts, tag='sdb', pack={ '__sdb__': functions, '__opts__': opts, '__utils__': utils, '__salt__': minion_mods(opts, utils), }, whitelist=whitelist, ) def pkgdb(opts): ''' Return modules for SPM's package database .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgdb', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgdb' ) def pkgfiles(opts): ''' Return modules for SPM's file handling .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgfiles', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgfiles' ) def clouds(opts): ''' Return the cloud functions ''' # Let's bring __active_provider_name__, defaulting to None, to all cloud # drivers. This will get temporarily updated/overridden with a context # manager when needed. functions = LazyLoader( _module_dirs(opts, 'clouds', 'cloud', base_path=os.path.join(SALT_BASE_PATH, 'cloud'), int_type='clouds'), opts, tag='clouds', pack={'__utils__': salt.loader.utils(opts), '__active_provider_name__': None}, ) for funcname in LIBCLOUD_FUNCS_NOT_SUPPORTED: log.trace( '\'%s\' has been marked as not supported. Removing from the ' 'list of supported cloud functions', funcname ) functions.pop(funcname, None) return functions def netapi(opts): ''' Return the network api functions ''' return LazyLoader( _module_dirs(opts, 'netapi'), opts, tag='netapi', ) def executors(opts, functions=None, context=None, proxy=None): ''' Returns the executor modules ''' executors = LazyLoader( _module_dirs(opts, 'executors', 'executor'), opts, tag='executor', pack={'__salt__': functions, '__context__': context or {}, '__proxy__': proxy or {}}, ) executors.pack['__executors__'] = executors return executors def cache(opts, serial): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'cache', 'cache'), opts, tag='cache', pack={'__opts__': opts, '__context__': {'serial': serial}}, ) def _generate_module(name): if name in sys.modules: return code = "'''Salt loaded {0} parent module'''".format(name.split('.')[-1]) # ModuleType can't accept a unicode type on PY2 module = types.ModuleType(str(name)) # future lint: disable=blacklisted-function exec(code, module.__dict__) sys.modules[name] = module def _mod_type(module_path): if module_path.startswith(SALT_BASE_PATH): return 'int' return 'ext' def _inject_into_mod(mod, name, value, force_lock=False): ''' Inject a variable into a module. This is used to inject "globals" like ``__salt__``, ``__pillar``, or ``grains``. Instead of injecting the value directly, a ``ThreadLocalProxy`` is created. If such a proxy is already present under the specified name, it is updated with the new value. This update only affects the current thread, so that the same name can refer to different values depending on the thread of execution. This is important for data that is not truly global. For example, pillar data might be dynamically overriden through function parameters and thus the actual values available in pillar might depend on the thread that is calling a module. mod: module object into which the value is going to be injected. name: name of the variable that is injected into the module. value: value that is injected into the variable. The value is not injected directly, but instead set as the new reference of the proxy that has been created for the variable. force_lock: whether the lock should be acquired before checking whether a proxy object for the specified name has already been injected into the module. If ``False`` (the default), this function checks for the module's variable without acquiring the lock and only acquires the lock if a new proxy has to be created and injected. ''' old_value = getattr(mod, name, None) # We use a double-checked locking scheme in order to avoid taking the lock # when a proxy object has already been injected. # In most programming languages, double-checked locking is considered # unsafe when used without explicit memory barriers because one might read # an uninitialized value. In CPython it is safe due to the global # interpreter lock (GIL). In Python implementations that do not have the # GIL, it could be unsafe, but at least Jython also guarantees that (for # Python objects) memory is not corrupted when writing and reading without # explicit synchronization # (http://www.jython.org/jythonbook/en/1.0/Concurrency.html). # Please note that in order to make this code safe in a runtime environment # that does not make this guarantees, it is not sufficient. The # ThreadLocalProxy must also be created with fallback_to_shared set to # False or a lock must be added to the ThreadLocalProxy. if force_lock: with _inject_into_mod.lock: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: setattr(mod, name, ThreadLocalProxy(value, True)) else: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: _inject_into_mod(mod, name, value, True) # Lock used when injecting globals. This is needed to avoid a race condition # when two threads try to load the same module concurrently. This must be # outside the loader because there might be more than one loader for the same # namespace. _inject_into_mod.lock = threading.RLock() # TODO: move somewhere else? class FilterDictWrapper(MutableMapping): ''' Create a dict which wraps another dict with a specific key suffix on get This is to replace "filter_load" ''' def __init__(self, d, suffix): self._dict = d self.suffix = suffix def __setitem__(self, key, val): self._dict[key] = val def __delitem__(self, key): del self._dict[key] def __getitem__(self, key): return self._dict[key + self.suffix] def __len__(self): return len(self._dict) def __iter__(self): for key in self._dict: if key.endswith(self.suffix): yield key.replace(self.suffix, '') class LazyLoader(salt.utils.lazy.LazyDict): ''' A pseduo-dictionary which has a set of keys which are the name of the module and function, delimited by a dot. When the value of the key is accessed, the function is then loaded from disk and into memory. .. note:: Iterating over keys will cause all modules to be loaded. :param list module_dirs: A list of directories on disk to search for modules :param dict opts: The salt options dictionary. :param str tag: The tag for the type of module to load :param func mod_type_check: A function which can be used to verify files :param dict pack: A dictionary of function to be packed into modules as they are loaded :param list whitelist: A list of modules to whitelist :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules. :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality. If not true, the module will not load. :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values are function references themselves which are loaded on-demand. # TODO: - move modules_max_memory into here - singletons (per tag) ''' mod_dict_class = salt.utils.odict.OrderedDict def __init__(self, module_dirs, opts=None, tag='module', loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, proxy=None, virtual_funcs=None, ): # pylint: disable=W0231 ''' In pack, if any of the values are None they will be replaced with an empty context-specific dict ''' self.inject_globals = {} self.pack = {} if pack is None else pack if opts is None: opts = {} threadsafety = not opts.get('multiprocessing') self.context_dict = salt.utils.context.ContextDict(threadsafe=threadsafety) self.opts = self.__prep_mod_opts(opts) self.module_dirs = module_dirs self.tag = tag self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME self.mod_type_check = mod_type_check or _mod_type if '__context__' not in self.pack: self.pack['__context__'] = None for k, v in six.iteritems(self.pack): if v is None: # if the value of a pack is None, lets make an empty dict value = self.context_dict.get(k, {}) if isinstance(value, ThreadLocalProxy): value = ThreadLocalProxy.unproxy(value) self.context_dict[k] = value self.pack[k] = salt.utils.context.NamespacedDictWrapper(self.context_dict, k) self.whitelist = whitelist self.virtual_enable = virtual_enable self.initial_load = True # names of modules that we don't have (errors, __virtual__, etc.) self.missing_modules = {} # mapping of name -> error self.loaded_modules = {} # mapping of module_name -> dict_of_functions self.loaded_files = set() # TODO: just remove them from file_mapping? self.static_modules = static_modules if static_modules else [] if virtual_funcs is None: virtual_funcs = [] self.virtual_funcs = virtual_funcs self.disabled = set( self.opts.get( 'disable_{0}{1}'.format( self.tag, '' if self.tag[-1] == 's' else 's' ), [] ) ) # A map of suffix to description for imp self.suffix_map = {} # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [''] for (suffix, mode, kind) in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) self._lock = threading.RLock() self._refresh_file_mapping() super(LazyLoader, self).__init__() # late init the lazy loader # create all of the import namespaces _generate_module('{0}.int'.format(self.loaded_base_name)) _generate_module('{0}.int.{1}'.format(self.loaded_base_name, tag)) _generate_module('{0}.ext'.format(self.loaded_base_name)) _generate_module('{0}.ext.{1}'.format(self.loaded_base_name, tag)) def __getitem__(self, item): ''' Override the __getitem__ in order to decorate the returned function if we need to last-minute inject globals ''' func = super(LazyLoader, self).__getitem__(item) if self.inject_globals: return global_injector_decorator(self.inject_globals)(func) else: return func def __getattr__(self, mod_name): ''' Allow for "direct" attribute access-- this allows jinja templates to access things like `salt.test.ping()` ''' if mod_name in ('__getstate__', '__setstate__'): return object.__getattribute__(self, mod_name) # if we have an attribute named that, lets return it. try: return object.__getattr__(self, mod_name) # pylint: disable=no-member except AttributeError: pass # otherwise we assume its jinja template access if mod_name not in self.loaded_modules and not self.loaded: for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and mod_name in self.loaded_modules: break if mod_name in self.loaded_modules: return self.loaded_modules[mod_name] else: raise AttributeError(mod_name) def missing_fun_string(self, function_name): ''' Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ''' mod_name = function_name.split('.')[0] if mod_name in self.loaded_modules: return '\'{0}\' is not available.'.format(function_name) else: try: reason = self.missing_modules[mod_name] except KeyError: return '\'{0}\' is not available.'.format(function_name) else: if reason is not None: return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason) else: return '\'{0}\' __virtual__ returned False'.format(mod_name) def _refresh_file_mapping(self): ''' refresh the mapping of the FS on disk ''' # map of suffix to description for imp if self.opts.get('cython_enable', True) is True: try: global pyximport pyximport = __import__('pyximport') # pylint: disable=import-error pyximport.install() # add to suffix_map so file_mapping will pick it up self.suffix_map['.pyx'] = tuple() except ImportError: log.info('Cython is enabled in the options but not present ' 'in the system path. Skipping Cython modules.') # Allow for zipimport of modules if self.opts.get('enable_zip_modules', True) is True: self.suffix_map['.zip'] = tuple() # allow for module dirs if USE_IMPORTLIB: self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY) else: self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY) # create mapping of filename (without suffix) to (path, suffix) # The files are added in order of priority, so order *must* be retained. self.file_mapping = salt.utils.odict.OrderedDict() opt_match = [] def _replace_pre_ext(obj): ''' Hack so we can get the optimization level that we replaced (if any) out of the re.sub call below. We use a list here because it is a persistent data structure that we will be able to access after re.sub is called. ''' opt_match.append(obj) return '' for mod_dir in self.module_dirs: try: # Make sure we have a sorted listdir in order to have # expectable override results files = sorted( x for x in os.listdir(mod_dir) if x != '__pycache__' ) except OSError: continue # Next mod_dir if six.PY3: try: pycache_files = [ os.path.join('__pycache__', x) for x in sorted(os.listdir(os.path.join(mod_dir, '__pycache__'))) ] except OSError: pass else: files.extend(pycache_files) for filename in files: try: dirname, basename = os.path.split(filename) if basename.startswith('_'): # skip private modules # log messages omitted for obviousness continue # Next filename f_noext, ext = os.path.splitext(basename) if six.PY3: f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext) try: opt_level = int( opt_match.pop().group(1).rsplit('-', 1)[-1] ) except (AttributeError, IndexError, ValueError): # No regex match or no optimization level matched opt_level = 0 try: opt_index = self.opts['optimization_order'].index(opt_level) except KeyError: log.trace( 'Disallowed optimization level %d for module ' 'name \'%s\', skipping. Add %d to the ' '\'optimization_order\' config option if you ' 'do not want to ignore this optimization ' 'level.', opt_level, f_noext, opt_level ) continue else: # Optimization level not reflected in filename on PY2 opt_index = 0 # make sure it is a suffix we support if ext not in self.suffix_map: continue # Next filename if f_noext in self.disabled: log.trace( 'Skipping %s, it is disabled by configuration', filename ) continue # Next filename fpath = os.path.join(mod_dir, filename) # if its a directory, lets allow us to load that if ext == '': # is there something __init__? subfiles = os.listdir(fpath) for suffix in self.suffix_order: if '' == suffix: continue # Next suffix (__init__ must have a suffix) init_file = '__init__{0}'.format(suffix) if init_file in subfiles: break else: continue # Next filename try: curr_ext = self.file_mapping[f_noext][1] curr_opt_index = self.file_mapping[f_noext][2] except KeyError: pass else: if '' in (curr_ext, ext) and curr_ext != ext: log.error( 'Module/package collision: \'%s\' and \'%s\'', fpath, self.file_mapping[f_noext][0] ) if six.PY3 and ext == '.pyc' and curr_ext == '.pyc': # Check the optimization level if opt_index >= curr_opt_index: # Module name match, but a higher-priority # optimization level was already matched, skipping. continue elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext): # Match found but a higher-priorty match already # exists, so skip this. continue if six.PY3 and not dirname and ext == '.pyc': # On Python 3, we should only load .pyc files from the # __pycache__ subdirectory (i.e. when dirname is not an # empty string). continue # Made it this far - add it self.file_mapping[f_noext] = (fpath, ext, opt_index) except OSError: continue for smod in self.static_modules: f_noext = smod.split('.')[-1] self.file_mapping[f_noext] = (smod, '.o', 0) def clear(self): ''' Clear the dict ''' with self._lock: super(LazyLoader, self).clear() # clear the lazy loader self.loaded_files = set() self.missing_modules = {} self.loaded_modules = {} # if we have been loaded before, lets clear the file mapping since # we obviously want a re-do if hasattr(self, 'opts'): self._refresh_file_mapping() self.initial_load = False def __prep_mod_opts(self, opts): ''' Strip out of the opts any logger instance ''' if '__grains__' not in self.pack: grains = opts.get('grains', {}) if isinstance(grains, ThreadLocalProxy): grains = ThreadLocalProxy.unproxy(grains) self.context_dict['grains'] = grains self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains') if '__pillar__' not in self.pack: pillar = opts.get('pillar', {}) if isinstance(pillar, ThreadLocalProxy): pillar = ThreadLocalProxy.unproxy(pillar) self.context_dict['pillar'] = pillar self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar') mod_opts = {} for key, val in list(opts.items()): if key == 'logger': continue mod_opts[key] = val return mod_opts def _iter_files(self, mod_name): ''' Iterate over all file_mapping files in order of closeness to mod_name ''' # do we have an exact match? if mod_name in self.file_mapping: yield mod_name # do we have a partial match? for k in self.file_mapping: if mod_name in k: yield k # anyone else? Bueller? for k in self.file_mapping: if mod_name not in k: yield k def _reload_submodules(self, mod): submodules = ( getattr(mod, sname) for sname in dir(mod) if isinstance(getattr(mod, sname), mod.__class__) ) # reload only custom "sub"modules for submodule in submodules: # it is a submodule if the name is in a namespace under mod if submodule.__name__.startswith(mod.__name__ + '.'): reload_module(submodule) self._reload_submodules(submodule) def _load_module(self, name): mod = None fpath, suffix = self.file_mapping[name][:2] self.loaded_files.add(name) fpath_dirname = os.path.dirname(fpath) try: sys.path.append(fpath_dirname) if suffix == '.pyx': mod = pyximport.load_module(name, fpath, tempfile.gettempdir()) elif suffix == '.o': top_mod = __import__(fpath, globals(), locals(), []) comps = fpath.split('.') if len(comps) < 2: mod = top_mod else: mod = top_mod for subname in comps[1:]: mod = getattr(mod, subname) elif suffix == '.zip': mod = zipimporter(fpath).load_module(name) else: desc = self.suffix_map[suffix] # if it is a directory, we don't open a file try: mod_namespace = '.'.join(( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name)) except TypeError: mod_namespace = '{0}.{1}.{2}.{3}'.format( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name) if suffix == '': if USE_IMPORTLIB: # pylint: disable=no-member # Package directory, look for __init__ loader_details = [ (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES), (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES), (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), ] file_finder = importlib.machinery.FileFinder( fpath_dirname, *loader_details ) spec = file_finder.find_spec(mod_namespace) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: mod = imp.load_module(mod_namespace, None, fpath, desc) # reload all submodules if necessary if not self.initial_load: self._reload_submodules(mod) else: if USE_IMPORTLIB: # pylint: disable=no-member loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath) spec = importlib.util.spec_from_file_location( mod_namespace, fpath, loader=loader ) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() #mod = importlib.util.module_from_spec(spec) #spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: with salt.utils.files.fopen(fpath, desc[1]) as fn_: mod = imp.load_module(mod_namespace, fn_, fpath, desc) except IOError: raise except ImportError as exc: if 'magic number' in six.text_type(exc): error_msg = 'Failed to import {0} {1}. Bad magic number. If migrating from Python2 to Python3, remove all .pyc files and try again.'.format(self.tag, name) log.warning(error_msg) self.missing_modules[name] = error_msg log.debug( 'Failed to import %s %s:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = exc return False except Exception as error: log.error( 'Failed to import %s %s, this is due most likely to a ' 'syntax error:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False except SystemExit as error: try: fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1] except Exception: pass else: tgt_fn = os.path.join('salt', 'utils', 'process.py') if fn_.endswith(tgt_fn) and '_handle_signals' in caller: # Race conditon, SIGTERM or SIGINT received while loader # was in process of loading a module. Call sys.exit to # ensure that the process is killed. sys.exit(salt.defaults.exitcodes.EX_OK) log.error( 'Failed to import %s %s as the module called exit()\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False finally: sys.path.remove(fpath_dirname) if hasattr(mod, '__opts__'): mod.__opts__.update(self.opts) else: mod.__opts__ = self.opts # pack whatever other globals we were asked to for p_name, p_value in six.iteritems(self.pack): _inject_into_mod(mod, p_name, p_value) module_name = mod.__name__.rsplit('.', 1)[-1] # Call a module's initialization method if it exists module_init = getattr(mod, '__init__', None) if inspect.isfunction(module_init): try: module_init(self.opts) except TypeError as e: log.error(e) except Exception: err_string = '__init__ failed' log.debug( 'Error loading %s.%s: %s', self.tag, module_name, err_string, exc_info=True ) self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False # if virtual modules are enabled, we need to look for the # __virtual__() function inside that module and run it. if self.virtual_enable: virtual_funcs_to_process = ['__virtual__'] + self.virtual_funcs for virtual_func in virtual_funcs_to_process: virtual_ret, module_name, virtual_err, virtual_aliases = \ self._process_virtual(mod, module_name, virtual_func) if virtual_err is not None: log.trace( 'Error loading %s.%s: %s', self.tag, module_name, virtual_err ) # if _process_virtual returned a non-True value then we are # supposed to not process this module if virtual_ret is not True and module_name not in self.missing_modules: # If a module has information about why it could not be loaded, record it self.missing_modules[module_name] = virtual_err self.missing_modules[name] = virtual_err return False else: virtual_aliases = () # If this is a proxy minion then MOST modules cannot work. Therefore, require that # any module that does work with salt-proxy-minion define __proxyenabled__ as a list # containing the names of the proxy types that the module supports. # # Render modules and state modules are OK though if 'proxy' in self.opts: if self.tag in ['grains', 'proxy']: if not hasattr(mod, '__proxyenabled__') or \ (self.opts['proxy']['proxytype'] not in mod.__proxyenabled__ and '*' not in mod.__proxyenabled__): err_string = 'not a proxy_minion enabled module' self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False if getattr(mod, '__load__', False) is not False: log.info( 'The functions from module \'%s\' are being loaded from the ' 'provided __load__ attribute', module_name ) # If we had another module by the same virtual name, we should put any # new functions under the existing dictionary. mod_names = [module_name] + list(virtual_aliases) mod_dict = dict(( (x, self.loaded_modules.get(x, self.mod_dict_class())) for x in mod_names )) for attr in getattr(mod, '__load__', dir(mod)): if attr.startswith('_') and attr != '__call__': # private functions are skipped, # except __call__ which is default entrance # for multi-function batch-like state syntax continue func = getattr(mod, attr) if not inspect.isfunction(func) and not isinstance(func, functools.partial): # Not a function!? Skip it!!! continue # Let's get the function name. # If the module has the __func_alias__ attribute, it must be a # dictionary mapping in the form of(key -> value): # <real-func-name> -> <desired-func-name> # # It default's of course to the found callable attribute name # if no alias is defined. funcname = getattr(mod, '__func_alias__', {}).get(attr, attr) for tgt_mod in mod_names: try: full_funcname = '.'.join((tgt_mod, funcname)) except TypeError: full_funcname = '{0}.{1}'.format(tgt_mod, funcname) # Save many references for lookups # Careful not to overwrite existing (higher priority) functions if full_funcname not in self._dict: self._dict[full_funcname] = func if funcname not in mod_dict[tgt_mod]: setattr(mod_dict[tgt_mod], funcname, func) mod_dict[tgt_mod][funcname] = func self._apply_outputter(func, mod) # enforce depends try: Depends.enforce_dependencies(self._dict, self.tag) except RuntimeError as exc: log.info( 'Depends.enforce_dependencies() failed for the following ' 'reason: %s', exc ) for tgt_mod in mod_names: self.loaded_modules[tgt_mod] = mod_dict[tgt_mod] return True def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise KeyError('The key \'{0}\' should contain a \'.\''.format(key)) mod_name, _ = key.split('.', 1) with self._lock: # It is possible that the key is in the dictionary after # acquiring the lock due to another thread loading it. if mod_name in self.missing_modules or key in self._dict: return True # if the modulename isn't in the whitelist, don't bother if self.whitelist and mod_name not in self.whitelist: log.error( 'Failed to load function %s because its module (%s) is ' 'not in the whitelist: %s', key, mod_name, self.whitelist ) raise KeyError(key) def _inner_load(mod_name): for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and key in self._dict: return True return False # try to load the module ret = None reloaded = False # re-scan up to once, IOErrors or a failed load cause re-scans of the # filesystem while True: try: ret = _inner_load(mod_name) if not reloaded and ret is not True: self._refresh_file_mapping() reloaded = True continue break except IOError: if not reloaded: self._refresh_file_mapping() reloaded = True continue return ret def _load_all(self): ''' Load all of them ''' with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True def reload_modules(self): with self._lock: self.loaded_files = set() self._load_all() def _apply_outputter(self, func, mod): ''' Apply the __outputter__ variable to the functions ''' if hasattr(mod, '__outputter__'): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__] def _process_virtual(self, mod, module_name, virtual_func='__virtual__'): ''' Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1] ''' # The __virtual__ function will return either a True or False value. # If it returns a True value it can also set a module level attribute # named __virtualname__ with the name that the module should be # referred to as. # # This allows us to have things like the pkg module working on all # platforms under the name 'pkg'. It also allows for modules like # augeas_cfg to be referred to as 'augeas', which would otherwise have # namespace collisions. And finally it allows modules to return False # if they are not intended to run on the given platform or are missing # dependencies. virtual_aliases = getattr(mod, '__virtual_aliases__', tuple()) try: error_reason = None if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__): try: start = time.time() virtual = getattr(mod, virtual_func)() if isinstance(virtual, tuple): error_reason = virtual[1] virtual = virtual[0] if self.opts.get('virtual_timer', False): end = time.time() - start msg = 'Virtual function took {0} seconds for {1}'.format( end, module_name) log.warning(msg) except Exception as exc: error_reason = ( 'Exception raised when processing __virtual__ function' ' for {0}. Module will not be loaded: {1}'.format( mod.__name__, exc)) log.error(error_reason, exc_info_on_loglevel=logging.DEBUG) virtual = None # Get the module's virtual name virtualname = getattr(mod, '__virtualname__', virtual) if not virtual: # if __virtual__() evaluates to False then the module # wasn't meant for this platform or it's not supposed to # load for some other reason. # Some modules might accidentally return None and are # improperly loaded if virtual is None: log.warning( '%s.__virtual__() is wrongly returning `None`. ' 'It should either return `True`, `False` or a new ' 'name. If you\'re the developer of the module ' '\'%s\', please fix this.', mod.__name__, module_name ) return (False, module_name, error_reason, virtual_aliases) # At this point, __virtual__ did not return a # boolean value, let's check for deprecated usage # or module renames if virtual is not True and module_name != virtual: # The module is renaming itself. Updating the module name # with the new name log.trace('Loaded %s as virtual %s', module_name, virtual) if virtualname != virtual: # The __virtualname__ attribute does not match what's # being returned by the __virtual__() function. This # should be considered an error. log.error( 'The module \'%s\' is showing some bad usage. Its ' '__virtualname__ attribute is set to \'%s\' yet the ' '__virtual__() function is returning \'%s\'. These ' 'values should match!', mod.__name__, virtualname, virtual ) module_name = virtualname # If the __virtual__ function returns True and __virtualname__ # is set then use it elif virtual is True and virtualname != module_name: if virtualname is not True: module_name = virtualname except KeyError: # Key errors come out of the virtual function when passing # in incomplete grains sets, these can be safely ignored # and logged to debug, still, it includes the traceback to # help debugging. log.debug('KeyError when loading %s', module_name, exc_info=True) except Exception: # If the module throws an exception during __virtual__() # then log the information and continue to the next. log.error( 'Failed to read the virtual function for %s: %s', self.tag, module_name, exc_info=True ) return (False, module_name, error_reason, virtual_aliases) return (True, module_name, None, virtual_aliases) def global_injector_decorator(inject_globals): ''' Decorator used by the LazyLoader to inject globals into a function at execute time. globals Dictionary with global variables to inject ''' def inner_decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): with salt.utils.context.func_globals_inject(f, **inject_globals): return f(*args, **kwargs) return wrapper return inner_decorator
saltstack/salt
salt/loader.py
ssh_wrapper
python
def ssh_wrapper(opts, functions=None, context=None): ''' Returns the custom logging handler modules ''' return LazyLoader( _module_dirs( opts, 'wrapper', base_path=os.path.join(SALT_BASE_PATH, os.path.join('client', 'ssh')), ), opts, tag='wrapper', pack={ '__salt__': functions, '__grains__': opts.get('grains', {}), '__pillar__': opts.get('pillar', {}), '__context__': context, }, )
Returns the custom logging handler modules
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L613-L631
null
# -*- coding: utf-8 -*- ''' The Salt loader is the core to Salt's plugin system, the loader scans directories for python loadable code and organizes the code into the plugin interfaces used by Salt. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import sys import time import logging import inspect import tempfile import threading import functools import threading import traceback import types from zipimport import zipimporter # Import salt libs import salt.config import salt.defaults.events import salt.defaults.exitcodes import salt.syspaths import salt.utils.args import salt.utils.context import salt.utils.data import salt.utils.dictupdate import salt.utils.event import salt.utils.files import salt.utils.lazy import salt.utils.odict import salt.utils.platform import salt.utils.versions import salt.utils.stringutils from salt.exceptions import LoaderError from salt.template import check_render_pipe_str from salt.utils.decorators import Depends from salt.utils.thread_local_proxy import ThreadLocalProxy # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import reload_module if sys.version_info[:2] >= (3, 5): import importlib.machinery # pylint: disable=no-name-in-module,import-error import importlib.util # pylint: disable=no-name-in-module,import-error USE_IMPORTLIB = True else: import imp USE_IMPORTLIB = False try: from collections.abc import MutableMapping except ImportError: from collections import MutableMapping try: import pkg_resources HAS_PKG_RESOURCES = True except ImportError: HAS_PKG_RESOURCES = False log = logging.getLogger(__name__) SALT_BASE_PATH = os.path.abspath(salt.syspaths.INSTALL_DIR) LOADED_BASE_NAME = 'salt.loaded' if USE_IMPORTLIB: # pylint: disable=no-member MODULE_KIND_SOURCE = 1 MODULE_KIND_COMPILED = 2 MODULE_KIND_EXTENSION = 3 MODULE_KIND_PKG_DIRECTORY = 5 SUFFIXES = [] for suffix in importlib.machinery.EXTENSION_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_EXTENSION)) for suffix in importlib.machinery.SOURCE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_SOURCE)) for suffix in importlib.machinery.BYTECODE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_COMPILED)) MODULE_KIND_MAP = { MODULE_KIND_SOURCE: importlib.machinery.SourceFileLoader, MODULE_KIND_COMPILED: importlib.machinery.SourcelessFileLoader, MODULE_KIND_EXTENSION: importlib.machinery.ExtensionFileLoader } # pylint: enable=no-member else: SUFFIXES = imp.get_suffixes() PY3_PRE_EXT = \ re.compile(r'\.cpython-{0}{1}(\.opt-[1-9])?'.format(*sys.version_info[:2])) # Because on the cloud drivers we do `from salt.cloud.libcloudfuncs import *` # which simplifies code readability, it adds some unsupported functions into # the driver's module scope. # We list un-supported functions here. These will be removed from the loaded. # TODO: remove the need for this cross-module code. Maybe use NotImplemented LIBCLOUD_FUNCS_NOT_SUPPORTED = ( 'parallels.avail_sizes', 'parallels.avail_locations', 'proxmox.avail_sizes', ) # Will be set to pyximport module at runtime if cython is enabled in config. pyximport = None def static_loader( opts, ext_type, tag, pack=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, filter_name=None, ): funcs = LazyLoader( _module_dirs( opts, ext_type, tag, int_type, ext_dirs, ext_type_dirs, base_path, ), opts, tag=tag, pack=pack, ) ret = {} funcs._load_all() if filter_name: funcs = FilterDictWrapper(funcs, filter_name) for key in funcs: ret[key] = funcs[key] return ret def _format_entrypoint_target(ep): ''' Makes a string describing the target of an EntryPoint object. Base strongly on EntryPoint.__str__(). ''' s = ep.module_name if ep.attrs: s += ':' + '.'.join(ep.attrs) return s def _module_dirs( opts, ext_type, tag=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, ): if tag is None: tag = ext_type sys_types = os.path.join(base_path or SALT_BASE_PATH, int_type or ext_type) ext_types = os.path.join(opts['extension_modules'], ext_type) ext_type_types = [] if ext_dirs: if ext_type_dirs is None: ext_type_dirs = '{0}_dirs'.format(tag) if ext_type_dirs in opts: ext_type_types.extend(opts[ext_type_dirs]) if HAS_PKG_RESOURCES and ext_type_dirs: for entry_point in pkg_resources.iter_entry_points('salt.loader', ext_type_dirs): try: loaded_entry_point = entry_point.load() for path in loaded_entry_point(): ext_type_types.append(path) except Exception as exc: log.error("Error getting module directories from %s: %s", _format_entrypoint_target(entry_point), exc) log.debug("Full backtrace for module directories error", exc_info=True) cli_module_dirs = [] # The dirs can be any module dir, or a in-tree _{ext_type} dir for _dir in opts.get('module_dirs', []): # Prepend to the list to match cli argument ordering maybe_dir = os.path.join(_dir, ext_type) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) continue maybe_dir = os.path.join(_dir, '_{0}'.format(ext_type)) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) return cli_module_dirs + ext_type_types + [ext_types, sys_types] def minion_mods( opts, context=None, utils=None, whitelist=None, initial_load=False, loaded_base_name=None, notify=False, static_modules=None, proxy=None): ''' Load execution modules Returns a dictionary of execution modules appropriate for the current system by evaluating the __virtual__() function in each module. :param dict opts: The Salt options dictionary :param dict context: A Salt context that should be made present inside generated modules in __context__ :param dict utils: Utility functions which should be made available to Salt modules in __utils__. See `utils_dirs` in salt.config for additional information about configuration. :param list whitelist: A list of modules which should be whitelisted. :param bool initial_load: Deprecated flag! Unused. :param str loaded_base_name: A string marker for the loaded base name. :param bool notify: Flag indicating that an event should be fired upon completion of module loading. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) __opts__['grains'] = __grains__ __utils__ = salt.loader.utils(__opts__) __salt__ = salt.loader.minion_mods(__opts__, utils=__utils__) __salt__['test.ping']() ''' # TODO Publish documentation for module whitelisting if not whitelist: whitelist = opts.get('whitelist_modules', None) ret = LazyLoader( _module_dirs(opts, 'modules', 'module'), opts, tag='module', pack={'__context__': context, '__utils__': utils, '__proxy__': proxy}, whitelist=whitelist, loaded_base_name=loaded_base_name, static_modules=static_modules, ) ret.pack['__salt__'] = ret # Load any provider overrides from the configuration file providers option # Note: Providers can be pkg, service, user or group - not to be confused # with cloud providers. providers = opts.get('providers', False) if providers and isinstance(providers, dict): for mod in providers: # sometimes providers opts is not to diverge modules but # for other configuration try: funcs = raw_mod(opts, providers[mod], ret) except TypeError: break else: if funcs: for func in funcs: f_key = '{0}{1}'.format(mod, func[func.rindex('.'):]) ret[f_key] = funcs[func] if notify: evt = salt.utils.event.get_event('minion', opts=opts, listen=False) evt.fire_event({'complete': True}, tag=salt.defaults.events.MINION_MOD_COMPLETE) return ret def raw_mod(opts, name, functions, mod='modules'): ''' Returns a single module loaded raw and bypassing the __virtual__ function .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') testmod = salt.loader.raw_mod(__opts__, 'test', None) testmod['test.ping']() ''' loader = LazyLoader( _module_dirs(opts, mod, 'module'), opts, tag='rawmodule', virtual_enable=False, pack={'__salt__': functions}, ) # if we don't have the module, return an empty dict if name not in loader.file_mapping: return {} loader._load_module(name) # load a single module (the one passed in) return dict(loader._dict) # return a copy of *just* the funcs for `name` def metaproxy(opts): ''' Return functions used in the meta proxy ''' return LazyLoader( _module_dirs(opts, 'metaproxy'), opts, tag='metaproxy' ) def matchers(opts): ''' Return the matcher services plugins ''' return LazyLoader( _module_dirs(opts, 'matchers'), opts, tag='matchers' ) def engines(opts, functions, runners, utils, proxy=None): ''' Return the master services plugins ''' pack = {'__salt__': functions, '__runners__': runners, '__proxy__': proxy, '__utils__': utils} return LazyLoader( _module_dirs(opts, 'engines'), opts, tag='engines', pack=pack, ) def proxy(opts, functions=None, returners=None, whitelist=None, utils=None): ''' Returns the proxy module for this salt-proxy-minion ''' ret = LazyLoader( _module_dirs(opts, 'proxy'), opts, tag='proxy', pack={'__salt__': functions, '__ret__': returners, '__utils__': utils}, ) ret.pack['__proxy__'] = ret return ret def returners(opts, functions, whitelist=None, context=None, proxy=None): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'returners', 'returner'), opts, tag='returner', whitelist=whitelist, pack={'__salt__': functions, '__context__': context, '__proxy__': proxy or {}}, ) def utils(opts, whitelist=None, context=None, proxy=proxy): ''' Returns the utility modules ''' return LazyLoader( _module_dirs(opts, 'utils', ext_type_dirs='utils_dirs'), opts, tag='utils', whitelist=whitelist, pack={'__context__': context, '__proxy__': proxy or {}}, ) def pillars(opts, functions, context=None): ''' Returns the pillars modules ''' ret = LazyLoader(_module_dirs(opts, 'pillar'), opts, tag='pillar', pack={'__salt__': functions, '__context__': context, '__utils__': utils(opts)}) ret.pack['__ext_pillar__'] = ret return FilterDictWrapper(ret, '.ext_pillar') def tops(opts): ''' Returns the tops modules ''' if 'master_tops' not in opts: return {} whitelist = list(opts['master_tops'].keys()) ret = LazyLoader( _module_dirs(opts, 'tops', 'top'), opts, tag='top', whitelist=whitelist, ) return FilterDictWrapper(ret, '.top') def wheels(opts, whitelist=None, context=None): ''' Returns the wheels modules ''' if context is None: context = {} return LazyLoader( _module_dirs(opts, 'wheel'), opts, tag='wheel', whitelist=whitelist, pack={'__context__': context}, ) def outputters(opts): ''' Returns the outputters modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only outputters present in the keyspace ''' ret = LazyLoader( _module_dirs(opts, 'output', ext_type_dirs='outputter_dirs'), opts, tag='output', ) wrapped_ret = FilterDictWrapper(ret, '.output') # TODO: this name seems terrible... __salt__ should always be execution mods ret.pack['__salt__'] = wrapped_ret return wrapped_ret def serializers(opts): ''' Returns the serializers modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only serializers present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'serializers'), opts, tag='serializers', ) def eauth_tokens(opts): ''' Returns the tokens modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only token backends present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'tokens'), opts, tag='tokens', ) def auth(opts, whitelist=None): ''' Returns the auth modules :param dict opts: The Salt options dictionary :returns: LazyLoader ''' return LazyLoader( _module_dirs(opts, 'auth'), opts, tag='auth', whitelist=whitelist, pack={'__salt__': minion_mods(opts)}, ) def fileserver(opts, backends): ''' Returns the file server modules ''' return LazyLoader(_module_dirs(opts, 'fileserver'), opts, tag='fileserver', whitelist=backends, pack={'__utils__': utils(opts)}) def roster(opts, runner=None, utils=None, whitelist=None): ''' Returns the roster modules ''' return LazyLoader( _module_dirs(opts, 'roster'), opts, tag='roster', whitelist=whitelist, pack={ '__runner__': runner, '__utils__': utils, }, ) def thorium(opts, functions, runners): ''' Load the thorium runtime modules ''' pack = {'__salt__': functions, '__runner__': runners, '__context__': {}} ret = LazyLoader(_module_dirs(opts, 'thorium'), opts, tag='thorium', pack=pack) ret.pack['__thorium__'] = ret return ret def states(opts, functions, utils, serializers, whitelist=None, proxy=None, context=None): ''' Returns the state modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') statemods = salt.loader.states(__opts__, None, None) ''' if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'states'), opts, tag='states', pack={'__salt__': functions, '__proxy__': proxy or {}}, whitelist=whitelist, ) ret.pack['__states__'] = ret ret.pack['__utils__'] = utils ret.pack['__serializers__'] = serializers ret.pack['__context__'] = context return ret def beacons(opts, functions, context=None, proxy=None): ''' Load the beacon modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. ''' return LazyLoader( _module_dirs(opts, 'beacons'), opts, tag='beacons', pack={'__context__': context, '__salt__': functions, '__proxy__': proxy or {}}, virtual_funcs=[], ) def log_handlers(opts): ''' Returns the custom logging handler modules :param dict opts: The Salt options dictionary ''' ret = LazyLoader( _module_dirs( opts, 'log_handlers', int_type='handlers', base_path=os.path.join(SALT_BASE_PATH, 'log'), ), opts, tag='log_handlers', ) return FilterDictWrapper(ret, '.setup_handlers') def render(opts, functions, states=None, proxy=None, context=None): ''' Returns the render modules ''' if context is None: context = {} pack = {'__salt__': functions, '__grains__': opts.get('grains', {}), '__context__': context} if states: pack['__states__'] = states pack['__proxy__'] = proxy or {} ret = LazyLoader( _module_dirs( opts, 'renderers', 'render', ext_type_dirs='render_dirs', ), opts, tag='render', pack=pack, ) rend = FilterDictWrapper(ret, '.render') if not check_render_pipe_str(opts['renderer'], rend, opts['renderer_blacklist'], opts['renderer_whitelist']): err = ('The renderer {0} is unavailable, this error is often because ' 'the needed software is unavailable'.format(opts['renderer'])) log.critical(err) raise LoaderError(err) return rend def grain_funcs(opts, proxy=None): ''' Returns the grain functions .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') grainfuncs = salt.loader.grain_funcs(__opts__) ''' ret = LazyLoader( _module_dirs( opts, 'grains', 'grain', ext_type_dirs='grains_dirs', ), opts, tag='grains', ) ret.pack['__utils__'] = utils(opts, proxy=proxy) return ret def _load_cached_grains(opts, cfn): ''' Returns the grains cached in cfn, or None if the cache is too old or is corrupted. ''' if not os.path.isfile(cfn): log.debug('Grains cache file does not exist.') return None grains_cache_age = int(time.time() - os.path.getmtime(cfn)) if grains_cache_age > opts.get('grains_cache_expiration', 300): log.debug( 'Grains cache last modified %s seconds ago and cache ' 'expiration is set to %s. Grains cache expired. ' 'Refreshing.', grains_cache_age, opts.get('grains_cache_expiration', 300) ) return None if opts.get('refresh_grains_cache', False): log.debug('refresh_grains_cache requested, Refreshing.') return None log.debug('Retrieving grains from cache') try: serial = salt.payload.Serial(opts) with salt.utils.files.fopen(cfn, 'rb') as fp_: cached_grains = salt.utils.data.decode(serial.load(fp_), preserve_tuples=True) if not cached_grains: log.debug('Cached grains are empty, cache might be corrupted. Refreshing.') return None return cached_grains except (IOError, OSError): return None def grains(opts, force_refresh=False, proxy=None): ''' Return the functions for the dynamic grains and the values for the static grains. Since grains are computed early in the startup process, grains functions do not have __salt__ or __proxy__ available. At proxy-minion startup, this function is called with the proxymodule LazyLoader object so grains functions can communicate with their controlled device. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) print __grains__['id'] ''' # Need to re-import salt.config, somehow it got lost when a minion is starting import salt.config # if we have no grains, lets try loading from disk (TODO: move to decorator?) cfn = os.path.join( opts['cachedir'], 'grains.cache.p' ) if not force_refresh and opts.get('grains_cache', False): cached_grains = _load_cached_grains(opts, cfn) if cached_grains: return cached_grains else: log.debug('Grains refresh requested. Refreshing grains.') if opts.get('skip_grains', False): return {} grains_deep_merge = opts.get('grains_deep_merge', False) is True if 'conf_file' in opts: pre_opts = {} pre_opts.update(salt.config.load_config( opts['conf_file'], 'SALT_MINION_CONFIG', salt.config.DEFAULT_MINION_OPTS['conf_file'] )) default_include = pre_opts.get( 'default_include', opts['default_include'] ) include = pre_opts.get('include', []) pre_opts.update(salt.config.include_config( default_include, opts['conf_file'], verbose=False )) pre_opts.update(salt.config.include_config( include, opts['conf_file'], verbose=True )) if 'grains' in pre_opts: opts['grains'] = pre_opts['grains'] else: opts['grains'] = {} else: opts['grains'] = {} grains_data = {} blist = opts.get('grains_blacklist', []) funcs = grain_funcs(opts, proxy=proxy) if force_refresh: # if we refresh, lets reload grain modules funcs.clear() # Run core grains for key in funcs: if not key.startswith('core.'): continue log.trace('Loading %s grain', key) ret = funcs[key]() if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) # Run the rest of the grains for key in funcs: if key.startswith('core.') or key == '_errors': continue try: # Grains are loaded too early to take advantage of the injected # __proxy__ variable. Pass an instance of that LazyLoader # here instead to grains functions if the grains functions take # one parameter. Then the grains can have access to the # proxymodule for retrieving information from the connected # device. log.trace('Loading %s grain', key) parameters = salt.utils.args.get_function_argspec(funcs[key]).args kwargs = {} if 'proxy' in parameters: kwargs['proxy'] = proxy if 'grains' in parameters: kwargs['grains'] = grains_data ret = funcs[key](**kwargs) except Exception: if salt.utils.platform.is_proxy(): log.info('The following CRITICAL message may not be an error; the proxy may not be completely established yet.') log.critical( 'Failed to load grains defined in grain file %s in ' 'function %s, error:\n', key, funcs[key], exc_info=True ) continue if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) if opts.get('proxy_merge_grains_in_module', True) and proxy: try: proxytype = proxy.opts['proxy']['proxytype'] if proxytype + '.grains' in proxy: if proxytype + '.initialized' in proxy and proxy[proxytype + '.initialized'](): try: proxytype = proxy.opts['proxy']['proxytype'] ret = proxy[proxytype + '.grains']() if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) except Exception: log.critical('Failed to run proxy\'s grains function!', exc_info=True ) except KeyError: pass grains_data.update(opts['grains']) # Write cache if enabled if opts.get('grains_cache', False): with salt.utils.files.set_umask(0o077): try: if salt.utils.platform.is_windows(): # Late import import salt.modules.cmdmod # Make sure cache file isn't read-only salt.modules.cmdmod._run_quiet('attrib -R "{0}"'.format(cfn)) with salt.utils.files.fopen(cfn, 'w+b') as fp_: try: serial = salt.payload.Serial(opts) serial.dump(grains_data, fp_) except TypeError as e: log.error('Failed to serialize grains cache: %s', e) raise # re-throw for cleanup except Exception as e: log.error('Unable to write to grains cache file %s: %s', cfn, e) # Based on the original exception, the file may or may not have been # created. If it was, we will remove it now, as the exception means # the serialized data is not to be trusted, no matter what the # exception is. if os.path.isfile(cfn): os.unlink(cfn) if grains_deep_merge: salt.utils.dictupdate.update(grains_data, opts['grains']) else: grains_data.update(opts['grains']) return salt.utils.data.decode(grains_data, preserve_tuples=True) # TODO: get rid of? Does anyone use this? You should use raw() instead def call(fun, **kwargs): ''' Directly call a function inside a loader directory ''' args = kwargs.get('args', []) dirs = kwargs.get('dirs', []) funcs = LazyLoader( [os.path.join(SALT_BASE_PATH, 'modules')] + dirs, None, tag='modules', virtual_enable=False, ) return funcs[fun](*args) def runner(opts, utils=None, context=None, whitelist=None): ''' Directly call a function inside a loader directory ''' if utils is None: utils = {} if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'runners', 'runner', ext_type_dirs='runner_dirs'), opts, tag='runners', pack={'__utils__': utils, '__context__': context}, whitelist=whitelist, ) # TODO: change from __salt__ to something else, we overload __salt__ too much ret.pack['__salt__'] = ret return ret def queues(opts): ''' Directly call a function inside a loader directory ''' return LazyLoader( _module_dirs(opts, 'queues', 'queue', ext_type_dirs='queue_dirs'), opts, tag='queues', ) def sdb(opts, functions=None, whitelist=None, utils=None): ''' Make a very small database call ''' if utils is None: utils = {} return LazyLoader( _module_dirs(opts, 'sdb'), opts, tag='sdb', pack={ '__sdb__': functions, '__opts__': opts, '__utils__': utils, '__salt__': minion_mods(opts, utils), }, whitelist=whitelist, ) def pkgdb(opts): ''' Return modules for SPM's package database .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgdb', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgdb' ) def pkgfiles(opts): ''' Return modules for SPM's file handling .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgfiles', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgfiles' ) def clouds(opts): ''' Return the cloud functions ''' # Let's bring __active_provider_name__, defaulting to None, to all cloud # drivers. This will get temporarily updated/overridden with a context # manager when needed. functions = LazyLoader( _module_dirs(opts, 'clouds', 'cloud', base_path=os.path.join(SALT_BASE_PATH, 'cloud'), int_type='clouds'), opts, tag='clouds', pack={'__utils__': salt.loader.utils(opts), '__active_provider_name__': None}, ) for funcname in LIBCLOUD_FUNCS_NOT_SUPPORTED: log.trace( '\'%s\' has been marked as not supported. Removing from the ' 'list of supported cloud functions', funcname ) functions.pop(funcname, None) return functions def netapi(opts): ''' Return the network api functions ''' return LazyLoader( _module_dirs(opts, 'netapi'), opts, tag='netapi', ) def executors(opts, functions=None, context=None, proxy=None): ''' Returns the executor modules ''' executors = LazyLoader( _module_dirs(opts, 'executors', 'executor'), opts, tag='executor', pack={'__salt__': functions, '__context__': context or {}, '__proxy__': proxy or {}}, ) executors.pack['__executors__'] = executors return executors def cache(opts, serial): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'cache', 'cache'), opts, tag='cache', pack={'__opts__': opts, '__context__': {'serial': serial}}, ) def _generate_module(name): if name in sys.modules: return code = "'''Salt loaded {0} parent module'''".format(name.split('.')[-1]) # ModuleType can't accept a unicode type on PY2 module = types.ModuleType(str(name)) # future lint: disable=blacklisted-function exec(code, module.__dict__) sys.modules[name] = module def _mod_type(module_path): if module_path.startswith(SALT_BASE_PATH): return 'int' return 'ext' def _inject_into_mod(mod, name, value, force_lock=False): ''' Inject a variable into a module. This is used to inject "globals" like ``__salt__``, ``__pillar``, or ``grains``. Instead of injecting the value directly, a ``ThreadLocalProxy`` is created. If such a proxy is already present under the specified name, it is updated with the new value. This update only affects the current thread, so that the same name can refer to different values depending on the thread of execution. This is important for data that is not truly global. For example, pillar data might be dynamically overriden through function parameters and thus the actual values available in pillar might depend on the thread that is calling a module. mod: module object into which the value is going to be injected. name: name of the variable that is injected into the module. value: value that is injected into the variable. The value is not injected directly, but instead set as the new reference of the proxy that has been created for the variable. force_lock: whether the lock should be acquired before checking whether a proxy object for the specified name has already been injected into the module. If ``False`` (the default), this function checks for the module's variable without acquiring the lock and only acquires the lock if a new proxy has to be created and injected. ''' old_value = getattr(mod, name, None) # We use a double-checked locking scheme in order to avoid taking the lock # when a proxy object has already been injected. # In most programming languages, double-checked locking is considered # unsafe when used without explicit memory barriers because one might read # an uninitialized value. In CPython it is safe due to the global # interpreter lock (GIL). In Python implementations that do not have the # GIL, it could be unsafe, but at least Jython also guarantees that (for # Python objects) memory is not corrupted when writing and reading without # explicit synchronization # (http://www.jython.org/jythonbook/en/1.0/Concurrency.html). # Please note that in order to make this code safe in a runtime environment # that does not make this guarantees, it is not sufficient. The # ThreadLocalProxy must also be created with fallback_to_shared set to # False or a lock must be added to the ThreadLocalProxy. if force_lock: with _inject_into_mod.lock: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: setattr(mod, name, ThreadLocalProxy(value, True)) else: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: _inject_into_mod(mod, name, value, True) # Lock used when injecting globals. This is needed to avoid a race condition # when two threads try to load the same module concurrently. This must be # outside the loader because there might be more than one loader for the same # namespace. _inject_into_mod.lock = threading.RLock() # TODO: move somewhere else? class FilterDictWrapper(MutableMapping): ''' Create a dict which wraps another dict with a specific key suffix on get This is to replace "filter_load" ''' def __init__(self, d, suffix): self._dict = d self.suffix = suffix def __setitem__(self, key, val): self._dict[key] = val def __delitem__(self, key): del self._dict[key] def __getitem__(self, key): return self._dict[key + self.suffix] def __len__(self): return len(self._dict) def __iter__(self): for key in self._dict: if key.endswith(self.suffix): yield key.replace(self.suffix, '') class LazyLoader(salt.utils.lazy.LazyDict): ''' A pseduo-dictionary which has a set of keys which are the name of the module and function, delimited by a dot. When the value of the key is accessed, the function is then loaded from disk and into memory. .. note:: Iterating over keys will cause all modules to be loaded. :param list module_dirs: A list of directories on disk to search for modules :param dict opts: The salt options dictionary. :param str tag: The tag for the type of module to load :param func mod_type_check: A function which can be used to verify files :param dict pack: A dictionary of function to be packed into modules as they are loaded :param list whitelist: A list of modules to whitelist :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules. :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality. If not true, the module will not load. :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values are function references themselves which are loaded on-demand. # TODO: - move modules_max_memory into here - singletons (per tag) ''' mod_dict_class = salt.utils.odict.OrderedDict def __init__(self, module_dirs, opts=None, tag='module', loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, proxy=None, virtual_funcs=None, ): # pylint: disable=W0231 ''' In pack, if any of the values are None they will be replaced with an empty context-specific dict ''' self.inject_globals = {} self.pack = {} if pack is None else pack if opts is None: opts = {} threadsafety = not opts.get('multiprocessing') self.context_dict = salt.utils.context.ContextDict(threadsafe=threadsafety) self.opts = self.__prep_mod_opts(opts) self.module_dirs = module_dirs self.tag = tag self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME self.mod_type_check = mod_type_check or _mod_type if '__context__' not in self.pack: self.pack['__context__'] = None for k, v in six.iteritems(self.pack): if v is None: # if the value of a pack is None, lets make an empty dict value = self.context_dict.get(k, {}) if isinstance(value, ThreadLocalProxy): value = ThreadLocalProxy.unproxy(value) self.context_dict[k] = value self.pack[k] = salt.utils.context.NamespacedDictWrapper(self.context_dict, k) self.whitelist = whitelist self.virtual_enable = virtual_enable self.initial_load = True # names of modules that we don't have (errors, __virtual__, etc.) self.missing_modules = {} # mapping of name -> error self.loaded_modules = {} # mapping of module_name -> dict_of_functions self.loaded_files = set() # TODO: just remove them from file_mapping? self.static_modules = static_modules if static_modules else [] if virtual_funcs is None: virtual_funcs = [] self.virtual_funcs = virtual_funcs self.disabled = set( self.opts.get( 'disable_{0}{1}'.format( self.tag, '' if self.tag[-1] == 's' else 's' ), [] ) ) # A map of suffix to description for imp self.suffix_map = {} # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [''] for (suffix, mode, kind) in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) self._lock = threading.RLock() self._refresh_file_mapping() super(LazyLoader, self).__init__() # late init the lazy loader # create all of the import namespaces _generate_module('{0}.int'.format(self.loaded_base_name)) _generate_module('{0}.int.{1}'.format(self.loaded_base_name, tag)) _generate_module('{0}.ext'.format(self.loaded_base_name)) _generate_module('{0}.ext.{1}'.format(self.loaded_base_name, tag)) def __getitem__(self, item): ''' Override the __getitem__ in order to decorate the returned function if we need to last-minute inject globals ''' func = super(LazyLoader, self).__getitem__(item) if self.inject_globals: return global_injector_decorator(self.inject_globals)(func) else: return func def __getattr__(self, mod_name): ''' Allow for "direct" attribute access-- this allows jinja templates to access things like `salt.test.ping()` ''' if mod_name in ('__getstate__', '__setstate__'): return object.__getattribute__(self, mod_name) # if we have an attribute named that, lets return it. try: return object.__getattr__(self, mod_name) # pylint: disable=no-member except AttributeError: pass # otherwise we assume its jinja template access if mod_name not in self.loaded_modules and not self.loaded: for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and mod_name in self.loaded_modules: break if mod_name in self.loaded_modules: return self.loaded_modules[mod_name] else: raise AttributeError(mod_name) def missing_fun_string(self, function_name): ''' Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ''' mod_name = function_name.split('.')[0] if mod_name in self.loaded_modules: return '\'{0}\' is not available.'.format(function_name) else: try: reason = self.missing_modules[mod_name] except KeyError: return '\'{0}\' is not available.'.format(function_name) else: if reason is not None: return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason) else: return '\'{0}\' __virtual__ returned False'.format(mod_name) def _refresh_file_mapping(self): ''' refresh the mapping of the FS on disk ''' # map of suffix to description for imp if self.opts.get('cython_enable', True) is True: try: global pyximport pyximport = __import__('pyximport') # pylint: disable=import-error pyximport.install() # add to suffix_map so file_mapping will pick it up self.suffix_map['.pyx'] = tuple() except ImportError: log.info('Cython is enabled in the options but not present ' 'in the system path. Skipping Cython modules.') # Allow for zipimport of modules if self.opts.get('enable_zip_modules', True) is True: self.suffix_map['.zip'] = tuple() # allow for module dirs if USE_IMPORTLIB: self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY) else: self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY) # create mapping of filename (without suffix) to (path, suffix) # The files are added in order of priority, so order *must* be retained. self.file_mapping = salt.utils.odict.OrderedDict() opt_match = [] def _replace_pre_ext(obj): ''' Hack so we can get the optimization level that we replaced (if any) out of the re.sub call below. We use a list here because it is a persistent data structure that we will be able to access after re.sub is called. ''' opt_match.append(obj) return '' for mod_dir in self.module_dirs: try: # Make sure we have a sorted listdir in order to have # expectable override results files = sorted( x for x in os.listdir(mod_dir) if x != '__pycache__' ) except OSError: continue # Next mod_dir if six.PY3: try: pycache_files = [ os.path.join('__pycache__', x) for x in sorted(os.listdir(os.path.join(mod_dir, '__pycache__'))) ] except OSError: pass else: files.extend(pycache_files) for filename in files: try: dirname, basename = os.path.split(filename) if basename.startswith('_'): # skip private modules # log messages omitted for obviousness continue # Next filename f_noext, ext = os.path.splitext(basename) if six.PY3: f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext) try: opt_level = int( opt_match.pop().group(1).rsplit('-', 1)[-1] ) except (AttributeError, IndexError, ValueError): # No regex match or no optimization level matched opt_level = 0 try: opt_index = self.opts['optimization_order'].index(opt_level) except KeyError: log.trace( 'Disallowed optimization level %d for module ' 'name \'%s\', skipping. Add %d to the ' '\'optimization_order\' config option if you ' 'do not want to ignore this optimization ' 'level.', opt_level, f_noext, opt_level ) continue else: # Optimization level not reflected in filename on PY2 opt_index = 0 # make sure it is a suffix we support if ext not in self.suffix_map: continue # Next filename if f_noext in self.disabled: log.trace( 'Skipping %s, it is disabled by configuration', filename ) continue # Next filename fpath = os.path.join(mod_dir, filename) # if its a directory, lets allow us to load that if ext == '': # is there something __init__? subfiles = os.listdir(fpath) for suffix in self.suffix_order: if '' == suffix: continue # Next suffix (__init__ must have a suffix) init_file = '__init__{0}'.format(suffix) if init_file in subfiles: break else: continue # Next filename try: curr_ext = self.file_mapping[f_noext][1] curr_opt_index = self.file_mapping[f_noext][2] except KeyError: pass else: if '' in (curr_ext, ext) and curr_ext != ext: log.error( 'Module/package collision: \'%s\' and \'%s\'', fpath, self.file_mapping[f_noext][0] ) if six.PY3 and ext == '.pyc' and curr_ext == '.pyc': # Check the optimization level if opt_index >= curr_opt_index: # Module name match, but a higher-priority # optimization level was already matched, skipping. continue elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext): # Match found but a higher-priorty match already # exists, so skip this. continue if six.PY3 and not dirname and ext == '.pyc': # On Python 3, we should only load .pyc files from the # __pycache__ subdirectory (i.e. when dirname is not an # empty string). continue # Made it this far - add it self.file_mapping[f_noext] = (fpath, ext, opt_index) except OSError: continue for smod in self.static_modules: f_noext = smod.split('.')[-1] self.file_mapping[f_noext] = (smod, '.o', 0) def clear(self): ''' Clear the dict ''' with self._lock: super(LazyLoader, self).clear() # clear the lazy loader self.loaded_files = set() self.missing_modules = {} self.loaded_modules = {} # if we have been loaded before, lets clear the file mapping since # we obviously want a re-do if hasattr(self, 'opts'): self._refresh_file_mapping() self.initial_load = False def __prep_mod_opts(self, opts): ''' Strip out of the opts any logger instance ''' if '__grains__' not in self.pack: grains = opts.get('grains', {}) if isinstance(grains, ThreadLocalProxy): grains = ThreadLocalProxy.unproxy(grains) self.context_dict['grains'] = grains self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains') if '__pillar__' not in self.pack: pillar = opts.get('pillar', {}) if isinstance(pillar, ThreadLocalProxy): pillar = ThreadLocalProxy.unproxy(pillar) self.context_dict['pillar'] = pillar self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar') mod_opts = {} for key, val in list(opts.items()): if key == 'logger': continue mod_opts[key] = val return mod_opts def _iter_files(self, mod_name): ''' Iterate over all file_mapping files in order of closeness to mod_name ''' # do we have an exact match? if mod_name in self.file_mapping: yield mod_name # do we have a partial match? for k in self.file_mapping: if mod_name in k: yield k # anyone else? Bueller? for k in self.file_mapping: if mod_name not in k: yield k def _reload_submodules(self, mod): submodules = ( getattr(mod, sname) for sname in dir(mod) if isinstance(getattr(mod, sname), mod.__class__) ) # reload only custom "sub"modules for submodule in submodules: # it is a submodule if the name is in a namespace under mod if submodule.__name__.startswith(mod.__name__ + '.'): reload_module(submodule) self._reload_submodules(submodule) def _load_module(self, name): mod = None fpath, suffix = self.file_mapping[name][:2] self.loaded_files.add(name) fpath_dirname = os.path.dirname(fpath) try: sys.path.append(fpath_dirname) if suffix == '.pyx': mod = pyximport.load_module(name, fpath, tempfile.gettempdir()) elif suffix == '.o': top_mod = __import__(fpath, globals(), locals(), []) comps = fpath.split('.') if len(comps) < 2: mod = top_mod else: mod = top_mod for subname in comps[1:]: mod = getattr(mod, subname) elif suffix == '.zip': mod = zipimporter(fpath).load_module(name) else: desc = self.suffix_map[suffix] # if it is a directory, we don't open a file try: mod_namespace = '.'.join(( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name)) except TypeError: mod_namespace = '{0}.{1}.{2}.{3}'.format( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name) if suffix == '': if USE_IMPORTLIB: # pylint: disable=no-member # Package directory, look for __init__ loader_details = [ (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES), (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES), (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), ] file_finder = importlib.machinery.FileFinder( fpath_dirname, *loader_details ) spec = file_finder.find_spec(mod_namespace) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: mod = imp.load_module(mod_namespace, None, fpath, desc) # reload all submodules if necessary if not self.initial_load: self._reload_submodules(mod) else: if USE_IMPORTLIB: # pylint: disable=no-member loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath) spec = importlib.util.spec_from_file_location( mod_namespace, fpath, loader=loader ) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() #mod = importlib.util.module_from_spec(spec) #spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: with salt.utils.files.fopen(fpath, desc[1]) as fn_: mod = imp.load_module(mod_namespace, fn_, fpath, desc) except IOError: raise except ImportError as exc: if 'magic number' in six.text_type(exc): error_msg = 'Failed to import {0} {1}. Bad magic number. If migrating from Python2 to Python3, remove all .pyc files and try again.'.format(self.tag, name) log.warning(error_msg) self.missing_modules[name] = error_msg log.debug( 'Failed to import %s %s:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = exc return False except Exception as error: log.error( 'Failed to import %s %s, this is due most likely to a ' 'syntax error:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False except SystemExit as error: try: fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1] except Exception: pass else: tgt_fn = os.path.join('salt', 'utils', 'process.py') if fn_.endswith(tgt_fn) and '_handle_signals' in caller: # Race conditon, SIGTERM or SIGINT received while loader # was in process of loading a module. Call sys.exit to # ensure that the process is killed. sys.exit(salt.defaults.exitcodes.EX_OK) log.error( 'Failed to import %s %s as the module called exit()\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False finally: sys.path.remove(fpath_dirname) if hasattr(mod, '__opts__'): mod.__opts__.update(self.opts) else: mod.__opts__ = self.opts # pack whatever other globals we were asked to for p_name, p_value in six.iteritems(self.pack): _inject_into_mod(mod, p_name, p_value) module_name = mod.__name__.rsplit('.', 1)[-1] # Call a module's initialization method if it exists module_init = getattr(mod, '__init__', None) if inspect.isfunction(module_init): try: module_init(self.opts) except TypeError as e: log.error(e) except Exception: err_string = '__init__ failed' log.debug( 'Error loading %s.%s: %s', self.tag, module_name, err_string, exc_info=True ) self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False # if virtual modules are enabled, we need to look for the # __virtual__() function inside that module and run it. if self.virtual_enable: virtual_funcs_to_process = ['__virtual__'] + self.virtual_funcs for virtual_func in virtual_funcs_to_process: virtual_ret, module_name, virtual_err, virtual_aliases = \ self._process_virtual(mod, module_name, virtual_func) if virtual_err is not None: log.trace( 'Error loading %s.%s: %s', self.tag, module_name, virtual_err ) # if _process_virtual returned a non-True value then we are # supposed to not process this module if virtual_ret is not True and module_name not in self.missing_modules: # If a module has information about why it could not be loaded, record it self.missing_modules[module_name] = virtual_err self.missing_modules[name] = virtual_err return False else: virtual_aliases = () # If this is a proxy minion then MOST modules cannot work. Therefore, require that # any module that does work with salt-proxy-minion define __proxyenabled__ as a list # containing the names of the proxy types that the module supports. # # Render modules and state modules are OK though if 'proxy' in self.opts: if self.tag in ['grains', 'proxy']: if not hasattr(mod, '__proxyenabled__') or \ (self.opts['proxy']['proxytype'] not in mod.__proxyenabled__ and '*' not in mod.__proxyenabled__): err_string = 'not a proxy_minion enabled module' self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False if getattr(mod, '__load__', False) is not False: log.info( 'The functions from module \'%s\' are being loaded from the ' 'provided __load__ attribute', module_name ) # If we had another module by the same virtual name, we should put any # new functions under the existing dictionary. mod_names = [module_name] + list(virtual_aliases) mod_dict = dict(( (x, self.loaded_modules.get(x, self.mod_dict_class())) for x in mod_names )) for attr in getattr(mod, '__load__', dir(mod)): if attr.startswith('_') and attr != '__call__': # private functions are skipped, # except __call__ which is default entrance # for multi-function batch-like state syntax continue func = getattr(mod, attr) if not inspect.isfunction(func) and not isinstance(func, functools.partial): # Not a function!? Skip it!!! continue # Let's get the function name. # If the module has the __func_alias__ attribute, it must be a # dictionary mapping in the form of(key -> value): # <real-func-name> -> <desired-func-name> # # It default's of course to the found callable attribute name # if no alias is defined. funcname = getattr(mod, '__func_alias__', {}).get(attr, attr) for tgt_mod in mod_names: try: full_funcname = '.'.join((tgt_mod, funcname)) except TypeError: full_funcname = '{0}.{1}'.format(tgt_mod, funcname) # Save many references for lookups # Careful not to overwrite existing (higher priority) functions if full_funcname not in self._dict: self._dict[full_funcname] = func if funcname not in mod_dict[tgt_mod]: setattr(mod_dict[tgt_mod], funcname, func) mod_dict[tgt_mod][funcname] = func self._apply_outputter(func, mod) # enforce depends try: Depends.enforce_dependencies(self._dict, self.tag) except RuntimeError as exc: log.info( 'Depends.enforce_dependencies() failed for the following ' 'reason: %s', exc ) for tgt_mod in mod_names: self.loaded_modules[tgt_mod] = mod_dict[tgt_mod] return True def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise KeyError('The key \'{0}\' should contain a \'.\''.format(key)) mod_name, _ = key.split('.', 1) with self._lock: # It is possible that the key is in the dictionary after # acquiring the lock due to another thread loading it. if mod_name in self.missing_modules or key in self._dict: return True # if the modulename isn't in the whitelist, don't bother if self.whitelist and mod_name not in self.whitelist: log.error( 'Failed to load function %s because its module (%s) is ' 'not in the whitelist: %s', key, mod_name, self.whitelist ) raise KeyError(key) def _inner_load(mod_name): for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and key in self._dict: return True return False # try to load the module ret = None reloaded = False # re-scan up to once, IOErrors or a failed load cause re-scans of the # filesystem while True: try: ret = _inner_load(mod_name) if not reloaded and ret is not True: self._refresh_file_mapping() reloaded = True continue break except IOError: if not reloaded: self._refresh_file_mapping() reloaded = True continue return ret def _load_all(self): ''' Load all of them ''' with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True def reload_modules(self): with self._lock: self.loaded_files = set() self._load_all() def _apply_outputter(self, func, mod): ''' Apply the __outputter__ variable to the functions ''' if hasattr(mod, '__outputter__'): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__] def _process_virtual(self, mod, module_name, virtual_func='__virtual__'): ''' Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1] ''' # The __virtual__ function will return either a True or False value. # If it returns a True value it can also set a module level attribute # named __virtualname__ with the name that the module should be # referred to as. # # This allows us to have things like the pkg module working on all # platforms under the name 'pkg'. It also allows for modules like # augeas_cfg to be referred to as 'augeas', which would otherwise have # namespace collisions. And finally it allows modules to return False # if they are not intended to run on the given platform or are missing # dependencies. virtual_aliases = getattr(mod, '__virtual_aliases__', tuple()) try: error_reason = None if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__): try: start = time.time() virtual = getattr(mod, virtual_func)() if isinstance(virtual, tuple): error_reason = virtual[1] virtual = virtual[0] if self.opts.get('virtual_timer', False): end = time.time() - start msg = 'Virtual function took {0} seconds for {1}'.format( end, module_name) log.warning(msg) except Exception as exc: error_reason = ( 'Exception raised when processing __virtual__ function' ' for {0}. Module will not be loaded: {1}'.format( mod.__name__, exc)) log.error(error_reason, exc_info_on_loglevel=logging.DEBUG) virtual = None # Get the module's virtual name virtualname = getattr(mod, '__virtualname__', virtual) if not virtual: # if __virtual__() evaluates to False then the module # wasn't meant for this platform or it's not supposed to # load for some other reason. # Some modules might accidentally return None and are # improperly loaded if virtual is None: log.warning( '%s.__virtual__() is wrongly returning `None`. ' 'It should either return `True`, `False` or a new ' 'name. If you\'re the developer of the module ' '\'%s\', please fix this.', mod.__name__, module_name ) return (False, module_name, error_reason, virtual_aliases) # At this point, __virtual__ did not return a # boolean value, let's check for deprecated usage # or module renames if virtual is not True and module_name != virtual: # The module is renaming itself. Updating the module name # with the new name log.trace('Loaded %s as virtual %s', module_name, virtual) if virtualname != virtual: # The __virtualname__ attribute does not match what's # being returned by the __virtual__() function. This # should be considered an error. log.error( 'The module \'%s\' is showing some bad usage. Its ' '__virtualname__ attribute is set to \'%s\' yet the ' '__virtual__() function is returning \'%s\'. These ' 'values should match!', mod.__name__, virtualname, virtual ) module_name = virtualname # If the __virtual__ function returns True and __virtualname__ # is set then use it elif virtual is True and virtualname != module_name: if virtualname is not True: module_name = virtualname except KeyError: # Key errors come out of the virtual function when passing # in incomplete grains sets, these can be safely ignored # and logged to debug, still, it includes the traceback to # help debugging. log.debug('KeyError when loading %s', module_name, exc_info=True) except Exception: # If the module throws an exception during __virtual__() # then log the information and continue to the next. log.error( 'Failed to read the virtual function for %s: %s', self.tag, module_name, exc_info=True ) return (False, module_name, error_reason, virtual_aliases) return (True, module_name, None, virtual_aliases) def global_injector_decorator(inject_globals): ''' Decorator used by the LazyLoader to inject globals into a function at execute time. globals Dictionary with global variables to inject ''' def inner_decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): with salt.utils.context.func_globals_inject(f, **inject_globals): return f(*args, **kwargs) return wrapper return inner_decorator
saltstack/salt
salt/loader.py
render
python
def render(opts, functions, states=None, proxy=None, context=None): ''' Returns the render modules ''' if context is None: context = {} pack = {'__salt__': functions, '__grains__': opts.get('grains', {}), '__context__': context} if states: pack['__states__'] = states pack['__proxy__'] = proxy or {} ret = LazyLoader( _module_dirs( opts, 'renderers', 'render', ext_type_dirs='render_dirs', ), opts, tag='render', pack=pack, ) rend = FilterDictWrapper(ret, '.render') if not check_render_pipe_str(opts['renderer'], rend, opts['renderer_blacklist'], opts['renderer_whitelist']): err = ('The renderer {0} is unavailable, this error is often because ' 'the needed software is unavailable'.format(opts['renderer'])) log.critical(err) raise LoaderError(err) return rend
Returns the render modules
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L634-L666
[ "def check_render_pipe_str(pipestr, renderers, blacklist, whitelist):\n '''\n Check that all renderers specified in the pipe string are available.\n If so, return the list of render functions in the pipe as\n (render_func, arg_str) tuples; otherwise return [].\n '''\n if pipestr is None:\n return []\n parts = [r.strip() for r in pipestr.split('|')]\n # Note: currently, | is not allowed anywhere in the shebang line except\n # as pipes between renderers.\n\n results = []\n try:\n if parts[0] == pipestr and pipestr in OLD_STYLE_RENDERERS:\n parts = OLD_STYLE_RENDERERS[pipestr].split('|')\n for part in parts:\n name, argline = (part + ' ').split(' ', 1)\n if whitelist and name not in whitelist or \\\n blacklist and name in blacklist:\n log.warning(\n 'The renderer \"%s\" is disallowed by configuration and '\n 'will be skipped.', name\n )\n continue\n results.append((renderers[name], argline.strip()))\n return results\n except KeyError:\n log.error('The renderer \"%s\" is not available', pipestr)\n return []\n" ]
# -*- coding: utf-8 -*- ''' The Salt loader is the core to Salt's plugin system, the loader scans directories for python loadable code and organizes the code into the plugin interfaces used by Salt. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import sys import time import logging import inspect import tempfile import threading import functools import threading import traceback import types from zipimport import zipimporter # Import salt libs import salt.config import salt.defaults.events import salt.defaults.exitcodes import salt.syspaths import salt.utils.args import salt.utils.context import salt.utils.data import salt.utils.dictupdate import salt.utils.event import salt.utils.files import salt.utils.lazy import salt.utils.odict import salt.utils.platform import salt.utils.versions import salt.utils.stringutils from salt.exceptions import LoaderError from salt.template import check_render_pipe_str from salt.utils.decorators import Depends from salt.utils.thread_local_proxy import ThreadLocalProxy # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import reload_module if sys.version_info[:2] >= (3, 5): import importlib.machinery # pylint: disable=no-name-in-module,import-error import importlib.util # pylint: disable=no-name-in-module,import-error USE_IMPORTLIB = True else: import imp USE_IMPORTLIB = False try: from collections.abc import MutableMapping except ImportError: from collections import MutableMapping try: import pkg_resources HAS_PKG_RESOURCES = True except ImportError: HAS_PKG_RESOURCES = False log = logging.getLogger(__name__) SALT_BASE_PATH = os.path.abspath(salt.syspaths.INSTALL_DIR) LOADED_BASE_NAME = 'salt.loaded' if USE_IMPORTLIB: # pylint: disable=no-member MODULE_KIND_SOURCE = 1 MODULE_KIND_COMPILED = 2 MODULE_KIND_EXTENSION = 3 MODULE_KIND_PKG_DIRECTORY = 5 SUFFIXES = [] for suffix in importlib.machinery.EXTENSION_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_EXTENSION)) for suffix in importlib.machinery.SOURCE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_SOURCE)) for suffix in importlib.machinery.BYTECODE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_COMPILED)) MODULE_KIND_MAP = { MODULE_KIND_SOURCE: importlib.machinery.SourceFileLoader, MODULE_KIND_COMPILED: importlib.machinery.SourcelessFileLoader, MODULE_KIND_EXTENSION: importlib.machinery.ExtensionFileLoader } # pylint: enable=no-member else: SUFFIXES = imp.get_suffixes() PY3_PRE_EXT = \ re.compile(r'\.cpython-{0}{1}(\.opt-[1-9])?'.format(*sys.version_info[:2])) # Because on the cloud drivers we do `from salt.cloud.libcloudfuncs import *` # which simplifies code readability, it adds some unsupported functions into # the driver's module scope. # We list un-supported functions here. These will be removed from the loaded. # TODO: remove the need for this cross-module code. Maybe use NotImplemented LIBCLOUD_FUNCS_NOT_SUPPORTED = ( 'parallels.avail_sizes', 'parallels.avail_locations', 'proxmox.avail_sizes', ) # Will be set to pyximport module at runtime if cython is enabled in config. pyximport = None def static_loader( opts, ext_type, tag, pack=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, filter_name=None, ): funcs = LazyLoader( _module_dirs( opts, ext_type, tag, int_type, ext_dirs, ext_type_dirs, base_path, ), opts, tag=tag, pack=pack, ) ret = {} funcs._load_all() if filter_name: funcs = FilterDictWrapper(funcs, filter_name) for key in funcs: ret[key] = funcs[key] return ret def _format_entrypoint_target(ep): ''' Makes a string describing the target of an EntryPoint object. Base strongly on EntryPoint.__str__(). ''' s = ep.module_name if ep.attrs: s += ':' + '.'.join(ep.attrs) return s def _module_dirs( opts, ext_type, tag=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, ): if tag is None: tag = ext_type sys_types = os.path.join(base_path or SALT_BASE_PATH, int_type or ext_type) ext_types = os.path.join(opts['extension_modules'], ext_type) ext_type_types = [] if ext_dirs: if ext_type_dirs is None: ext_type_dirs = '{0}_dirs'.format(tag) if ext_type_dirs in opts: ext_type_types.extend(opts[ext_type_dirs]) if HAS_PKG_RESOURCES and ext_type_dirs: for entry_point in pkg_resources.iter_entry_points('salt.loader', ext_type_dirs): try: loaded_entry_point = entry_point.load() for path in loaded_entry_point(): ext_type_types.append(path) except Exception as exc: log.error("Error getting module directories from %s: %s", _format_entrypoint_target(entry_point), exc) log.debug("Full backtrace for module directories error", exc_info=True) cli_module_dirs = [] # The dirs can be any module dir, or a in-tree _{ext_type} dir for _dir in opts.get('module_dirs', []): # Prepend to the list to match cli argument ordering maybe_dir = os.path.join(_dir, ext_type) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) continue maybe_dir = os.path.join(_dir, '_{0}'.format(ext_type)) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) return cli_module_dirs + ext_type_types + [ext_types, sys_types] def minion_mods( opts, context=None, utils=None, whitelist=None, initial_load=False, loaded_base_name=None, notify=False, static_modules=None, proxy=None): ''' Load execution modules Returns a dictionary of execution modules appropriate for the current system by evaluating the __virtual__() function in each module. :param dict opts: The Salt options dictionary :param dict context: A Salt context that should be made present inside generated modules in __context__ :param dict utils: Utility functions which should be made available to Salt modules in __utils__. See `utils_dirs` in salt.config for additional information about configuration. :param list whitelist: A list of modules which should be whitelisted. :param bool initial_load: Deprecated flag! Unused. :param str loaded_base_name: A string marker for the loaded base name. :param bool notify: Flag indicating that an event should be fired upon completion of module loading. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) __opts__['grains'] = __grains__ __utils__ = salt.loader.utils(__opts__) __salt__ = salt.loader.minion_mods(__opts__, utils=__utils__) __salt__['test.ping']() ''' # TODO Publish documentation for module whitelisting if not whitelist: whitelist = opts.get('whitelist_modules', None) ret = LazyLoader( _module_dirs(opts, 'modules', 'module'), opts, tag='module', pack={'__context__': context, '__utils__': utils, '__proxy__': proxy}, whitelist=whitelist, loaded_base_name=loaded_base_name, static_modules=static_modules, ) ret.pack['__salt__'] = ret # Load any provider overrides from the configuration file providers option # Note: Providers can be pkg, service, user or group - not to be confused # with cloud providers. providers = opts.get('providers', False) if providers and isinstance(providers, dict): for mod in providers: # sometimes providers opts is not to diverge modules but # for other configuration try: funcs = raw_mod(opts, providers[mod], ret) except TypeError: break else: if funcs: for func in funcs: f_key = '{0}{1}'.format(mod, func[func.rindex('.'):]) ret[f_key] = funcs[func] if notify: evt = salt.utils.event.get_event('minion', opts=opts, listen=False) evt.fire_event({'complete': True}, tag=salt.defaults.events.MINION_MOD_COMPLETE) return ret def raw_mod(opts, name, functions, mod='modules'): ''' Returns a single module loaded raw and bypassing the __virtual__ function .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') testmod = salt.loader.raw_mod(__opts__, 'test', None) testmod['test.ping']() ''' loader = LazyLoader( _module_dirs(opts, mod, 'module'), opts, tag='rawmodule', virtual_enable=False, pack={'__salt__': functions}, ) # if we don't have the module, return an empty dict if name not in loader.file_mapping: return {} loader._load_module(name) # load a single module (the one passed in) return dict(loader._dict) # return a copy of *just* the funcs for `name` def metaproxy(opts): ''' Return functions used in the meta proxy ''' return LazyLoader( _module_dirs(opts, 'metaproxy'), opts, tag='metaproxy' ) def matchers(opts): ''' Return the matcher services plugins ''' return LazyLoader( _module_dirs(opts, 'matchers'), opts, tag='matchers' ) def engines(opts, functions, runners, utils, proxy=None): ''' Return the master services plugins ''' pack = {'__salt__': functions, '__runners__': runners, '__proxy__': proxy, '__utils__': utils} return LazyLoader( _module_dirs(opts, 'engines'), opts, tag='engines', pack=pack, ) def proxy(opts, functions=None, returners=None, whitelist=None, utils=None): ''' Returns the proxy module for this salt-proxy-minion ''' ret = LazyLoader( _module_dirs(opts, 'proxy'), opts, tag='proxy', pack={'__salt__': functions, '__ret__': returners, '__utils__': utils}, ) ret.pack['__proxy__'] = ret return ret def returners(opts, functions, whitelist=None, context=None, proxy=None): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'returners', 'returner'), opts, tag='returner', whitelist=whitelist, pack={'__salt__': functions, '__context__': context, '__proxy__': proxy or {}}, ) def utils(opts, whitelist=None, context=None, proxy=proxy): ''' Returns the utility modules ''' return LazyLoader( _module_dirs(opts, 'utils', ext_type_dirs='utils_dirs'), opts, tag='utils', whitelist=whitelist, pack={'__context__': context, '__proxy__': proxy or {}}, ) def pillars(opts, functions, context=None): ''' Returns the pillars modules ''' ret = LazyLoader(_module_dirs(opts, 'pillar'), opts, tag='pillar', pack={'__salt__': functions, '__context__': context, '__utils__': utils(opts)}) ret.pack['__ext_pillar__'] = ret return FilterDictWrapper(ret, '.ext_pillar') def tops(opts): ''' Returns the tops modules ''' if 'master_tops' not in opts: return {} whitelist = list(opts['master_tops'].keys()) ret = LazyLoader( _module_dirs(opts, 'tops', 'top'), opts, tag='top', whitelist=whitelist, ) return FilterDictWrapper(ret, '.top') def wheels(opts, whitelist=None, context=None): ''' Returns the wheels modules ''' if context is None: context = {} return LazyLoader( _module_dirs(opts, 'wheel'), opts, tag='wheel', whitelist=whitelist, pack={'__context__': context}, ) def outputters(opts): ''' Returns the outputters modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only outputters present in the keyspace ''' ret = LazyLoader( _module_dirs(opts, 'output', ext_type_dirs='outputter_dirs'), opts, tag='output', ) wrapped_ret = FilterDictWrapper(ret, '.output') # TODO: this name seems terrible... __salt__ should always be execution mods ret.pack['__salt__'] = wrapped_ret return wrapped_ret def serializers(opts): ''' Returns the serializers modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only serializers present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'serializers'), opts, tag='serializers', ) def eauth_tokens(opts): ''' Returns the tokens modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only token backends present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'tokens'), opts, tag='tokens', ) def auth(opts, whitelist=None): ''' Returns the auth modules :param dict opts: The Salt options dictionary :returns: LazyLoader ''' return LazyLoader( _module_dirs(opts, 'auth'), opts, tag='auth', whitelist=whitelist, pack={'__salt__': minion_mods(opts)}, ) def fileserver(opts, backends): ''' Returns the file server modules ''' return LazyLoader(_module_dirs(opts, 'fileserver'), opts, tag='fileserver', whitelist=backends, pack={'__utils__': utils(opts)}) def roster(opts, runner=None, utils=None, whitelist=None): ''' Returns the roster modules ''' return LazyLoader( _module_dirs(opts, 'roster'), opts, tag='roster', whitelist=whitelist, pack={ '__runner__': runner, '__utils__': utils, }, ) def thorium(opts, functions, runners): ''' Load the thorium runtime modules ''' pack = {'__salt__': functions, '__runner__': runners, '__context__': {}} ret = LazyLoader(_module_dirs(opts, 'thorium'), opts, tag='thorium', pack=pack) ret.pack['__thorium__'] = ret return ret def states(opts, functions, utils, serializers, whitelist=None, proxy=None, context=None): ''' Returns the state modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') statemods = salt.loader.states(__opts__, None, None) ''' if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'states'), opts, tag='states', pack={'__salt__': functions, '__proxy__': proxy or {}}, whitelist=whitelist, ) ret.pack['__states__'] = ret ret.pack['__utils__'] = utils ret.pack['__serializers__'] = serializers ret.pack['__context__'] = context return ret def beacons(opts, functions, context=None, proxy=None): ''' Load the beacon modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. ''' return LazyLoader( _module_dirs(opts, 'beacons'), opts, tag='beacons', pack={'__context__': context, '__salt__': functions, '__proxy__': proxy or {}}, virtual_funcs=[], ) def log_handlers(opts): ''' Returns the custom logging handler modules :param dict opts: The Salt options dictionary ''' ret = LazyLoader( _module_dirs( opts, 'log_handlers', int_type='handlers', base_path=os.path.join(SALT_BASE_PATH, 'log'), ), opts, tag='log_handlers', ) return FilterDictWrapper(ret, '.setup_handlers') def ssh_wrapper(opts, functions=None, context=None): ''' Returns the custom logging handler modules ''' return LazyLoader( _module_dirs( opts, 'wrapper', base_path=os.path.join(SALT_BASE_PATH, os.path.join('client', 'ssh')), ), opts, tag='wrapper', pack={ '__salt__': functions, '__grains__': opts.get('grains', {}), '__pillar__': opts.get('pillar', {}), '__context__': context, }, ) def grain_funcs(opts, proxy=None): ''' Returns the grain functions .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') grainfuncs = salt.loader.grain_funcs(__opts__) ''' ret = LazyLoader( _module_dirs( opts, 'grains', 'grain', ext_type_dirs='grains_dirs', ), opts, tag='grains', ) ret.pack['__utils__'] = utils(opts, proxy=proxy) return ret def _load_cached_grains(opts, cfn): ''' Returns the grains cached in cfn, or None if the cache is too old or is corrupted. ''' if not os.path.isfile(cfn): log.debug('Grains cache file does not exist.') return None grains_cache_age = int(time.time() - os.path.getmtime(cfn)) if grains_cache_age > opts.get('grains_cache_expiration', 300): log.debug( 'Grains cache last modified %s seconds ago and cache ' 'expiration is set to %s. Grains cache expired. ' 'Refreshing.', grains_cache_age, opts.get('grains_cache_expiration', 300) ) return None if opts.get('refresh_grains_cache', False): log.debug('refresh_grains_cache requested, Refreshing.') return None log.debug('Retrieving grains from cache') try: serial = salt.payload.Serial(opts) with salt.utils.files.fopen(cfn, 'rb') as fp_: cached_grains = salt.utils.data.decode(serial.load(fp_), preserve_tuples=True) if not cached_grains: log.debug('Cached grains are empty, cache might be corrupted. Refreshing.') return None return cached_grains except (IOError, OSError): return None def grains(opts, force_refresh=False, proxy=None): ''' Return the functions for the dynamic grains and the values for the static grains. Since grains are computed early in the startup process, grains functions do not have __salt__ or __proxy__ available. At proxy-minion startup, this function is called with the proxymodule LazyLoader object so grains functions can communicate with their controlled device. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) print __grains__['id'] ''' # Need to re-import salt.config, somehow it got lost when a minion is starting import salt.config # if we have no grains, lets try loading from disk (TODO: move to decorator?) cfn = os.path.join( opts['cachedir'], 'grains.cache.p' ) if not force_refresh and opts.get('grains_cache', False): cached_grains = _load_cached_grains(opts, cfn) if cached_grains: return cached_grains else: log.debug('Grains refresh requested. Refreshing grains.') if opts.get('skip_grains', False): return {} grains_deep_merge = opts.get('grains_deep_merge', False) is True if 'conf_file' in opts: pre_opts = {} pre_opts.update(salt.config.load_config( opts['conf_file'], 'SALT_MINION_CONFIG', salt.config.DEFAULT_MINION_OPTS['conf_file'] )) default_include = pre_opts.get( 'default_include', opts['default_include'] ) include = pre_opts.get('include', []) pre_opts.update(salt.config.include_config( default_include, opts['conf_file'], verbose=False )) pre_opts.update(salt.config.include_config( include, opts['conf_file'], verbose=True )) if 'grains' in pre_opts: opts['grains'] = pre_opts['grains'] else: opts['grains'] = {} else: opts['grains'] = {} grains_data = {} blist = opts.get('grains_blacklist', []) funcs = grain_funcs(opts, proxy=proxy) if force_refresh: # if we refresh, lets reload grain modules funcs.clear() # Run core grains for key in funcs: if not key.startswith('core.'): continue log.trace('Loading %s grain', key) ret = funcs[key]() if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) # Run the rest of the grains for key in funcs: if key.startswith('core.') or key == '_errors': continue try: # Grains are loaded too early to take advantage of the injected # __proxy__ variable. Pass an instance of that LazyLoader # here instead to grains functions if the grains functions take # one parameter. Then the grains can have access to the # proxymodule for retrieving information from the connected # device. log.trace('Loading %s grain', key) parameters = salt.utils.args.get_function_argspec(funcs[key]).args kwargs = {} if 'proxy' in parameters: kwargs['proxy'] = proxy if 'grains' in parameters: kwargs['grains'] = grains_data ret = funcs[key](**kwargs) except Exception: if salt.utils.platform.is_proxy(): log.info('The following CRITICAL message may not be an error; the proxy may not be completely established yet.') log.critical( 'Failed to load grains defined in grain file %s in ' 'function %s, error:\n', key, funcs[key], exc_info=True ) continue if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) if opts.get('proxy_merge_grains_in_module', True) and proxy: try: proxytype = proxy.opts['proxy']['proxytype'] if proxytype + '.grains' in proxy: if proxytype + '.initialized' in proxy and proxy[proxytype + '.initialized'](): try: proxytype = proxy.opts['proxy']['proxytype'] ret = proxy[proxytype + '.grains']() if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) except Exception: log.critical('Failed to run proxy\'s grains function!', exc_info=True ) except KeyError: pass grains_data.update(opts['grains']) # Write cache if enabled if opts.get('grains_cache', False): with salt.utils.files.set_umask(0o077): try: if salt.utils.platform.is_windows(): # Late import import salt.modules.cmdmod # Make sure cache file isn't read-only salt.modules.cmdmod._run_quiet('attrib -R "{0}"'.format(cfn)) with salt.utils.files.fopen(cfn, 'w+b') as fp_: try: serial = salt.payload.Serial(opts) serial.dump(grains_data, fp_) except TypeError as e: log.error('Failed to serialize grains cache: %s', e) raise # re-throw for cleanup except Exception as e: log.error('Unable to write to grains cache file %s: %s', cfn, e) # Based on the original exception, the file may or may not have been # created. If it was, we will remove it now, as the exception means # the serialized data is not to be trusted, no matter what the # exception is. if os.path.isfile(cfn): os.unlink(cfn) if grains_deep_merge: salt.utils.dictupdate.update(grains_data, opts['grains']) else: grains_data.update(opts['grains']) return salt.utils.data.decode(grains_data, preserve_tuples=True) # TODO: get rid of? Does anyone use this? You should use raw() instead def call(fun, **kwargs): ''' Directly call a function inside a loader directory ''' args = kwargs.get('args', []) dirs = kwargs.get('dirs', []) funcs = LazyLoader( [os.path.join(SALT_BASE_PATH, 'modules')] + dirs, None, tag='modules', virtual_enable=False, ) return funcs[fun](*args) def runner(opts, utils=None, context=None, whitelist=None): ''' Directly call a function inside a loader directory ''' if utils is None: utils = {} if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'runners', 'runner', ext_type_dirs='runner_dirs'), opts, tag='runners', pack={'__utils__': utils, '__context__': context}, whitelist=whitelist, ) # TODO: change from __salt__ to something else, we overload __salt__ too much ret.pack['__salt__'] = ret return ret def queues(opts): ''' Directly call a function inside a loader directory ''' return LazyLoader( _module_dirs(opts, 'queues', 'queue', ext_type_dirs='queue_dirs'), opts, tag='queues', ) def sdb(opts, functions=None, whitelist=None, utils=None): ''' Make a very small database call ''' if utils is None: utils = {} return LazyLoader( _module_dirs(opts, 'sdb'), opts, tag='sdb', pack={ '__sdb__': functions, '__opts__': opts, '__utils__': utils, '__salt__': minion_mods(opts, utils), }, whitelist=whitelist, ) def pkgdb(opts): ''' Return modules for SPM's package database .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgdb', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgdb' ) def pkgfiles(opts): ''' Return modules for SPM's file handling .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgfiles', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgfiles' ) def clouds(opts): ''' Return the cloud functions ''' # Let's bring __active_provider_name__, defaulting to None, to all cloud # drivers. This will get temporarily updated/overridden with a context # manager when needed. functions = LazyLoader( _module_dirs(opts, 'clouds', 'cloud', base_path=os.path.join(SALT_BASE_PATH, 'cloud'), int_type='clouds'), opts, tag='clouds', pack={'__utils__': salt.loader.utils(opts), '__active_provider_name__': None}, ) for funcname in LIBCLOUD_FUNCS_NOT_SUPPORTED: log.trace( '\'%s\' has been marked as not supported. Removing from the ' 'list of supported cloud functions', funcname ) functions.pop(funcname, None) return functions def netapi(opts): ''' Return the network api functions ''' return LazyLoader( _module_dirs(opts, 'netapi'), opts, tag='netapi', ) def executors(opts, functions=None, context=None, proxy=None): ''' Returns the executor modules ''' executors = LazyLoader( _module_dirs(opts, 'executors', 'executor'), opts, tag='executor', pack={'__salt__': functions, '__context__': context or {}, '__proxy__': proxy or {}}, ) executors.pack['__executors__'] = executors return executors def cache(opts, serial): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'cache', 'cache'), opts, tag='cache', pack={'__opts__': opts, '__context__': {'serial': serial}}, ) def _generate_module(name): if name in sys.modules: return code = "'''Salt loaded {0} parent module'''".format(name.split('.')[-1]) # ModuleType can't accept a unicode type on PY2 module = types.ModuleType(str(name)) # future lint: disable=blacklisted-function exec(code, module.__dict__) sys.modules[name] = module def _mod_type(module_path): if module_path.startswith(SALT_BASE_PATH): return 'int' return 'ext' def _inject_into_mod(mod, name, value, force_lock=False): ''' Inject a variable into a module. This is used to inject "globals" like ``__salt__``, ``__pillar``, or ``grains``. Instead of injecting the value directly, a ``ThreadLocalProxy`` is created. If such a proxy is already present under the specified name, it is updated with the new value. This update only affects the current thread, so that the same name can refer to different values depending on the thread of execution. This is important for data that is not truly global. For example, pillar data might be dynamically overriden through function parameters and thus the actual values available in pillar might depend on the thread that is calling a module. mod: module object into which the value is going to be injected. name: name of the variable that is injected into the module. value: value that is injected into the variable. The value is not injected directly, but instead set as the new reference of the proxy that has been created for the variable. force_lock: whether the lock should be acquired before checking whether a proxy object for the specified name has already been injected into the module. If ``False`` (the default), this function checks for the module's variable without acquiring the lock and only acquires the lock if a new proxy has to be created and injected. ''' old_value = getattr(mod, name, None) # We use a double-checked locking scheme in order to avoid taking the lock # when a proxy object has already been injected. # In most programming languages, double-checked locking is considered # unsafe when used without explicit memory barriers because one might read # an uninitialized value. In CPython it is safe due to the global # interpreter lock (GIL). In Python implementations that do not have the # GIL, it could be unsafe, but at least Jython also guarantees that (for # Python objects) memory is not corrupted when writing and reading without # explicit synchronization # (http://www.jython.org/jythonbook/en/1.0/Concurrency.html). # Please note that in order to make this code safe in a runtime environment # that does not make this guarantees, it is not sufficient. The # ThreadLocalProxy must also be created with fallback_to_shared set to # False or a lock must be added to the ThreadLocalProxy. if force_lock: with _inject_into_mod.lock: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: setattr(mod, name, ThreadLocalProxy(value, True)) else: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: _inject_into_mod(mod, name, value, True) # Lock used when injecting globals. This is needed to avoid a race condition # when two threads try to load the same module concurrently. This must be # outside the loader because there might be more than one loader for the same # namespace. _inject_into_mod.lock = threading.RLock() # TODO: move somewhere else? class FilterDictWrapper(MutableMapping): ''' Create a dict which wraps another dict with a specific key suffix on get This is to replace "filter_load" ''' def __init__(self, d, suffix): self._dict = d self.suffix = suffix def __setitem__(self, key, val): self._dict[key] = val def __delitem__(self, key): del self._dict[key] def __getitem__(self, key): return self._dict[key + self.suffix] def __len__(self): return len(self._dict) def __iter__(self): for key in self._dict: if key.endswith(self.suffix): yield key.replace(self.suffix, '') class LazyLoader(salt.utils.lazy.LazyDict): ''' A pseduo-dictionary which has a set of keys which are the name of the module and function, delimited by a dot. When the value of the key is accessed, the function is then loaded from disk and into memory. .. note:: Iterating over keys will cause all modules to be loaded. :param list module_dirs: A list of directories on disk to search for modules :param dict opts: The salt options dictionary. :param str tag: The tag for the type of module to load :param func mod_type_check: A function which can be used to verify files :param dict pack: A dictionary of function to be packed into modules as they are loaded :param list whitelist: A list of modules to whitelist :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules. :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality. If not true, the module will not load. :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values are function references themselves which are loaded on-demand. # TODO: - move modules_max_memory into here - singletons (per tag) ''' mod_dict_class = salt.utils.odict.OrderedDict def __init__(self, module_dirs, opts=None, tag='module', loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, proxy=None, virtual_funcs=None, ): # pylint: disable=W0231 ''' In pack, if any of the values are None they will be replaced with an empty context-specific dict ''' self.inject_globals = {} self.pack = {} if pack is None else pack if opts is None: opts = {} threadsafety = not opts.get('multiprocessing') self.context_dict = salt.utils.context.ContextDict(threadsafe=threadsafety) self.opts = self.__prep_mod_opts(opts) self.module_dirs = module_dirs self.tag = tag self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME self.mod_type_check = mod_type_check or _mod_type if '__context__' not in self.pack: self.pack['__context__'] = None for k, v in six.iteritems(self.pack): if v is None: # if the value of a pack is None, lets make an empty dict value = self.context_dict.get(k, {}) if isinstance(value, ThreadLocalProxy): value = ThreadLocalProxy.unproxy(value) self.context_dict[k] = value self.pack[k] = salt.utils.context.NamespacedDictWrapper(self.context_dict, k) self.whitelist = whitelist self.virtual_enable = virtual_enable self.initial_load = True # names of modules that we don't have (errors, __virtual__, etc.) self.missing_modules = {} # mapping of name -> error self.loaded_modules = {} # mapping of module_name -> dict_of_functions self.loaded_files = set() # TODO: just remove them from file_mapping? self.static_modules = static_modules if static_modules else [] if virtual_funcs is None: virtual_funcs = [] self.virtual_funcs = virtual_funcs self.disabled = set( self.opts.get( 'disable_{0}{1}'.format( self.tag, '' if self.tag[-1] == 's' else 's' ), [] ) ) # A map of suffix to description for imp self.suffix_map = {} # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [''] for (suffix, mode, kind) in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) self._lock = threading.RLock() self._refresh_file_mapping() super(LazyLoader, self).__init__() # late init the lazy loader # create all of the import namespaces _generate_module('{0}.int'.format(self.loaded_base_name)) _generate_module('{0}.int.{1}'.format(self.loaded_base_name, tag)) _generate_module('{0}.ext'.format(self.loaded_base_name)) _generate_module('{0}.ext.{1}'.format(self.loaded_base_name, tag)) def __getitem__(self, item): ''' Override the __getitem__ in order to decorate the returned function if we need to last-minute inject globals ''' func = super(LazyLoader, self).__getitem__(item) if self.inject_globals: return global_injector_decorator(self.inject_globals)(func) else: return func def __getattr__(self, mod_name): ''' Allow for "direct" attribute access-- this allows jinja templates to access things like `salt.test.ping()` ''' if mod_name in ('__getstate__', '__setstate__'): return object.__getattribute__(self, mod_name) # if we have an attribute named that, lets return it. try: return object.__getattr__(self, mod_name) # pylint: disable=no-member except AttributeError: pass # otherwise we assume its jinja template access if mod_name not in self.loaded_modules and not self.loaded: for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and mod_name in self.loaded_modules: break if mod_name in self.loaded_modules: return self.loaded_modules[mod_name] else: raise AttributeError(mod_name) def missing_fun_string(self, function_name): ''' Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ''' mod_name = function_name.split('.')[0] if mod_name in self.loaded_modules: return '\'{0}\' is not available.'.format(function_name) else: try: reason = self.missing_modules[mod_name] except KeyError: return '\'{0}\' is not available.'.format(function_name) else: if reason is not None: return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason) else: return '\'{0}\' __virtual__ returned False'.format(mod_name) def _refresh_file_mapping(self): ''' refresh the mapping of the FS on disk ''' # map of suffix to description for imp if self.opts.get('cython_enable', True) is True: try: global pyximport pyximport = __import__('pyximport') # pylint: disable=import-error pyximport.install() # add to suffix_map so file_mapping will pick it up self.suffix_map['.pyx'] = tuple() except ImportError: log.info('Cython is enabled in the options but not present ' 'in the system path. Skipping Cython modules.') # Allow for zipimport of modules if self.opts.get('enable_zip_modules', True) is True: self.suffix_map['.zip'] = tuple() # allow for module dirs if USE_IMPORTLIB: self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY) else: self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY) # create mapping of filename (without suffix) to (path, suffix) # The files are added in order of priority, so order *must* be retained. self.file_mapping = salt.utils.odict.OrderedDict() opt_match = [] def _replace_pre_ext(obj): ''' Hack so we can get the optimization level that we replaced (if any) out of the re.sub call below. We use a list here because it is a persistent data structure that we will be able to access after re.sub is called. ''' opt_match.append(obj) return '' for mod_dir in self.module_dirs: try: # Make sure we have a sorted listdir in order to have # expectable override results files = sorted( x for x in os.listdir(mod_dir) if x != '__pycache__' ) except OSError: continue # Next mod_dir if six.PY3: try: pycache_files = [ os.path.join('__pycache__', x) for x in sorted(os.listdir(os.path.join(mod_dir, '__pycache__'))) ] except OSError: pass else: files.extend(pycache_files) for filename in files: try: dirname, basename = os.path.split(filename) if basename.startswith('_'): # skip private modules # log messages omitted for obviousness continue # Next filename f_noext, ext = os.path.splitext(basename) if six.PY3: f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext) try: opt_level = int( opt_match.pop().group(1).rsplit('-', 1)[-1] ) except (AttributeError, IndexError, ValueError): # No regex match or no optimization level matched opt_level = 0 try: opt_index = self.opts['optimization_order'].index(opt_level) except KeyError: log.trace( 'Disallowed optimization level %d for module ' 'name \'%s\', skipping. Add %d to the ' '\'optimization_order\' config option if you ' 'do not want to ignore this optimization ' 'level.', opt_level, f_noext, opt_level ) continue else: # Optimization level not reflected in filename on PY2 opt_index = 0 # make sure it is a suffix we support if ext not in self.suffix_map: continue # Next filename if f_noext in self.disabled: log.trace( 'Skipping %s, it is disabled by configuration', filename ) continue # Next filename fpath = os.path.join(mod_dir, filename) # if its a directory, lets allow us to load that if ext == '': # is there something __init__? subfiles = os.listdir(fpath) for suffix in self.suffix_order: if '' == suffix: continue # Next suffix (__init__ must have a suffix) init_file = '__init__{0}'.format(suffix) if init_file in subfiles: break else: continue # Next filename try: curr_ext = self.file_mapping[f_noext][1] curr_opt_index = self.file_mapping[f_noext][2] except KeyError: pass else: if '' in (curr_ext, ext) and curr_ext != ext: log.error( 'Module/package collision: \'%s\' and \'%s\'', fpath, self.file_mapping[f_noext][0] ) if six.PY3 and ext == '.pyc' and curr_ext == '.pyc': # Check the optimization level if opt_index >= curr_opt_index: # Module name match, but a higher-priority # optimization level was already matched, skipping. continue elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext): # Match found but a higher-priorty match already # exists, so skip this. continue if six.PY3 and not dirname and ext == '.pyc': # On Python 3, we should only load .pyc files from the # __pycache__ subdirectory (i.e. when dirname is not an # empty string). continue # Made it this far - add it self.file_mapping[f_noext] = (fpath, ext, opt_index) except OSError: continue for smod in self.static_modules: f_noext = smod.split('.')[-1] self.file_mapping[f_noext] = (smod, '.o', 0) def clear(self): ''' Clear the dict ''' with self._lock: super(LazyLoader, self).clear() # clear the lazy loader self.loaded_files = set() self.missing_modules = {} self.loaded_modules = {} # if we have been loaded before, lets clear the file mapping since # we obviously want a re-do if hasattr(self, 'opts'): self._refresh_file_mapping() self.initial_load = False def __prep_mod_opts(self, opts): ''' Strip out of the opts any logger instance ''' if '__grains__' not in self.pack: grains = opts.get('grains', {}) if isinstance(grains, ThreadLocalProxy): grains = ThreadLocalProxy.unproxy(grains) self.context_dict['grains'] = grains self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains') if '__pillar__' not in self.pack: pillar = opts.get('pillar', {}) if isinstance(pillar, ThreadLocalProxy): pillar = ThreadLocalProxy.unproxy(pillar) self.context_dict['pillar'] = pillar self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar') mod_opts = {} for key, val in list(opts.items()): if key == 'logger': continue mod_opts[key] = val return mod_opts def _iter_files(self, mod_name): ''' Iterate over all file_mapping files in order of closeness to mod_name ''' # do we have an exact match? if mod_name in self.file_mapping: yield mod_name # do we have a partial match? for k in self.file_mapping: if mod_name in k: yield k # anyone else? Bueller? for k in self.file_mapping: if mod_name not in k: yield k def _reload_submodules(self, mod): submodules = ( getattr(mod, sname) for sname in dir(mod) if isinstance(getattr(mod, sname), mod.__class__) ) # reload only custom "sub"modules for submodule in submodules: # it is a submodule if the name is in a namespace under mod if submodule.__name__.startswith(mod.__name__ + '.'): reload_module(submodule) self._reload_submodules(submodule) def _load_module(self, name): mod = None fpath, suffix = self.file_mapping[name][:2] self.loaded_files.add(name) fpath_dirname = os.path.dirname(fpath) try: sys.path.append(fpath_dirname) if suffix == '.pyx': mod = pyximport.load_module(name, fpath, tempfile.gettempdir()) elif suffix == '.o': top_mod = __import__(fpath, globals(), locals(), []) comps = fpath.split('.') if len(comps) < 2: mod = top_mod else: mod = top_mod for subname in comps[1:]: mod = getattr(mod, subname) elif suffix == '.zip': mod = zipimporter(fpath).load_module(name) else: desc = self.suffix_map[suffix] # if it is a directory, we don't open a file try: mod_namespace = '.'.join(( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name)) except TypeError: mod_namespace = '{0}.{1}.{2}.{3}'.format( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name) if suffix == '': if USE_IMPORTLIB: # pylint: disable=no-member # Package directory, look for __init__ loader_details = [ (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES), (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES), (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), ] file_finder = importlib.machinery.FileFinder( fpath_dirname, *loader_details ) spec = file_finder.find_spec(mod_namespace) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: mod = imp.load_module(mod_namespace, None, fpath, desc) # reload all submodules if necessary if not self.initial_load: self._reload_submodules(mod) else: if USE_IMPORTLIB: # pylint: disable=no-member loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath) spec = importlib.util.spec_from_file_location( mod_namespace, fpath, loader=loader ) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() #mod = importlib.util.module_from_spec(spec) #spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: with salt.utils.files.fopen(fpath, desc[1]) as fn_: mod = imp.load_module(mod_namespace, fn_, fpath, desc) except IOError: raise except ImportError as exc: if 'magic number' in six.text_type(exc): error_msg = 'Failed to import {0} {1}. Bad magic number. If migrating from Python2 to Python3, remove all .pyc files and try again.'.format(self.tag, name) log.warning(error_msg) self.missing_modules[name] = error_msg log.debug( 'Failed to import %s %s:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = exc return False except Exception as error: log.error( 'Failed to import %s %s, this is due most likely to a ' 'syntax error:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False except SystemExit as error: try: fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1] except Exception: pass else: tgt_fn = os.path.join('salt', 'utils', 'process.py') if fn_.endswith(tgt_fn) and '_handle_signals' in caller: # Race conditon, SIGTERM or SIGINT received while loader # was in process of loading a module. Call sys.exit to # ensure that the process is killed. sys.exit(salt.defaults.exitcodes.EX_OK) log.error( 'Failed to import %s %s as the module called exit()\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False finally: sys.path.remove(fpath_dirname) if hasattr(mod, '__opts__'): mod.__opts__.update(self.opts) else: mod.__opts__ = self.opts # pack whatever other globals we were asked to for p_name, p_value in six.iteritems(self.pack): _inject_into_mod(mod, p_name, p_value) module_name = mod.__name__.rsplit('.', 1)[-1] # Call a module's initialization method if it exists module_init = getattr(mod, '__init__', None) if inspect.isfunction(module_init): try: module_init(self.opts) except TypeError as e: log.error(e) except Exception: err_string = '__init__ failed' log.debug( 'Error loading %s.%s: %s', self.tag, module_name, err_string, exc_info=True ) self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False # if virtual modules are enabled, we need to look for the # __virtual__() function inside that module and run it. if self.virtual_enable: virtual_funcs_to_process = ['__virtual__'] + self.virtual_funcs for virtual_func in virtual_funcs_to_process: virtual_ret, module_name, virtual_err, virtual_aliases = \ self._process_virtual(mod, module_name, virtual_func) if virtual_err is not None: log.trace( 'Error loading %s.%s: %s', self.tag, module_name, virtual_err ) # if _process_virtual returned a non-True value then we are # supposed to not process this module if virtual_ret is not True and module_name not in self.missing_modules: # If a module has information about why it could not be loaded, record it self.missing_modules[module_name] = virtual_err self.missing_modules[name] = virtual_err return False else: virtual_aliases = () # If this is a proxy minion then MOST modules cannot work. Therefore, require that # any module that does work with salt-proxy-minion define __proxyenabled__ as a list # containing the names of the proxy types that the module supports. # # Render modules and state modules are OK though if 'proxy' in self.opts: if self.tag in ['grains', 'proxy']: if not hasattr(mod, '__proxyenabled__') or \ (self.opts['proxy']['proxytype'] not in mod.__proxyenabled__ and '*' not in mod.__proxyenabled__): err_string = 'not a proxy_minion enabled module' self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False if getattr(mod, '__load__', False) is not False: log.info( 'The functions from module \'%s\' are being loaded from the ' 'provided __load__ attribute', module_name ) # If we had another module by the same virtual name, we should put any # new functions under the existing dictionary. mod_names = [module_name] + list(virtual_aliases) mod_dict = dict(( (x, self.loaded_modules.get(x, self.mod_dict_class())) for x in mod_names )) for attr in getattr(mod, '__load__', dir(mod)): if attr.startswith('_') and attr != '__call__': # private functions are skipped, # except __call__ which is default entrance # for multi-function batch-like state syntax continue func = getattr(mod, attr) if not inspect.isfunction(func) and not isinstance(func, functools.partial): # Not a function!? Skip it!!! continue # Let's get the function name. # If the module has the __func_alias__ attribute, it must be a # dictionary mapping in the form of(key -> value): # <real-func-name> -> <desired-func-name> # # It default's of course to the found callable attribute name # if no alias is defined. funcname = getattr(mod, '__func_alias__', {}).get(attr, attr) for tgt_mod in mod_names: try: full_funcname = '.'.join((tgt_mod, funcname)) except TypeError: full_funcname = '{0}.{1}'.format(tgt_mod, funcname) # Save many references for lookups # Careful not to overwrite existing (higher priority) functions if full_funcname not in self._dict: self._dict[full_funcname] = func if funcname not in mod_dict[tgt_mod]: setattr(mod_dict[tgt_mod], funcname, func) mod_dict[tgt_mod][funcname] = func self._apply_outputter(func, mod) # enforce depends try: Depends.enforce_dependencies(self._dict, self.tag) except RuntimeError as exc: log.info( 'Depends.enforce_dependencies() failed for the following ' 'reason: %s', exc ) for tgt_mod in mod_names: self.loaded_modules[tgt_mod] = mod_dict[tgt_mod] return True def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise KeyError('The key \'{0}\' should contain a \'.\''.format(key)) mod_name, _ = key.split('.', 1) with self._lock: # It is possible that the key is in the dictionary after # acquiring the lock due to another thread loading it. if mod_name in self.missing_modules or key in self._dict: return True # if the modulename isn't in the whitelist, don't bother if self.whitelist and mod_name not in self.whitelist: log.error( 'Failed to load function %s because its module (%s) is ' 'not in the whitelist: %s', key, mod_name, self.whitelist ) raise KeyError(key) def _inner_load(mod_name): for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and key in self._dict: return True return False # try to load the module ret = None reloaded = False # re-scan up to once, IOErrors or a failed load cause re-scans of the # filesystem while True: try: ret = _inner_load(mod_name) if not reloaded and ret is not True: self._refresh_file_mapping() reloaded = True continue break except IOError: if not reloaded: self._refresh_file_mapping() reloaded = True continue return ret def _load_all(self): ''' Load all of them ''' with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True def reload_modules(self): with self._lock: self.loaded_files = set() self._load_all() def _apply_outputter(self, func, mod): ''' Apply the __outputter__ variable to the functions ''' if hasattr(mod, '__outputter__'): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__] def _process_virtual(self, mod, module_name, virtual_func='__virtual__'): ''' Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1] ''' # The __virtual__ function will return either a True or False value. # If it returns a True value it can also set a module level attribute # named __virtualname__ with the name that the module should be # referred to as. # # This allows us to have things like the pkg module working on all # platforms under the name 'pkg'. It also allows for modules like # augeas_cfg to be referred to as 'augeas', which would otherwise have # namespace collisions. And finally it allows modules to return False # if they are not intended to run on the given platform or are missing # dependencies. virtual_aliases = getattr(mod, '__virtual_aliases__', tuple()) try: error_reason = None if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__): try: start = time.time() virtual = getattr(mod, virtual_func)() if isinstance(virtual, tuple): error_reason = virtual[1] virtual = virtual[0] if self.opts.get('virtual_timer', False): end = time.time() - start msg = 'Virtual function took {0} seconds for {1}'.format( end, module_name) log.warning(msg) except Exception as exc: error_reason = ( 'Exception raised when processing __virtual__ function' ' for {0}. Module will not be loaded: {1}'.format( mod.__name__, exc)) log.error(error_reason, exc_info_on_loglevel=logging.DEBUG) virtual = None # Get the module's virtual name virtualname = getattr(mod, '__virtualname__', virtual) if not virtual: # if __virtual__() evaluates to False then the module # wasn't meant for this platform or it's not supposed to # load for some other reason. # Some modules might accidentally return None and are # improperly loaded if virtual is None: log.warning( '%s.__virtual__() is wrongly returning `None`. ' 'It should either return `True`, `False` or a new ' 'name. If you\'re the developer of the module ' '\'%s\', please fix this.', mod.__name__, module_name ) return (False, module_name, error_reason, virtual_aliases) # At this point, __virtual__ did not return a # boolean value, let's check for deprecated usage # or module renames if virtual is not True and module_name != virtual: # The module is renaming itself. Updating the module name # with the new name log.trace('Loaded %s as virtual %s', module_name, virtual) if virtualname != virtual: # The __virtualname__ attribute does not match what's # being returned by the __virtual__() function. This # should be considered an error. log.error( 'The module \'%s\' is showing some bad usage. Its ' '__virtualname__ attribute is set to \'%s\' yet the ' '__virtual__() function is returning \'%s\'. These ' 'values should match!', mod.__name__, virtualname, virtual ) module_name = virtualname # If the __virtual__ function returns True and __virtualname__ # is set then use it elif virtual is True and virtualname != module_name: if virtualname is not True: module_name = virtualname except KeyError: # Key errors come out of the virtual function when passing # in incomplete grains sets, these can be safely ignored # and logged to debug, still, it includes the traceback to # help debugging. log.debug('KeyError when loading %s', module_name, exc_info=True) except Exception: # If the module throws an exception during __virtual__() # then log the information and continue to the next. log.error( 'Failed to read the virtual function for %s: %s', self.tag, module_name, exc_info=True ) return (False, module_name, error_reason, virtual_aliases) return (True, module_name, None, virtual_aliases) def global_injector_decorator(inject_globals): ''' Decorator used by the LazyLoader to inject globals into a function at execute time. globals Dictionary with global variables to inject ''' def inner_decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): with salt.utils.context.func_globals_inject(f, **inject_globals): return f(*args, **kwargs) return wrapper return inner_decorator
saltstack/salt
salt/loader.py
grain_funcs
python
def grain_funcs(opts, proxy=None): ''' Returns the grain functions .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') grainfuncs = salt.loader.grain_funcs(__opts__) ''' ret = LazyLoader( _module_dirs( opts, 'grains', 'grain', ext_type_dirs='grains_dirs', ), opts, tag='grains', ) ret.pack['__utils__'] = utils(opts, proxy=proxy) return ret
Returns the grain functions .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') grainfuncs = salt.loader.grain_funcs(__opts__)
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L669-L692
null
# -*- coding: utf-8 -*- ''' The Salt loader is the core to Salt's plugin system, the loader scans directories for python loadable code and organizes the code into the plugin interfaces used by Salt. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import sys import time import logging import inspect import tempfile import threading import functools import threading import traceback import types from zipimport import zipimporter # Import salt libs import salt.config import salt.defaults.events import salt.defaults.exitcodes import salt.syspaths import salt.utils.args import salt.utils.context import salt.utils.data import salt.utils.dictupdate import salt.utils.event import salt.utils.files import salt.utils.lazy import salt.utils.odict import salt.utils.platform import salt.utils.versions import salt.utils.stringutils from salt.exceptions import LoaderError from salt.template import check_render_pipe_str from salt.utils.decorators import Depends from salt.utils.thread_local_proxy import ThreadLocalProxy # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import reload_module if sys.version_info[:2] >= (3, 5): import importlib.machinery # pylint: disable=no-name-in-module,import-error import importlib.util # pylint: disable=no-name-in-module,import-error USE_IMPORTLIB = True else: import imp USE_IMPORTLIB = False try: from collections.abc import MutableMapping except ImportError: from collections import MutableMapping try: import pkg_resources HAS_PKG_RESOURCES = True except ImportError: HAS_PKG_RESOURCES = False log = logging.getLogger(__name__) SALT_BASE_PATH = os.path.abspath(salt.syspaths.INSTALL_DIR) LOADED_BASE_NAME = 'salt.loaded' if USE_IMPORTLIB: # pylint: disable=no-member MODULE_KIND_SOURCE = 1 MODULE_KIND_COMPILED = 2 MODULE_KIND_EXTENSION = 3 MODULE_KIND_PKG_DIRECTORY = 5 SUFFIXES = [] for suffix in importlib.machinery.EXTENSION_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_EXTENSION)) for suffix in importlib.machinery.SOURCE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_SOURCE)) for suffix in importlib.machinery.BYTECODE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_COMPILED)) MODULE_KIND_MAP = { MODULE_KIND_SOURCE: importlib.machinery.SourceFileLoader, MODULE_KIND_COMPILED: importlib.machinery.SourcelessFileLoader, MODULE_KIND_EXTENSION: importlib.machinery.ExtensionFileLoader } # pylint: enable=no-member else: SUFFIXES = imp.get_suffixes() PY3_PRE_EXT = \ re.compile(r'\.cpython-{0}{1}(\.opt-[1-9])?'.format(*sys.version_info[:2])) # Because on the cloud drivers we do `from salt.cloud.libcloudfuncs import *` # which simplifies code readability, it adds some unsupported functions into # the driver's module scope. # We list un-supported functions here. These will be removed from the loaded. # TODO: remove the need for this cross-module code. Maybe use NotImplemented LIBCLOUD_FUNCS_NOT_SUPPORTED = ( 'parallels.avail_sizes', 'parallels.avail_locations', 'proxmox.avail_sizes', ) # Will be set to pyximport module at runtime if cython is enabled in config. pyximport = None def static_loader( opts, ext_type, tag, pack=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, filter_name=None, ): funcs = LazyLoader( _module_dirs( opts, ext_type, tag, int_type, ext_dirs, ext_type_dirs, base_path, ), opts, tag=tag, pack=pack, ) ret = {} funcs._load_all() if filter_name: funcs = FilterDictWrapper(funcs, filter_name) for key in funcs: ret[key] = funcs[key] return ret def _format_entrypoint_target(ep): ''' Makes a string describing the target of an EntryPoint object. Base strongly on EntryPoint.__str__(). ''' s = ep.module_name if ep.attrs: s += ':' + '.'.join(ep.attrs) return s def _module_dirs( opts, ext_type, tag=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, ): if tag is None: tag = ext_type sys_types = os.path.join(base_path or SALT_BASE_PATH, int_type or ext_type) ext_types = os.path.join(opts['extension_modules'], ext_type) ext_type_types = [] if ext_dirs: if ext_type_dirs is None: ext_type_dirs = '{0}_dirs'.format(tag) if ext_type_dirs in opts: ext_type_types.extend(opts[ext_type_dirs]) if HAS_PKG_RESOURCES and ext_type_dirs: for entry_point in pkg_resources.iter_entry_points('salt.loader', ext_type_dirs): try: loaded_entry_point = entry_point.load() for path in loaded_entry_point(): ext_type_types.append(path) except Exception as exc: log.error("Error getting module directories from %s: %s", _format_entrypoint_target(entry_point), exc) log.debug("Full backtrace for module directories error", exc_info=True) cli_module_dirs = [] # The dirs can be any module dir, or a in-tree _{ext_type} dir for _dir in opts.get('module_dirs', []): # Prepend to the list to match cli argument ordering maybe_dir = os.path.join(_dir, ext_type) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) continue maybe_dir = os.path.join(_dir, '_{0}'.format(ext_type)) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) return cli_module_dirs + ext_type_types + [ext_types, sys_types] def minion_mods( opts, context=None, utils=None, whitelist=None, initial_load=False, loaded_base_name=None, notify=False, static_modules=None, proxy=None): ''' Load execution modules Returns a dictionary of execution modules appropriate for the current system by evaluating the __virtual__() function in each module. :param dict opts: The Salt options dictionary :param dict context: A Salt context that should be made present inside generated modules in __context__ :param dict utils: Utility functions which should be made available to Salt modules in __utils__. See `utils_dirs` in salt.config for additional information about configuration. :param list whitelist: A list of modules which should be whitelisted. :param bool initial_load: Deprecated flag! Unused. :param str loaded_base_name: A string marker for the loaded base name. :param bool notify: Flag indicating that an event should be fired upon completion of module loading. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) __opts__['grains'] = __grains__ __utils__ = salt.loader.utils(__opts__) __salt__ = salt.loader.minion_mods(__opts__, utils=__utils__) __salt__['test.ping']() ''' # TODO Publish documentation for module whitelisting if not whitelist: whitelist = opts.get('whitelist_modules', None) ret = LazyLoader( _module_dirs(opts, 'modules', 'module'), opts, tag='module', pack={'__context__': context, '__utils__': utils, '__proxy__': proxy}, whitelist=whitelist, loaded_base_name=loaded_base_name, static_modules=static_modules, ) ret.pack['__salt__'] = ret # Load any provider overrides from the configuration file providers option # Note: Providers can be pkg, service, user or group - not to be confused # with cloud providers. providers = opts.get('providers', False) if providers and isinstance(providers, dict): for mod in providers: # sometimes providers opts is not to diverge modules but # for other configuration try: funcs = raw_mod(opts, providers[mod], ret) except TypeError: break else: if funcs: for func in funcs: f_key = '{0}{1}'.format(mod, func[func.rindex('.'):]) ret[f_key] = funcs[func] if notify: evt = salt.utils.event.get_event('minion', opts=opts, listen=False) evt.fire_event({'complete': True}, tag=salt.defaults.events.MINION_MOD_COMPLETE) return ret def raw_mod(opts, name, functions, mod='modules'): ''' Returns a single module loaded raw and bypassing the __virtual__ function .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') testmod = salt.loader.raw_mod(__opts__, 'test', None) testmod['test.ping']() ''' loader = LazyLoader( _module_dirs(opts, mod, 'module'), opts, tag='rawmodule', virtual_enable=False, pack={'__salt__': functions}, ) # if we don't have the module, return an empty dict if name not in loader.file_mapping: return {} loader._load_module(name) # load a single module (the one passed in) return dict(loader._dict) # return a copy of *just* the funcs for `name` def metaproxy(opts): ''' Return functions used in the meta proxy ''' return LazyLoader( _module_dirs(opts, 'metaproxy'), opts, tag='metaproxy' ) def matchers(opts): ''' Return the matcher services plugins ''' return LazyLoader( _module_dirs(opts, 'matchers'), opts, tag='matchers' ) def engines(opts, functions, runners, utils, proxy=None): ''' Return the master services plugins ''' pack = {'__salt__': functions, '__runners__': runners, '__proxy__': proxy, '__utils__': utils} return LazyLoader( _module_dirs(opts, 'engines'), opts, tag='engines', pack=pack, ) def proxy(opts, functions=None, returners=None, whitelist=None, utils=None): ''' Returns the proxy module for this salt-proxy-minion ''' ret = LazyLoader( _module_dirs(opts, 'proxy'), opts, tag='proxy', pack={'__salt__': functions, '__ret__': returners, '__utils__': utils}, ) ret.pack['__proxy__'] = ret return ret def returners(opts, functions, whitelist=None, context=None, proxy=None): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'returners', 'returner'), opts, tag='returner', whitelist=whitelist, pack={'__salt__': functions, '__context__': context, '__proxy__': proxy or {}}, ) def utils(opts, whitelist=None, context=None, proxy=proxy): ''' Returns the utility modules ''' return LazyLoader( _module_dirs(opts, 'utils', ext_type_dirs='utils_dirs'), opts, tag='utils', whitelist=whitelist, pack={'__context__': context, '__proxy__': proxy or {}}, ) def pillars(opts, functions, context=None): ''' Returns the pillars modules ''' ret = LazyLoader(_module_dirs(opts, 'pillar'), opts, tag='pillar', pack={'__salt__': functions, '__context__': context, '__utils__': utils(opts)}) ret.pack['__ext_pillar__'] = ret return FilterDictWrapper(ret, '.ext_pillar') def tops(opts): ''' Returns the tops modules ''' if 'master_tops' not in opts: return {} whitelist = list(opts['master_tops'].keys()) ret = LazyLoader( _module_dirs(opts, 'tops', 'top'), opts, tag='top', whitelist=whitelist, ) return FilterDictWrapper(ret, '.top') def wheels(opts, whitelist=None, context=None): ''' Returns the wheels modules ''' if context is None: context = {} return LazyLoader( _module_dirs(opts, 'wheel'), opts, tag='wheel', whitelist=whitelist, pack={'__context__': context}, ) def outputters(opts): ''' Returns the outputters modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only outputters present in the keyspace ''' ret = LazyLoader( _module_dirs(opts, 'output', ext_type_dirs='outputter_dirs'), opts, tag='output', ) wrapped_ret = FilterDictWrapper(ret, '.output') # TODO: this name seems terrible... __salt__ should always be execution mods ret.pack['__salt__'] = wrapped_ret return wrapped_ret def serializers(opts): ''' Returns the serializers modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only serializers present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'serializers'), opts, tag='serializers', ) def eauth_tokens(opts): ''' Returns the tokens modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only token backends present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'tokens'), opts, tag='tokens', ) def auth(opts, whitelist=None): ''' Returns the auth modules :param dict opts: The Salt options dictionary :returns: LazyLoader ''' return LazyLoader( _module_dirs(opts, 'auth'), opts, tag='auth', whitelist=whitelist, pack={'__salt__': minion_mods(opts)}, ) def fileserver(opts, backends): ''' Returns the file server modules ''' return LazyLoader(_module_dirs(opts, 'fileserver'), opts, tag='fileserver', whitelist=backends, pack={'__utils__': utils(opts)}) def roster(opts, runner=None, utils=None, whitelist=None): ''' Returns the roster modules ''' return LazyLoader( _module_dirs(opts, 'roster'), opts, tag='roster', whitelist=whitelist, pack={ '__runner__': runner, '__utils__': utils, }, ) def thorium(opts, functions, runners): ''' Load the thorium runtime modules ''' pack = {'__salt__': functions, '__runner__': runners, '__context__': {}} ret = LazyLoader(_module_dirs(opts, 'thorium'), opts, tag='thorium', pack=pack) ret.pack['__thorium__'] = ret return ret def states(opts, functions, utils, serializers, whitelist=None, proxy=None, context=None): ''' Returns the state modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') statemods = salt.loader.states(__opts__, None, None) ''' if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'states'), opts, tag='states', pack={'__salt__': functions, '__proxy__': proxy or {}}, whitelist=whitelist, ) ret.pack['__states__'] = ret ret.pack['__utils__'] = utils ret.pack['__serializers__'] = serializers ret.pack['__context__'] = context return ret def beacons(opts, functions, context=None, proxy=None): ''' Load the beacon modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. ''' return LazyLoader( _module_dirs(opts, 'beacons'), opts, tag='beacons', pack={'__context__': context, '__salt__': functions, '__proxy__': proxy or {}}, virtual_funcs=[], ) def log_handlers(opts): ''' Returns the custom logging handler modules :param dict opts: The Salt options dictionary ''' ret = LazyLoader( _module_dirs( opts, 'log_handlers', int_type='handlers', base_path=os.path.join(SALT_BASE_PATH, 'log'), ), opts, tag='log_handlers', ) return FilterDictWrapper(ret, '.setup_handlers') def ssh_wrapper(opts, functions=None, context=None): ''' Returns the custom logging handler modules ''' return LazyLoader( _module_dirs( opts, 'wrapper', base_path=os.path.join(SALT_BASE_PATH, os.path.join('client', 'ssh')), ), opts, tag='wrapper', pack={ '__salt__': functions, '__grains__': opts.get('grains', {}), '__pillar__': opts.get('pillar', {}), '__context__': context, }, ) def render(opts, functions, states=None, proxy=None, context=None): ''' Returns the render modules ''' if context is None: context = {} pack = {'__salt__': functions, '__grains__': opts.get('grains', {}), '__context__': context} if states: pack['__states__'] = states pack['__proxy__'] = proxy or {} ret = LazyLoader( _module_dirs( opts, 'renderers', 'render', ext_type_dirs='render_dirs', ), opts, tag='render', pack=pack, ) rend = FilterDictWrapper(ret, '.render') if not check_render_pipe_str(opts['renderer'], rend, opts['renderer_blacklist'], opts['renderer_whitelist']): err = ('The renderer {0} is unavailable, this error is often because ' 'the needed software is unavailable'.format(opts['renderer'])) log.critical(err) raise LoaderError(err) return rend def _load_cached_grains(opts, cfn): ''' Returns the grains cached in cfn, or None if the cache is too old or is corrupted. ''' if not os.path.isfile(cfn): log.debug('Grains cache file does not exist.') return None grains_cache_age = int(time.time() - os.path.getmtime(cfn)) if grains_cache_age > opts.get('grains_cache_expiration', 300): log.debug( 'Grains cache last modified %s seconds ago and cache ' 'expiration is set to %s. Grains cache expired. ' 'Refreshing.', grains_cache_age, opts.get('grains_cache_expiration', 300) ) return None if opts.get('refresh_grains_cache', False): log.debug('refresh_grains_cache requested, Refreshing.') return None log.debug('Retrieving grains from cache') try: serial = salt.payload.Serial(opts) with salt.utils.files.fopen(cfn, 'rb') as fp_: cached_grains = salt.utils.data.decode(serial.load(fp_), preserve_tuples=True) if not cached_grains: log.debug('Cached grains are empty, cache might be corrupted. Refreshing.') return None return cached_grains except (IOError, OSError): return None def grains(opts, force_refresh=False, proxy=None): ''' Return the functions for the dynamic grains and the values for the static grains. Since grains are computed early in the startup process, grains functions do not have __salt__ or __proxy__ available. At proxy-minion startup, this function is called with the proxymodule LazyLoader object so grains functions can communicate with their controlled device. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) print __grains__['id'] ''' # Need to re-import salt.config, somehow it got lost when a minion is starting import salt.config # if we have no grains, lets try loading from disk (TODO: move to decorator?) cfn = os.path.join( opts['cachedir'], 'grains.cache.p' ) if not force_refresh and opts.get('grains_cache', False): cached_grains = _load_cached_grains(opts, cfn) if cached_grains: return cached_grains else: log.debug('Grains refresh requested. Refreshing grains.') if opts.get('skip_grains', False): return {} grains_deep_merge = opts.get('grains_deep_merge', False) is True if 'conf_file' in opts: pre_opts = {} pre_opts.update(salt.config.load_config( opts['conf_file'], 'SALT_MINION_CONFIG', salt.config.DEFAULT_MINION_OPTS['conf_file'] )) default_include = pre_opts.get( 'default_include', opts['default_include'] ) include = pre_opts.get('include', []) pre_opts.update(salt.config.include_config( default_include, opts['conf_file'], verbose=False )) pre_opts.update(salt.config.include_config( include, opts['conf_file'], verbose=True )) if 'grains' in pre_opts: opts['grains'] = pre_opts['grains'] else: opts['grains'] = {} else: opts['grains'] = {} grains_data = {} blist = opts.get('grains_blacklist', []) funcs = grain_funcs(opts, proxy=proxy) if force_refresh: # if we refresh, lets reload grain modules funcs.clear() # Run core grains for key in funcs: if not key.startswith('core.'): continue log.trace('Loading %s grain', key) ret = funcs[key]() if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) # Run the rest of the grains for key in funcs: if key.startswith('core.') or key == '_errors': continue try: # Grains are loaded too early to take advantage of the injected # __proxy__ variable. Pass an instance of that LazyLoader # here instead to grains functions if the grains functions take # one parameter. Then the grains can have access to the # proxymodule for retrieving information from the connected # device. log.trace('Loading %s grain', key) parameters = salt.utils.args.get_function_argspec(funcs[key]).args kwargs = {} if 'proxy' in parameters: kwargs['proxy'] = proxy if 'grains' in parameters: kwargs['grains'] = grains_data ret = funcs[key](**kwargs) except Exception: if salt.utils.platform.is_proxy(): log.info('The following CRITICAL message may not be an error; the proxy may not be completely established yet.') log.critical( 'Failed to load grains defined in grain file %s in ' 'function %s, error:\n', key, funcs[key], exc_info=True ) continue if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) if opts.get('proxy_merge_grains_in_module', True) and proxy: try: proxytype = proxy.opts['proxy']['proxytype'] if proxytype + '.grains' in proxy: if proxytype + '.initialized' in proxy and proxy[proxytype + '.initialized'](): try: proxytype = proxy.opts['proxy']['proxytype'] ret = proxy[proxytype + '.grains']() if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) except Exception: log.critical('Failed to run proxy\'s grains function!', exc_info=True ) except KeyError: pass grains_data.update(opts['grains']) # Write cache if enabled if opts.get('grains_cache', False): with salt.utils.files.set_umask(0o077): try: if salt.utils.platform.is_windows(): # Late import import salt.modules.cmdmod # Make sure cache file isn't read-only salt.modules.cmdmod._run_quiet('attrib -R "{0}"'.format(cfn)) with salt.utils.files.fopen(cfn, 'w+b') as fp_: try: serial = salt.payload.Serial(opts) serial.dump(grains_data, fp_) except TypeError as e: log.error('Failed to serialize grains cache: %s', e) raise # re-throw for cleanup except Exception as e: log.error('Unable to write to grains cache file %s: %s', cfn, e) # Based on the original exception, the file may or may not have been # created. If it was, we will remove it now, as the exception means # the serialized data is not to be trusted, no matter what the # exception is. if os.path.isfile(cfn): os.unlink(cfn) if grains_deep_merge: salt.utils.dictupdate.update(grains_data, opts['grains']) else: grains_data.update(opts['grains']) return salt.utils.data.decode(grains_data, preserve_tuples=True) # TODO: get rid of? Does anyone use this? You should use raw() instead def call(fun, **kwargs): ''' Directly call a function inside a loader directory ''' args = kwargs.get('args', []) dirs = kwargs.get('dirs', []) funcs = LazyLoader( [os.path.join(SALT_BASE_PATH, 'modules')] + dirs, None, tag='modules', virtual_enable=False, ) return funcs[fun](*args) def runner(opts, utils=None, context=None, whitelist=None): ''' Directly call a function inside a loader directory ''' if utils is None: utils = {} if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'runners', 'runner', ext_type_dirs='runner_dirs'), opts, tag='runners', pack={'__utils__': utils, '__context__': context}, whitelist=whitelist, ) # TODO: change from __salt__ to something else, we overload __salt__ too much ret.pack['__salt__'] = ret return ret def queues(opts): ''' Directly call a function inside a loader directory ''' return LazyLoader( _module_dirs(opts, 'queues', 'queue', ext_type_dirs='queue_dirs'), opts, tag='queues', ) def sdb(opts, functions=None, whitelist=None, utils=None): ''' Make a very small database call ''' if utils is None: utils = {} return LazyLoader( _module_dirs(opts, 'sdb'), opts, tag='sdb', pack={ '__sdb__': functions, '__opts__': opts, '__utils__': utils, '__salt__': minion_mods(opts, utils), }, whitelist=whitelist, ) def pkgdb(opts): ''' Return modules for SPM's package database .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgdb', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgdb' ) def pkgfiles(opts): ''' Return modules for SPM's file handling .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgfiles', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgfiles' ) def clouds(opts): ''' Return the cloud functions ''' # Let's bring __active_provider_name__, defaulting to None, to all cloud # drivers. This will get temporarily updated/overridden with a context # manager when needed. functions = LazyLoader( _module_dirs(opts, 'clouds', 'cloud', base_path=os.path.join(SALT_BASE_PATH, 'cloud'), int_type='clouds'), opts, tag='clouds', pack={'__utils__': salt.loader.utils(opts), '__active_provider_name__': None}, ) for funcname in LIBCLOUD_FUNCS_NOT_SUPPORTED: log.trace( '\'%s\' has been marked as not supported. Removing from the ' 'list of supported cloud functions', funcname ) functions.pop(funcname, None) return functions def netapi(opts): ''' Return the network api functions ''' return LazyLoader( _module_dirs(opts, 'netapi'), opts, tag='netapi', ) def executors(opts, functions=None, context=None, proxy=None): ''' Returns the executor modules ''' executors = LazyLoader( _module_dirs(opts, 'executors', 'executor'), opts, tag='executor', pack={'__salt__': functions, '__context__': context or {}, '__proxy__': proxy or {}}, ) executors.pack['__executors__'] = executors return executors def cache(opts, serial): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'cache', 'cache'), opts, tag='cache', pack={'__opts__': opts, '__context__': {'serial': serial}}, ) def _generate_module(name): if name in sys.modules: return code = "'''Salt loaded {0} parent module'''".format(name.split('.')[-1]) # ModuleType can't accept a unicode type on PY2 module = types.ModuleType(str(name)) # future lint: disable=blacklisted-function exec(code, module.__dict__) sys.modules[name] = module def _mod_type(module_path): if module_path.startswith(SALT_BASE_PATH): return 'int' return 'ext' def _inject_into_mod(mod, name, value, force_lock=False): ''' Inject a variable into a module. This is used to inject "globals" like ``__salt__``, ``__pillar``, or ``grains``. Instead of injecting the value directly, a ``ThreadLocalProxy`` is created. If such a proxy is already present under the specified name, it is updated with the new value. This update only affects the current thread, so that the same name can refer to different values depending on the thread of execution. This is important for data that is not truly global. For example, pillar data might be dynamically overriden through function parameters and thus the actual values available in pillar might depend on the thread that is calling a module. mod: module object into which the value is going to be injected. name: name of the variable that is injected into the module. value: value that is injected into the variable. The value is not injected directly, but instead set as the new reference of the proxy that has been created for the variable. force_lock: whether the lock should be acquired before checking whether a proxy object for the specified name has already been injected into the module. If ``False`` (the default), this function checks for the module's variable without acquiring the lock and only acquires the lock if a new proxy has to be created and injected. ''' old_value = getattr(mod, name, None) # We use a double-checked locking scheme in order to avoid taking the lock # when a proxy object has already been injected. # In most programming languages, double-checked locking is considered # unsafe when used without explicit memory barriers because one might read # an uninitialized value. In CPython it is safe due to the global # interpreter lock (GIL). In Python implementations that do not have the # GIL, it could be unsafe, but at least Jython also guarantees that (for # Python objects) memory is not corrupted when writing and reading without # explicit synchronization # (http://www.jython.org/jythonbook/en/1.0/Concurrency.html). # Please note that in order to make this code safe in a runtime environment # that does not make this guarantees, it is not sufficient. The # ThreadLocalProxy must also be created with fallback_to_shared set to # False or a lock must be added to the ThreadLocalProxy. if force_lock: with _inject_into_mod.lock: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: setattr(mod, name, ThreadLocalProxy(value, True)) else: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: _inject_into_mod(mod, name, value, True) # Lock used when injecting globals. This is needed to avoid a race condition # when two threads try to load the same module concurrently. This must be # outside the loader because there might be more than one loader for the same # namespace. _inject_into_mod.lock = threading.RLock() # TODO: move somewhere else? class FilterDictWrapper(MutableMapping): ''' Create a dict which wraps another dict with a specific key suffix on get This is to replace "filter_load" ''' def __init__(self, d, suffix): self._dict = d self.suffix = suffix def __setitem__(self, key, val): self._dict[key] = val def __delitem__(self, key): del self._dict[key] def __getitem__(self, key): return self._dict[key + self.suffix] def __len__(self): return len(self._dict) def __iter__(self): for key in self._dict: if key.endswith(self.suffix): yield key.replace(self.suffix, '') class LazyLoader(salt.utils.lazy.LazyDict): ''' A pseduo-dictionary which has a set of keys which are the name of the module and function, delimited by a dot. When the value of the key is accessed, the function is then loaded from disk and into memory. .. note:: Iterating over keys will cause all modules to be loaded. :param list module_dirs: A list of directories on disk to search for modules :param dict opts: The salt options dictionary. :param str tag: The tag for the type of module to load :param func mod_type_check: A function which can be used to verify files :param dict pack: A dictionary of function to be packed into modules as they are loaded :param list whitelist: A list of modules to whitelist :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules. :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality. If not true, the module will not load. :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values are function references themselves which are loaded on-demand. # TODO: - move modules_max_memory into here - singletons (per tag) ''' mod_dict_class = salt.utils.odict.OrderedDict def __init__(self, module_dirs, opts=None, tag='module', loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, proxy=None, virtual_funcs=None, ): # pylint: disable=W0231 ''' In pack, if any of the values are None they will be replaced with an empty context-specific dict ''' self.inject_globals = {} self.pack = {} if pack is None else pack if opts is None: opts = {} threadsafety = not opts.get('multiprocessing') self.context_dict = salt.utils.context.ContextDict(threadsafe=threadsafety) self.opts = self.__prep_mod_opts(opts) self.module_dirs = module_dirs self.tag = tag self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME self.mod_type_check = mod_type_check or _mod_type if '__context__' not in self.pack: self.pack['__context__'] = None for k, v in six.iteritems(self.pack): if v is None: # if the value of a pack is None, lets make an empty dict value = self.context_dict.get(k, {}) if isinstance(value, ThreadLocalProxy): value = ThreadLocalProxy.unproxy(value) self.context_dict[k] = value self.pack[k] = salt.utils.context.NamespacedDictWrapper(self.context_dict, k) self.whitelist = whitelist self.virtual_enable = virtual_enable self.initial_load = True # names of modules that we don't have (errors, __virtual__, etc.) self.missing_modules = {} # mapping of name -> error self.loaded_modules = {} # mapping of module_name -> dict_of_functions self.loaded_files = set() # TODO: just remove them from file_mapping? self.static_modules = static_modules if static_modules else [] if virtual_funcs is None: virtual_funcs = [] self.virtual_funcs = virtual_funcs self.disabled = set( self.opts.get( 'disable_{0}{1}'.format( self.tag, '' if self.tag[-1] == 's' else 's' ), [] ) ) # A map of suffix to description for imp self.suffix_map = {} # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [''] for (suffix, mode, kind) in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) self._lock = threading.RLock() self._refresh_file_mapping() super(LazyLoader, self).__init__() # late init the lazy loader # create all of the import namespaces _generate_module('{0}.int'.format(self.loaded_base_name)) _generate_module('{0}.int.{1}'.format(self.loaded_base_name, tag)) _generate_module('{0}.ext'.format(self.loaded_base_name)) _generate_module('{0}.ext.{1}'.format(self.loaded_base_name, tag)) def __getitem__(self, item): ''' Override the __getitem__ in order to decorate the returned function if we need to last-minute inject globals ''' func = super(LazyLoader, self).__getitem__(item) if self.inject_globals: return global_injector_decorator(self.inject_globals)(func) else: return func def __getattr__(self, mod_name): ''' Allow for "direct" attribute access-- this allows jinja templates to access things like `salt.test.ping()` ''' if mod_name in ('__getstate__', '__setstate__'): return object.__getattribute__(self, mod_name) # if we have an attribute named that, lets return it. try: return object.__getattr__(self, mod_name) # pylint: disable=no-member except AttributeError: pass # otherwise we assume its jinja template access if mod_name not in self.loaded_modules and not self.loaded: for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and mod_name in self.loaded_modules: break if mod_name in self.loaded_modules: return self.loaded_modules[mod_name] else: raise AttributeError(mod_name) def missing_fun_string(self, function_name): ''' Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ''' mod_name = function_name.split('.')[0] if mod_name in self.loaded_modules: return '\'{0}\' is not available.'.format(function_name) else: try: reason = self.missing_modules[mod_name] except KeyError: return '\'{0}\' is not available.'.format(function_name) else: if reason is not None: return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason) else: return '\'{0}\' __virtual__ returned False'.format(mod_name) def _refresh_file_mapping(self): ''' refresh the mapping of the FS on disk ''' # map of suffix to description for imp if self.opts.get('cython_enable', True) is True: try: global pyximport pyximport = __import__('pyximport') # pylint: disable=import-error pyximport.install() # add to suffix_map so file_mapping will pick it up self.suffix_map['.pyx'] = tuple() except ImportError: log.info('Cython is enabled in the options but not present ' 'in the system path. Skipping Cython modules.') # Allow for zipimport of modules if self.opts.get('enable_zip_modules', True) is True: self.suffix_map['.zip'] = tuple() # allow for module dirs if USE_IMPORTLIB: self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY) else: self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY) # create mapping of filename (without suffix) to (path, suffix) # The files are added in order of priority, so order *must* be retained. self.file_mapping = salt.utils.odict.OrderedDict() opt_match = [] def _replace_pre_ext(obj): ''' Hack so we can get the optimization level that we replaced (if any) out of the re.sub call below. We use a list here because it is a persistent data structure that we will be able to access after re.sub is called. ''' opt_match.append(obj) return '' for mod_dir in self.module_dirs: try: # Make sure we have a sorted listdir in order to have # expectable override results files = sorted( x for x in os.listdir(mod_dir) if x != '__pycache__' ) except OSError: continue # Next mod_dir if six.PY3: try: pycache_files = [ os.path.join('__pycache__', x) for x in sorted(os.listdir(os.path.join(mod_dir, '__pycache__'))) ] except OSError: pass else: files.extend(pycache_files) for filename in files: try: dirname, basename = os.path.split(filename) if basename.startswith('_'): # skip private modules # log messages omitted for obviousness continue # Next filename f_noext, ext = os.path.splitext(basename) if six.PY3: f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext) try: opt_level = int( opt_match.pop().group(1).rsplit('-', 1)[-1] ) except (AttributeError, IndexError, ValueError): # No regex match or no optimization level matched opt_level = 0 try: opt_index = self.opts['optimization_order'].index(opt_level) except KeyError: log.trace( 'Disallowed optimization level %d for module ' 'name \'%s\', skipping. Add %d to the ' '\'optimization_order\' config option if you ' 'do not want to ignore this optimization ' 'level.', opt_level, f_noext, opt_level ) continue else: # Optimization level not reflected in filename on PY2 opt_index = 0 # make sure it is a suffix we support if ext not in self.suffix_map: continue # Next filename if f_noext in self.disabled: log.trace( 'Skipping %s, it is disabled by configuration', filename ) continue # Next filename fpath = os.path.join(mod_dir, filename) # if its a directory, lets allow us to load that if ext == '': # is there something __init__? subfiles = os.listdir(fpath) for suffix in self.suffix_order: if '' == suffix: continue # Next suffix (__init__ must have a suffix) init_file = '__init__{0}'.format(suffix) if init_file in subfiles: break else: continue # Next filename try: curr_ext = self.file_mapping[f_noext][1] curr_opt_index = self.file_mapping[f_noext][2] except KeyError: pass else: if '' in (curr_ext, ext) and curr_ext != ext: log.error( 'Module/package collision: \'%s\' and \'%s\'', fpath, self.file_mapping[f_noext][0] ) if six.PY3 and ext == '.pyc' and curr_ext == '.pyc': # Check the optimization level if opt_index >= curr_opt_index: # Module name match, but a higher-priority # optimization level was already matched, skipping. continue elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext): # Match found but a higher-priorty match already # exists, so skip this. continue if six.PY3 and not dirname and ext == '.pyc': # On Python 3, we should only load .pyc files from the # __pycache__ subdirectory (i.e. when dirname is not an # empty string). continue # Made it this far - add it self.file_mapping[f_noext] = (fpath, ext, opt_index) except OSError: continue for smod in self.static_modules: f_noext = smod.split('.')[-1] self.file_mapping[f_noext] = (smod, '.o', 0) def clear(self): ''' Clear the dict ''' with self._lock: super(LazyLoader, self).clear() # clear the lazy loader self.loaded_files = set() self.missing_modules = {} self.loaded_modules = {} # if we have been loaded before, lets clear the file mapping since # we obviously want a re-do if hasattr(self, 'opts'): self._refresh_file_mapping() self.initial_load = False def __prep_mod_opts(self, opts): ''' Strip out of the opts any logger instance ''' if '__grains__' not in self.pack: grains = opts.get('grains', {}) if isinstance(grains, ThreadLocalProxy): grains = ThreadLocalProxy.unproxy(grains) self.context_dict['grains'] = grains self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains') if '__pillar__' not in self.pack: pillar = opts.get('pillar', {}) if isinstance(pillar, ThreadLocalProxy): pillar = ThreadLocalProxy.unproxy(pillar) self.context_dict['pillar'] = pillar self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar') mod_opts = {} for key, val in list(opts.items()): if key == 'logger': continue mod_opts[key] = val return mod_opts def _iter_files(self, mod_name): ''' Iterate over all file_mapping files in order of closeness to mod_name ''' # do we have an exact match? if mod_name in self.file_mapping: yield mod_name # do we have a partial match? for k in self.file_mapping: if mod_name in k: yield k # anyone else? Bueller? for k in self.file_mapping: if mod_name not in k: yield k def _reload_submodules(self, mod): submodules = ( getattr(mod, sname) for sname in dir(mod) if isinstance(getattr(mod, sname), mod.__class__) ) # reload only custom "sub"modules for submodule in submodules: # it is a submodule if the name is in a namespace under mod if submodule.__name__.startswith(mod.__name__ + '.'): reload_module(submodule) self._reload_submodules(submodule) def _load_module(self, name): mod = None fpath, suffix = self.file_mapping[name][:2] self.loaded_files.add(name) fpath_dirname = os.path.dirname(fpath) try: sys.path.append(fpath_dirname) if suffix == '.pyx': mod = pyximport.load_module(name, fpath, tempfile.gettempdir()) elif suffix == '.o': top_mod = __import__(fpath, globals(), locals(), []) comps = fpath.split('.') if len(comps) < 2: mod = top_mod else: mod = top_mod for subname in comps[1:]: mod = getattr(mod, subname) elif suffix == '.zip': mod = zipimporter(fpath).load_module(name) else: desc = self.suffix_map[suffix] # if it is a directory, we don't open a file try: mod_namespace = '.'.join(( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name)) except TypeError: mod_namespace = '{0}.{1}.{2}.{3}'.format( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name) if suffix == '': if USE_IMPORTLIB: # pylint: disable=no-member # Package directory, look for __init__ loader_details = [ (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES), (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES), (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), ] file_finder = importlib.machinery.FileFinder( fpath_dirname, *loader_details ) spec = file_finder.find_spec(mod_namespace) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: mod = imp.load_module(mod_namespace, None, fpath, desc) # reload all submodules if necessary if not self.initial_load: self._reload_submodules(mod) else: if USE_IMPORTLIB: # pylint: disable=no-member loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath) spec = importlib.util.spec_from_file_location( mod_namespace, fpath, loader=loader ) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() #mod = importlib.util.module_from_spec(spec) #spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: with salt.utils.files.fopen(fpath, desc[1]) as fn_: mod = imp.load_module(mod_namespace, fn_, fpath, desc) except IOError: raise except ImportError as exc: if 'magic number' in six.text_type(exc): error_msg = 'Failed to import {0} {1}. Bad magic number. If migrating from Python2 to Python3, remove all .pyc files and try again.'.format(self.tag, name) log.warning(error_msg) self.missing_modules[name] = error_msg log.debug( 'Failed to import %s %s:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = exc return False except Exception as error: log.error( 'Failed to import %s %s, this is due most likely to a ' 'syntax error:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False except SystemExit as error: try: fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1] except Exception: pass else: tgt_fn = os.path.join('salt', 'utils', 'process.py') if fn_.endswith(tgt_fn) and '_handle_signals' in caller: # Race conditon, SIGTERM or SIGINT received while loader # was in process of loading a module. Call sys.exit to # ensure that the process is killed. sys.exit(salt.defaults.exitcodes.EX_OK) log.error( 'Failed to import %s %s as the module called exit()\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False finally: sys.path.remove(fpath_dirname) if hasattr(mod, '__opts__'): mod.__opts__.update(self.opts) else: mod.__opts__ = self.opts # pack whatever other globals we were asked to for p_name, p_value in six.iteritems(self.pack): _inject_into_mod(mod, p_name, p_value) module_name = mod.__name__.rsplit('.', 1)[-1] # Call a module's initialization method if it exists module_init = getattr(mod, '__init__', None) if inspect.isfunction(module_init): try: module_init(self.opts) except TypeError as e: log.error(e) except Exception: err_string = '__init__ failed' log.debug( 'Error loading %s.%s: %s', self.tag, module_name, err_string, exc_info=True ) self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False # if virtual modules are enabled, we need to look for the # __virtual__() function inside that module and run it. if self.virtual_enable: virtual_funcs_to_process = ['__virtual__'] + self.virtual_funcs for virtual_func in virtual_funcs_to_process: virtual_ret, module_name, virtual_err, virtual_aliases = \ self._process_virtual(mod, module_name, virtual_func) if virtual_err is not None: log.trace( 'Error loading %s.%s: %s', self.tag, module_name, virtual_err ) # if _process_virtual returned a non-True value then we are # supposed to not process this module if virtual_ret is not True and module_name not in self.missing_modules: # If a module has information about why it could not be loaded, record it self.missing_modules[module_name] = virtual_err self.missing_modules[name] = virtual_err return False else: virtual_aliases = () # If this is a proxy minion then MOST modules cannot work. Therefore, require that # any module that does work with salt-proxy-minion define __proxyenabled__ as a list # containing the names of the proxy types that the module supports. # # Render modules and state modules are OK though if 'proxy' in self.opts: if self.tag in ['grains', 'proxy']: if not hasattr(mod, '__proxyenabled__') or \ (self.opts['proxy']['proxytype'] not in mod.__proxyenabled__ and '*' not in mod.__proxyenabled__): err_string = 'not a proxy_minion enabled module' self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False if getattr(mod, '__load__', False) is not False: log.info( 'The functions from module \'%s\' are being loaded from the ' 'provided __load__ attribute', module_name ) # If we had another module by the same virtual name, we should put any # new functions under the existing dictionary. mod_names = [module_name] + list(virtual_aliases) mod_dict = dict(( (x, self.loaded_modules.get(x, self.mod_dict_class())) for x in mod_names )) for attr in getattr(mod, '__load__', dir(mod)): if attr.startswith('_') and attr != '__call__': # private functions are skipped, # except __call__ which is default entrance # for multi-function batch-like state syntax continue func = getattr(mod, attr) if not inspect.isfunction(func) and not isinstance(func, functools.partial): # Not a function!? Skip it!!! continue # Let's get the function name. # If the module has the __func_alias__ attribute, it must be a # dictionary mapping in the form of(key -> value): # <real-func-name> -> <desired-func-name> # # It default's of course to the found callable attribute name # if no alias is defined. funcname = getattr(mod, '__func_alias__', {}).get(attr, attr) for tgt_mod in mod_names: try: full_funcname = '.'.join((tgt_mod, funcname)) except TypeError: full_funcname = '{0}.{1}'.format(tgt_mod, funcname) # Save many references for lookups # Careful not to overwrite existing (higher priority) functions if full_funcname not in self._dict: self._dict[full_funcname] = func if funcname not in mod_dict[tgt_mod]: setattr(mod_dict[tgt_mod], funcname, func) mod_dict[tgt_mod][funcname] = func self._apply_outputter(func, mod) # enforce depends try: Depends.enforce_dependencies(self._dict, self.tag) except RuntimeError as exc: log.info( 'Depends.enforce_dependencies() failed for the following ' 'reason: %s', exc ) for tgt_mod in mod_names: self.loaded_modules[tgt_mod] = mod_dict[tgt_mod] return True def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise KeyError('The key \'{0}\' should contain a \'.\''.format(key)) mod_name, _ = key.split('.', 1) with self._lock: # It is possible that the key is in the dictionary after # acquiring the lock due to another thread loading it. if mod_name in self.missing_modules or key in self._dict: return True # if the modulename isn't in the whitelist, don't bother if self.whitelist and mod_name not in self.whitelist: log.error( 'Failed to load function %s because its module (%s) is ' 'not in the whitelist: %s', key, mod_name, self.whitelist ) raise KeyError(key) def _inner_load(mod_name): for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and key in self._dict: return True return False # try to load the module ret = None reloaded = False # re-scan up to once, IOErrors or a failed load cause re-scans of the # filesystem while True: try: ret = _inner_load(mod_name) if not reloaded and ret is not True: self._refresh_file_mapping() reloaded = True continue break except IOError: if not reloaded: self._refresh_file_mapping() reloaded = True continue return ret def _load_all(self): ''' Load all of them ''' with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True def reload_modules(self): with self._lock: self.loaded_files = set() self._load_all() def _apply_outputter(self, func, mod): ''' Apply the __outputter__ variable to the functions ''' if hasattr(mod, '__outputter__'): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__] def _process_virtual(self, mod, module_name, virtual_func='__virtual__'): ''' Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1] ''' # The __virtual__ function will return either a True or False value. # If it returns a True value it can also set a module level attribute # named __virtualname__ with the name that the module should be # referred to as. # # This allows us to have things like the pkg module working on all # platforms under the name 'pkg'. It also allows for modules like # augeas_cfg to be referred to as 'augeas', which would otherwise have # namespace collisions. And finally it allows modules to return False # if they are not intended to run on the given platform or are missing # dependencies. virtual_aliases = getattr(mod, '__virtual_aliases__', tuple()) try: error_reason = None if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__): try: start = time.time() virtual = getattr(mod, virtual_func)() if isinstance(virtual, tuple): error_reason = virtual[1] virtual = virtual[0] if self.opts.get('virtual_timer', False): end = time.time() - start msg = 'Virtual function took {0} seconds for {1}'.format( end, module_name) log.warning(msg) except Exception as exc: error_reason = ( 'Exception raised when processing __virtual__ function' ' for {0}. Module will not be loaded: {1}'.format( mod.__name__, exc)) log.error(error_reason, exc_info_on_loglevel=logging.DEBUG) virtual = None # Get the module's virtual name virtualname = getattr(mod, '__virtualname__', virtual) if not virtual: # if __virtual__() evaluates to False then the module # wasn't meant for this platform or it's not supposed to # load for some other reason. # Some modules might accidentally return None and are # improperly loaded if virtual is None: log.warning( '%s.__virtual__() is wrongly returning `None`. ' 'It should either return `True`, `False` or a new ' 'name. If you\'re the developer of the module ' '\'%s\', please fix this.', mod.__name__, module_name ) return (False, module_name, error_reason, virtual_aliases) # At this point, __virtual__ did not return a # boolean value, let's check for deprecated usage # or module renames if virtual is not True and module_name != virtual: # The module is renaming itself. Updating the module name # with the new name log.trace('Loaded %s as virtual %s', module_name, virtual) if virtualname != virtual: # The __virtualname__ attribute does not match what's # being returned by the __virtual__() function. This # should be considered an error. log.error( 'The module \'%s\' is showing some bad usage. Its ' '__virtualname__ attribute is set to \'%s\' yet the ' '__virtual__() function is returning \'%s\'. These ' 'values should match!', mod.__name__, virtualname, virtual ) module_name = virtualname # If the __virtual__ function returns True and __virtualname__ # is set then use it elif virtual is True and virtualname != module_name: if virtualname is not True: module_name = virtualname except KeyError: # Key errors come out of the virtual function when passing # in incomplete grains sets, these can be safely ignored # and logged to debug, still, it includes the traceback to # help debugging. log.debug('KeyError when loading %s', module_name, exc_info=True) except Exception: # If the module throws an exception during __virtual__() # then log the information and continue to the next. log.error( 'Failed to read the virtual function for %s: %s', self.tag, module_name, exc_info=True ) return (False, module_name, error_reason, virtual_aliases) return (True, module_name, None, virtual_aliases) def global_injector_decorator(inject_globals): ''' Decorator used by the LazyLoader to inject globals into a function at execute time. globals Dictionary with global variables to inject ''' def inner_decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): with salt.utils.context.func_globals_inject(f, **inject_globals): return f(*args, **kwargs) return wrapper return inner_decorator
saltstack/salt
salt/loader.py
_load_cached_grains
python
def _load_cached_grains(opts, cfn): ''' Returns the grains cached in cfn, or None if the cache is too old or is corrupted. ''' if not os.path.isfile(cfn): log.debug('Grains cache file does not exist.') return None grains_cache_age = int(time.time() - os.path.getmtime(cfn)) if grains_cache_age > opts.get('grains_cache_expiration', 300): log.debug( 'Grains cache last modified %s seconds ago and cache ' 'expiration is set to %s. Grains cache expired. ' 'Refreshing.', grains_cache_age, opts.get('grains_cache_expiration', 300) ) return None if opts.get('refresh_grains_cache', False): log.debug('refresh_grains_cache requested, Refreshing.') return None log.debug('Retrieving grains from cache') try: serial = salt.payload.Serial(opts) with salt.utils.files.fopen(cfn, 'rb') as fp_: cached_grains = salt.utils.data.decode(serial.load(fp_), preserve_tuples=True) if not cached_grains: log.debug('Cached grains are empty, cache might be corrupted. Refreshing.') return None return cached_grains except (IOError, OSError): return None
Returns the grains cached in cfn, or None if the cache is too old or is corrupted.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L695-L729
null
# -*- coding: utf-8 -*- ''' The Salt loader is the core to Salt's plugin system, the loader scans directories for python loadable code and organizes the code into the plugin interfaces used by Salt. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import sys import time import logging import inspect import tempfile import threading import functools import threading import traceback import types from zipimport import zipimporter # Import salt libs import salt.config import salt.defaults.events import salt.defaults.exitcodes import salt.syspaths import salt.utils.args import salt.utils.context import salt.utils.data import salt.utils.dictupdate import salt.utils.event import salt.utils.files import salt.utils.lazy import salt.utils.odict import salt.utils.platform import salt.utils.versions import salt.utils.stringutils from salt.exceptions import LoaderError from salt.template import check_render_pipe_str from salt.utils.decorators import Depends from salt.utils.thread_local_proxy import ThreadLocalProxy # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import reload_module if sys.version_info[:2] >= (3, 5): import importlib.machinery # pylint: disable=no-name-in-module,import-error import importlib.util # pylint: disable=no-name-in-module,import-error USE_IMPORTLIB = True else: import imp USE_IMPORTLIB = False try: from collections.abc import MutableMapping except ImportError: from collections import MutableMapping try: import pkg_resources HAS_PKG_RESOURCES = True except ImportError: HAS_PKG_RESOURCES = False log = logging.getLogger(__name__) SALT_BASE_PATH = os.path.abspath(salt.syspaths.INSTALL_DIR) LOADED_BASE_NAME = 'salt.loaded' if USE_IMPORTLIB: # pylint: disable=no-member MODULE_KIND_SOURCE = 1 MODULE_KIND_COMPILED = 2 MODULE_KIND_EXTENSION = 3 MODULE_KIND_PKG_DIRECTORY = 5 SUFFIXES = [] for suffix in importlib.machinery.EXTENSION_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_EXTENSION)) for suffix in importlib.machinery.SOURCE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_SOURCE)) for suffix in importlib.machinery.BYTECODE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_COMPILED)) MODULE_KIND_MAP = { MODULE_KIND_SOURCE: importlib.machinery.SourceFileLoader, MODULE_KIND_COMPILED: importlib.machinery.SourcelessFileLoader, MODULE_KIND_EXTENSION: importlib.machinery.ExtensionFileLoader } # pylint: enable=no-member else: SUFFIXES = imp.get_suffixes() PY3_PRE_EXT = \ re.compile(r'\.cpython-{0}{1}(\.opt-[1-9])?'.format(*sys.version_info[:2])) # Because on the cloud drivers we do `from salt.cloud.libcloudfuncs import *` # which simplifies code readability, it adds some unsupported functions into # the driver's module scope. # We list un-supported functions here. These will be removed from the loaded. # TODO: remove the need for this cross-module code. Maybe use NotImplemented LIBCLOUD_FUNCS_NOT_SUPPORTED = ( 'parallels.avail_sizes', 'parallels.avail_locations', 'proxmox.avail_sizes', ) # Will be set to pyximport module at runtime if cython is enabled in config. pyximport = None def static_loader( opts, ext_type, tag, pack=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, filter_name=None, ): funcs = LazyLoader( _module_dirs( opts, ext_type, tag, int_type, ext_dirs, ext_type_dirs, base_path, ), opts, tag=tag, pack=pack, ) ret = {} funcs._load_all() if filter_name: funcs = FilterDictWrapper(funcs, filter_name) for key in funcs: ret[key] = funcs[key] return ret def _format_entrypoint_target(ep): ''' Makes a string describing the target of an EntryPoint object. Base strongly on EntryPoint.__str__(). ''' s = ep.module_name if ep.attrs: s += ':' + '.'.join(ep.attrs) return s def _module_dirs( opts, ext_type, tag=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, ): if tag is None: tag = ext_type sys_types = os.path.join(base_path or SALT_BASE_PATH, int_type or ext_type) ext_types = os.path.join(opts['extension_modules'], ext_type) ext_type_types = [] if ext_dirs: if ext_type_dirs is None: ext_type_dirs = '{0}_dirs'.format(tag) if ext_type_dirs in opts: ext_type_types.extend(opts[ext_type_dirs]) if HAS_PKG_RESOURCES and ext_type_dirs: for entry_point in pkg_resources.iter_entry_points('salt.loader', ext_type_dirs): try: loaded_entry_point = entry_point.load() for path in loaded_entry_point(): ext_type_types.append(path) except Exception as exc: log.error("Error getting module directories from %s: %s", _format_entrypoint_target(entry_point), exc) log.debug("Full backtrace for module directories error", exc_info=True) cli_module_dirs = [] # The dirs can be any module dir, or a in-tree _{ext_type} dir for _dir in opts.get('module_dirs', []): # Prepend to the list to match cli argument ordering maybe_dir = os.path.join(_dir, ext_type) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) continue maybe_dir = os.path.join(_dir, '_{0}'.format(ext_type)) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) return cli_module_dirs + ext_type_types + [ext_types, sys_types] def minion_mods( opts, context=None, utils=None, whitelist=None, initial_load=False, loaded_base_name=None, notify=False, static_modules=None, proxy=None): ''' Load execution modules Returns a dictionary of execution modules appropriate for the current system by evaluating the __virtual__() function in each module. :param dict opts: The Salt options dictionary :param dict context: A Salt context that should be made present inside generated modules in __context__ :param dict utils: Utility functions which should be made available to Salt modules in __utils__. See `utils_dirs` in salt.config for additional information about configuration. :param list whitelist: A list of modules which should be whitelisted. :param bool initial_load: Deprecated flag! Unused. :param str loaded_base_name: A string marker for the loaded base name. :param bool notify: Flag indicating that an event should be fired upon completion of module loading. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) __opts__['grains'] = __grains__ __utils__ = salt.loader.utils(__opts__) __salt__ = salt.loader.minion_mods(__opts__, utils=__utils__) __salt__['test.ping']() ''' # TODO Publish documentation for module whitelisting if not whitelist: whitelist = opts.get('whitelist_modules', None) ret = LazyLoader( _module_dirs(opts, 'modules', 'module'), opts, tag='module', pack={'__context__': context, '__utils__': utils, '__proxy__': proxy}, whitelist=whitelist, loaded_base_name=loaded_base_name, static_modules=static_modules, ) ret.pack['__salt__'] = ret # Load any provider overrides from the configuration file providers option # Note: Providers can be pkg, service, user or group - not to be confused # with cloud providers. providers = opts.get('providers', False) if providers and isinstance(providers, dict): for mod in providers: # sometimes providers opts is not to diverge modules but # for other configuration try: funcs = raw_mod(opts, providers[mod], ret) except TypeError: break else: if funcs: for func in funcs: f_key = '{0}{1}'.format(mod, func[func.rindex('.'):]) ret[f_key] = funcs[func] if notify: evt = salt.utils.event.get_event('minion', opts=opts, listen=False) evt.fire_event({'complete': True}, tag=salt.defaults.events.MINION_MOD_COMPLETE) return ret def raw_mod(opts, name, functions, mod='modules'): ''' Returns a single module loaded raw and bypassing the __virtual__ function .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') testmod = salt.loader.raw_mod(__opts__, 'test', None) testmod['test.ping']() ''' loader = LazyLoader( _module_dirs(opts, mod, 'module'), opts, tag='rawmodule', virtual_enable=False, pack={'__salt__': functions}, ) # if we don't have the module, return an empty dict if name not in loader.file_mapping: return {} loader._load_module(name) # load a single module (the one passed in) return dict(loader._dict) # return a copy of *just* the funcs for `name` def metaproxy(opts): ''' Return functions used in the meta proxy ''' return LazyLoader( _module_dirs(opts, 'metaproxy'), opts, tag='metaproxy' ) def matchers(opts): ''' Return the matcher services plugins ''' return LazyLoader( _module_dirs(opts, 'matchers'), opts, tag='matchers' ) def engines(opts, functions, runners, utils, proxy=None): ''' Return the master services plugins ''' pack = {'__salt__': functions, '__runners__': runners, '__proxy__': proxy, '__utils__': utils} return LazyLoader( _module_dirs(opts, 'engines'), opts, tag='engines', pack=pack, ) def proxy(opts, functions=None, returners=None, whitelist=None, utils=None): ''' Returns the proxy module for this salt-proxy-minion ''' ret = LazyLoader( _module_dirs(opts, 'proxy'), opts, tag='proxy', pack={'__salt__': functions, '__ret__': returners, '__utils__': utils}, ) ret.pack['__proxy__'] = ret return ret def returners(opts, functions, whitelist=None, context=None, proxy=None): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'returners', 'returner'), opts, tag='returner', whitelist=whitelist, pack={'__salt__': functions, '__context__': context, '__proxy__': proxy or {}}, ) def utils(opts, whitelist=None, context=None, proxy=proxy): ''' Returns the utility modules ''' return LazyLoader( _module_dirs(opts, 'utils', ext_type_dirs='utils_dirs'), opts, tag='utils', whitelist=whitelist, pack={'__context__': context, '__proxy__': proxy or {}}, ) def pillars(opts, functions, context=None): ''' Returns the pillars modules ''' ret = LazyLoader(_module_dirs(opts, 'pillar'), opts, tag='pillar', pack={'__salt__': functions, '__context__': context, '__utils__': utils(opts)}) ret.pack['__ext_pillar__'] = ret return FilterDictWrapper(ret, '.ext_pillar') def tops(opts): ''' Returns the tops modules ''' if 'master_tops' not in opts: return {} whitelist = list(opts['master_tops'].keys()) ret = LazyLoader( _module_dirs(opts, 'tops', 'top'), opts, tag='top', whitelist=whitelist, ) return FilterDictWrapper(ret, '.top') def wheels(opts, whitelist=None, context=None): ''' Returns the wheels modules ''' if context is None: context = {} return LazyLoader( _module_dirs(opts, 'wheel'), opts, tag='wheel', whitelist=whitelist, pack={'__context__': context}, ) def outputters(opts): ''' Returns the outputters modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only outputters present in the keyspace ''' ret = LazyLoader( _module_dirs(opts, 'output', ext_type_dirs='outputter_dirs'), opts, tag='output', ) wrapped_ret = FilterDictWrapper(ret, '.output') # TODO: this name seems terrible... __salt__ should always be execution mods ret.pack['__salt__'] = wrapped_ret return wrapped_ret def serializers(opts): ''' Returns the serializers modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only serializers present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'serializers'), opts, tag='serializers', ) def eauth_tokens(opts): ''' Returns the tokens modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only token backends present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'tokens'), opts, tag='tokens', ) def auth(opts, whitelist=None): ''' Returns the auth modules :param dict opts: The Salt options dictionary :returns: LazyLoader ''' return LazyLoader( _module_dirs(opts, 'auth'), opts, tag='auth', whitelist=whitelist, pack={'__salt__': minion_mods(opts)}, ) def fileserver(opts, backends): ''' Returns the file server modules ''' return LazyLoader(_module_dirs(opts, 'fileserver'), opts, tag='fileserver', whitelist=backends, pack={'__utils__': utils(opts)}) def roster(opts, runner=None, utils=None, whitelist=None): ''' Returns the roster modules ''' return LazyLoader( _module_dirs(opts, 'roster'), opts, tag='roster', whitelist=whitelist, pack={ '__runner__': runner, '__utils__': utils, }, ) def thorium(opts, functions, runners): ''' Load the thorium runtime modules ''' pack = {'__salt__': functions, '__runner__': runners, '__context__': {}} ret = LazyLoader(_module_dirs(opts, 'thorium'), opts, tag='thorium', pack=pack) ret.pack['__thorium__'] = ret return ret def states(opts, functions, utils, serializers, whitelist=None, proxy=None, context=None): ''' Returns the state modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') statemods = salt.loader.states(__opts__, None, None) ''' if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'states'), opts, tag='states', pack={'__salt__': functions, '__proxy__': proxy or {}}, whitelist=whitelist, ) ret.pack['__states__'] = ret ret.pack['__utils__'] = utils ret.pack['__serializers__'] = serializers ret.pack['__context__'] = context return ret def beacons(opts, functions, context=None, proxy=None): ''' Load the beacon modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. ''' return LazyLoader( _module_dirs(opts, 'beacons'), opts, tag='beacons', pack={'__context__': context, '__salt__': functions, '__proxy__': proxy or {}}, virtual_funcs=[], ) def log_handlers(opts): ''' Returns the custom logging handler modules :param dict opts: The Salt options dictionary ''' ret = LazyLoader( _module_dirs( opts, 'log_handlers', int_type='handlers', base_path=os.path.join(SALT_BASE_PATH, 'log'), ), opts, tag='log_handlers', ) return FilterDictWrapper(ret, '.setup_handlers') def ssh_wrapper(opts, functions=None, context=None): ''' Returns the custom logging handler modules ''' return LazyLoader( _module_dirs( opts, 'wrapper', base_path=os.path.join(SALT_BASE_PATH, os.path.join('client', 'ssh')), ), opts, tag='wrapper', pack={ '__salt__': functions, '__grains__': opts.get('grains', {}), '__pillar__': opts.get('pillar', {}), '__context__': context, }, ) def render(opts, functions, states=None, proxy=None, context=None): ''' Returns the render modules ''' if context is None: context = {} pack = {'__salt__': functions, '__grains__': opts.get('grains', {}), '__context__': context} if states: pack['__states__'] = states pack['__proxy__'] = proxy or {} ret = LazyLoader( _module_dirs( opts, 'renderers', 'render', ext_type_dirs='render_dirs', ), opts, tag='render', pack=pack, ) rend = FilterDictWrapper(ret, '.render') if not check_render_pipe_str(opts['renderer'], rend, opts['renderer_blacklist'], opts['renderer_whitelist']): err = ('The renderer {0} is unavailable, this error is often because ' 'the needed software is unavailable'.format(opts['renderer'])) log.critical(err) raise LoaderError(err) return rend def grain_funcs(opts, proxy=None): ''' Returns the grain functions .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') grainfuncs = salt.loader.grain_funcs(__opts__) ''' ret = LazyLoader( _module_dirs( opts, 'grains', 'grain', ext_type_dirs='grains_dirs', ), opts, tag='grains', ) ret.pack['__utils__'] = utils(opts, proxy=proxy) return ret def grains(opts, force_refresh=False, proxy=None): ''' Return the functions for the dynamic grains and the values for the static grains. Since grains are computed early in the startup process, grains functions do not have __salt__ or __proxy__ available. At proxy-minion startup, this function is called with the proxymodule LazyLoader object so grains functions can communicate with their controlled device. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) print __grains__['id'] ''' # Need to re-import salt.config, somehow it got lost when a minion is starting import salt.config # if we have no grains, lets try loading from disk (TODO: move to decorator?) cfn = os.path.join( opts['cachedir'], 'grains.cache.p' ) if not force_refresh and opts.get('grains_cache', False): cached_grains = _load_cached_grains(opts, cfn) if cached_grains: return cached_grains else: log.debug('Grains refresh requested. Refreshing grains.') if opts.get('skip_grains', False): return {} grains_deep_merge = opts.get('grains_deep_merge', False) is True if 'conf_file' in opts: pre_opts = {} pre_opts.update(salt.config.load_config( opts['conf_file'], 'SALT_MINION_CONFIG', salt.config.DEFAULT_MINION_OPTS['conf_file'] )) default_include = pre_opts.get( 'default_include', opts['default_include'] ) include = pre_opts.get('include', []) pre_opts.update(salt.config.include_config( default_include, opts['conf_file'], verbose=False )) pre_opts.update(salt.config.include_config( include, opts['conf_file'], verbose=True )) if 'grains' in pre_opts: opts['grains'] = pre_opts['grains'] else: opts['grains'] = {} else: opts['grains'] = {} grains_data = {} blist = opts.get('grains_blacklist', []) funcs = grain_funcs(opts, proxy=proxy) if force_refresh: # if we refresh, lets reload grain modules funcs.clear() # Run core grains for key in funcs: if not key.startswith('core.'): continue log.trace('Loading %s grain', key) ret = funcs[key]() if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) # Run the rest of the grains for key in funcs: if key.startswith('core.') or key == '_errors': continue try: # Grains are loaded too early to take advantage of the injected # __proxy__ variable. Pass an instance of that LazyLoader # here instead to grains functions if the grains functions take # one parameter. Then the grains can have access to the # proxymodule for retrieving information from the connected # device. log.trace('Loading %s grain', key) parameters = salt.utils.args.get_function_argspec(funcs[key]).args kwargs = {} if 'proxy' in parameters: kwargs['proxy'] = proxy if 'grains' in parameters: kwargs['grains'] = grains_data ret = funcs[key](**kwargs) except Exception: if salt.utils.platform.is_proxy(): log.info('The following CRITICAL message may not be an error; the proxy may not be completely established yet.') log.critical( 'Failed to load grains defined in grain file %s in ' 'function %s, error:\n', key, funcs[key], exc_info=True ) continue if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) if opts.get('proxy_merge_grains_in_module', True) and proxy: try: proxytype = proxy.opts['proxy']['proxytype'] if proxytype + '.grains' in proxy: if proxytype + '.initialized' in proxy and proxy[proxytype + '.initialized'](): try: proxytype = proxy.opts['proxy']['proxytype'] ret = proxy[proxytype + '.grains']() if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) except Exception: log.critical('Failed to run proxy\'s grains function!', exc_info=True ) except KeyError: pass grains_data.update(opts['grains']) # Write cache if enabled if opts.get('grains_cache', False): with salt.utils.files.set_umask(0o077): try: if salt.utils.platform.is_windows(): # Late import import salt.modules.cmdmod # Make sure cache file isn't read-only salt.modules.cmdmod._run_quiet('attrib -R "{0}"'.format(cfn)) with salt.utils.files.fopen(cfn, 'w+b') as fp_: try: serial = salt.payload.Serial(opts) serial.dump(grains_data, fp_) except TypeError as e: log.error('Failed to serialize grains cache: %s', e) raise # re-throw for cleanup except Exception as e: log.error('Unable to write to grains cache file %s: %s', cfn, e) # Based on the original exception, the file may or may not have been # created. If it was, we will remove it now, as the exception means # the serialized data is not to be trusted, no matter what the # exception is. if os.path.isfile(cfn): os.unlink(cfn) if grains_deep_merge: salt.utils.dictupdate.update(grains_data, opts['grains']) else: grains_data.update(opts['grains']) return salt.utils.data.decode(grains_data, preserve_tuples=True) # TODO: get rid of? Does anyone use this? You should use raw() instead def call(fun, **kwargs): ''' Directly call a function inside a loader directory ''' args = kwargs.get('args', []) dirs = kwargs.get('dirs', []) funcs = LazyLoader( [os.path.join(SALT_BASE_PATH, 'modules')] + dirs, None, tag='modules', virtual_enable=False, ) return funcs[fun](*args) def runner(opts, utils=None, context=None, whitelist=None): ''' Directly call a function inside a loader directory ''' if utils is None: utils = {} if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'runners', 'runner', ext_type_dirs='runner_dirs'), opts, tag='runners', pack={'__utils__': utils, '__context__': context}, whitelist=whitelist, ) # TODO: change from __salt__ to something else, we overload __salt__ too much ret.pack['__salt__'] = ret return ret def queues(opts): ''' Directly call a function inside a loader directory ''' return LazyLoader( _module_dirs(opts, 'queues', 'queue', ext_type_dirs='queue_dirs'), opts, tag='queues', ) def sdb(opts, functions=None, whitelist=None, utils=None): ''' Make a very small database call ''' if utils is None: utils = {} return LazyLoader( _module_dirs(opts, 'sdb'), opts, tag='sdb', pack={ '__sdb__': functions, '__opts__': opts, '__utils__': utils, '__salt__': minion_mods(opts, utils), }, whitelist=whitelist, ) def pkgdb(opts): ''' Return modules for SPM's package database .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgdb', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgdb' ) def pkgfiles(opts): ''' Return modules for SPM's file handling .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgfiles', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgfiles' ) def clouds(opts): ''' Return the cloud functions ''' # Let's bring __active_provider_name__, defaulting to None, to all cloud # drivers. This will get temporarily updated/overridden with a context # manager when needed. functions = LazyLoader( _module_dirs(opts, 'clouds', 'cloud', base_path=os.path.join(SALT_BASE_PATH, 'cloud'), int_type='clouds'), opts, tag='clouds', pack={'__utils__': salt.loader.utils(opts), '__active_provider_name__': None}, ) for funcname in LIBCLOUD_FUNCS_NOT_SUPPORTED: log.trace( '\'%s\' has been marked as not supported. Removing from the ' 'list of supported cloud functions', funcname ) functions.pop(funcname, None) return functions def netapi(opts): ''' Return the network api functions ''' return LazyLoader( _module_dirs(opts, 'netapi'), opts, tag='netapi', ) def executors(opts, functions=None, context=None, proxy=None): ''' Returns the executor modules ''' executors = LazyLoader( _module_dirs(opts, 'executors', 'executor'), opts, tag='executor', pack={'__salt__': functions, '__context__': context or {}, '__proxy__': proxy or {}}, ) executors.pack['__executors__'] = executors return executors def cache(opts, serial): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'cache', 'cache'), opts, tag='cache', pack={'__opts__': opts, '__context__': {'serial': serial}}, ) def _generate_module(name): if name in sys.modules: return code = "'''Salt loaded {0} parent module'''".format(name.split('.')[-1]) # ModuleType can't accept a unicode type on PY2 module = types.ModuleType(str(name)) # future lint: disable=blacklisted-function exec(code, module.__dict__) sys.modules[name] = module def _mod_type(module_path): if module_path.startswith(SALT_BASE_PATH): return 'int' return 'ext' def _inject_into_mod(mod, name, value, force_lock=False): ''' Inject a variable into a module. This is used to inject "globals" like ``__salt__``, ``__pillar``, or ``grains``. Instead of injecting the value directly, a ``ThreadLocalProxy`` is created. If such a proxy is already present under the specified name, it is updated with the new value. This update only affects the current thread, so that the same name can refer to different values depending on the thread of execution. This is important for data that is not truly global. For example, pillar data might be dynamically overriden through function parameters and thus the actual values available in pillar might depend on the thread that is calling a module. mod: module object into which the value is going to be injected. name: name of the variable that is injected into the module. value: value that is injected into the variable. The value is not injected directly, but instead set as the new reference of the proxy that has been created for the variable. force_lock: whether the lock should be acquired before checking whether a proxy object for the specified name has already been injected into the module. If ``False`` (the default), this function checks for the module's variable without acquiring the lock and only acquires the lock if a new proxy has to be created and injected. ''' old_value = getattr(mod, name, None) # We use a double-checked locking scheme in order to avoid taking the lock # when a proxy object has already been injected. # In most programming languages, double-checked locking is considered # unsafe when used without explicit memory barriers because one might read # an uninitialized value. In CPython it is safe due to the global # interpreter lock (GIL). In Python implementations that do not have the # GIL, it could be unsafe, but at least Jython also guarantees that (for # Python objects) memory is not corrupted when writing and reading without # explicit synchronization # (http://www.jython.org/jythonbook/en/1.0/Concurrency.html). # Please note that in order to make this code safe in a runtime environment # that does not make this guarantees, it is not sufficient. The # ThreadLocalProxy must also be created with fallback_to_shared set to # False or a lock must be added to the ThreadLocalProxy. if force_lock: with _inject_into_mod.lock: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: setattr(mod, name, ThreadLocalProxy(value, True)) else: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: _inject_into_mod(mod, name, value, True) # Lock used when injecting globals. This is needed to avoid a race condition # when two threads try to load the same module concurrently. This must be # outside the loader because there might be more than one loader for the same # namespace. _inject_into_mod.lock = threading.RLock() # TODO: move somewhere else? class FilterDictWrapper(MutableMapping): ''' Create a dict which wraps another dict with a specific key suffix on get This is to replace "filter_load" ''' def __init__(self, d, suffix): self._dict = d self.suffix = suffix def __setitem__(self, key, val): self._dict[key] = val def __delitem__(self, key): del self._dict[key] def __getitem__(self, key): return self._dict[key + self.suffix] def __len__(self): return len(self._dict) def __iter__(self): for key in self._dict: if key.endswith(self.suffix): yield key.replace(self.suffix, '') class LazyLoader(salt.utils.lazy.LazyDict): ''' A pseduo-dictionary which has a set of keys which are the name of the module and function, delimited by a dot. When the value of the key is accessed, the function is then loaded from disk and into memory. .. note:: Iterating over keys will cause all modules to be loaded. :param list module_dirs: A list of directories on disk to search for modules :param dict opts: The salt options dictionary. :param str tag: The tag for the type of module to load :param func mod_type_check: A function which can be used to verify files :param dict pack: A dictionary of function to be packed into modules as they are loaded :param list whitelist: A list of modules to whitelist :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules. :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality. If not true, the module will not load. :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values are function references themselves which are loaded on-demand. # TODO: - move modules_max_memory into here - singletons (per tag) ''' mod_dict_class = salt.utils.odict.OrderedDict def __init__(self, module_dirs, opts=None, tag='module', loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, proxy=None, virtual_funcs=None, ): # pylint: disable=W0231 ''' In pack, if any of the values are None they will be replaced with an empty context-specific dict ''' self.inject_globals = {} self.pack = {} if pack is None else pack if opts is None: opts = {} threadsafety = not opts.get('multiprocessing') self.context_dict = salt.utils.context.ContextDict(threadsafe=threadsafety) self.opts = self.__prep_mod_opts(opts) self.module_dirs = module_dirs self.tag = tag self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME self.mod_type_check = mod_type_check or _mod_type if '__context__' not in self.pack: self.pack['__context__'] = None for k, v in six.iteritems(self.pack): if v is None: # if the value of a pack is None, lets make an empty dict value = self.context_dict.get(k, {}) if isinstance(value, ThreadLocalProxy): value = ThreadLocalProxy.unproxy(value) self.context_dict[k] = value self.pack[k] = salt.utils.context.NamespacedDictWrapper(self.context_dict, k) self.whitelist = whitelist self.virtual_enable = virtual_enable self.initial_load = True # names of modules that we don't have (errors, __virtual__, etc.) self.missing_modules = {} # mapping of name -> error self.loaded_modules = {} # mapping of module_name -> dict_of_functions self.loaded_files = set() # TODO: just remove them from file_mapping? self.static_modules = static_modules if static_modules else [] if virtual_funcs is None: virtual_funcs = [] self.virtual_funcs = virtual_funcs self.disabled = set( self.opts.get( 'disable_{0}{1}'.format( self.tag, '' if self.tag[-1] == 's' else 's' ), [] ) ) # A map of suffix to description for imp self.suffix_map = {} # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [''] for (suffix, mode, kind) in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) self._lock = threading.RLock() self._refresh_file_mapping() super(LazyLoader, self).__init__() # late init the lazy loader # create all of the import namespaces _generate_module('{0}.int'.format(self.loaded_base_name)) _generate_module('{0}.int.{1}'.format(self.loaded_base_name, tag)) _generate_module('{0}.ext'.format(self.loaded_base_name)) _generate_module('{0}.ext.{1}'.format(self.loaded_base_name, tag)) def __getitem__(self, item): ''' Override the __getitem__ in order to decorate the returned function if we need to last-minute inject globals ''' func = super(LazyLoader, self).__getitem__(item) if self.inject_globals: return global_injector_decorator(self.inject_globals)(func) else: return func def __getattr__(self, mod_name): ''' Allow for "direct" attribute access-- this allows jinja templates to access things like `salt.test.ping()` ''' if mod_name in ('__getstate__', '__setstate__'): return object.__getattribute__(self, mod_name) # if we have an attribute named that, lets return it. try: return object.__getattr__(self, mod_name) # pylint: disable=no-member except AttributeError: pass # otherwise we assume its jinja template access if mod_name not in self.loaded_modules and not self.loaded: for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and mod_name in self.loaded_modules: break if mod_name in self.loaded_modules: return self.loaded_modules[mod_name] else: raise AttributeError(mod_name) def missing_fun_string(self, function_name): ''' Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ''' mod_name = function_name.split('.')[0] if mod_name in self.loaded_modules: return '\'{0}\' is not available.'.format(function_name) else: try: reason = self.missing_modules[mod_name] except KeyError: return '\'{0}\' is not available.'.format(function_name) else: if reason is not None: return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason) else: return '\'{0}\' __virtual__ returned False'.format(mod_name) def _refresh_file_mapping(self): ''' refresh the mapping of the FS on disk ''' # map of suffix to description for imp if self.opts.get('cython_enable', True) is True: try: global pyximport pyximport = __import__('pyximport') # pylint: disable=import-error pyximport.install() # add to suffix_map so file_mapping will pick it up self.suffix_map['.pyx'] = tuple() except ImportError: log.info('Cython is enabled in the options but not present ' 'in the system path. Skipping Cython modules.') # Allow for zipimport of modules if self.opts.get('enable_zip_modules', True) is True: self.suffix_map['.zip'] = tuple() # allow for module dirs if USE_IMPORTLIB: self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY) else: self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY) # create mapping of filename (without suffix) to (path, suffix) # The files are added in order of priority, so order *must* be retained. self.file_mapping = salt.utils.odict.OrderedDict() opt_match = [] def _replace_pre_ext(obj): ''' Hack so we can get the optimization level that we replaced (if any) out of the re.sub call below. We use a list here because it is a persistent data structure that we will be able to access after re.sub is called. ''' opt_match.append(obj) return '' for mod_dir in self.module_dirs: try: # Make sure we have a sorted listdir in order to have # expectable override results files = sorted( x for x in os.listdir(mod_dir) if x != '__pycache__' ) except OSError: continue # Next mod_dir if six.PY3: try: pycache_files = [ os.path.join('__pycache__', x) for x in sorted(os.listdir(os.path.join(mod_dir, '__pycache__'))) ] except OSError: pass else: files.extend(pycache_files) for filename in files: try: dirname, basename = os.path.split(filename) if basename.startswith('_'): # skip private modules # log messages omitted for obviousness continue # Next filename f_noext, ext = os.path.splitext(basename) if six.PY3: f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext) try: opt_level = int( opt_match.pop().group(1).rsplit('-', 1)[-1] ) except (AttributeError, IndexError, ValueError): # No regex match or no optimization level matched opt_level = 0 try: opt_index = self.opts['optimization_order'].index(opt_level) except KeyError: log.trace( 'Disallowed optimization level %d for module ' 'name \'%s\', skipping. Add %d to the ' '\'optimization_order\' config option if you ' 'do not want to ignore this optimization ' 'level.', opt_level, f_noext, opt_level ) continue else: # Optimization level not reflected in filename on PY2 opt_index = 0 # make sure it is a suffix we support if ext not in self.suffix_map: continue # Next filename if f_noext in self.disabled: log.trace( 'Skipping %s, it is disabled by configuration', filename ) continue # Next filename fpath = os.path.join(mod_dir, filename) # if its a directory, lets allow us to load that if ext == '': # is there something __init__? subfiles = os.listdir(fpath) for suffix in self.suffix_order: if '' == suffix: continue # Next suffix (__init__ must have a suffix) init_file = '__init__{0}'.format(suffix) if init_file in subfiles: break else: continue # Next filename try: curr_ext = self.file_mapping[f_noext][1] curr_opt_index = self.file_mapping[f_noext][2] except KeyError: pass else: if '' in (curr_ext, ext) and curr_ext != ext: log.error( 'Module/package collision: \'%s\' and \'%s\'', fpath, self.file_mapping[f_noext][0] ) if six.PY3 and ext == '.pyc' and curr_ext == '.pyc': # Check the optimization level if opt_index >= curr_opt_index: # Module name match, but a higher-priority # optimization level was already matched, skipping. continue elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext): # Match found but a higher-priorty match already # exists, so skip this. continue if six.PY3 and not dirname and ext == '.pyc': # On Python 3, we should only load .pyc files from the # __pycache__ subdirectory (i.e. when dirname is not an # empty string). continue # Made it this far - add it self.file_mapping[f_noext] = (fpath, ext, opt_index) except OSError: continue for smod in self.static_modules: f_noext = smod.split('.')[-1] self.file_mapping[f_noext] = (smod, '.o', 0) def clear(self): ''' Clear the dict ''' with self._lock: super(LazyLoader, self).clear() # clear the lazy loader self.loaded_files = set() self.missing_modules = {} self.loaded_modules = {} # if we have been loaded before, lets clear the file mapping since # we obviously want a re-do if hasattr(self, 'opts'): self._refresh_file_mapping() self.initial_load = False def __prep_mod_opts(self, opts): ''' Strip out of the opts any logger instance ''' if '__grains__' not in self.pack: grains = opts.get('grains', {}) if isinstance(grains, ThreadLocalProxy): grains = ThreadLocalProxy.unproxy(grains) self.context_dict['grains'] = grains self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains') if '__pillar__' not in self.pack: pillar = opts.get('pillar', {}) if isinstance(pillar, ThreadLocalProxy): pillar = ThreadLocalProxy.unproxy(pillar) self.context_dict['pillar'] = pillar self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar') mod_opts = {} for key, val in list(opts.items()): if key == 'logger': continue mod_opts[key] = val return mod_opts def _iter_files(self, mod_name): ''' Iterate over all file_mapping files in order of closeness to mod_name ''' # do we have an exact match? if mod_name in self.file_mapping: yield mod_name # do we have a partial match? for k in self.file_mapping: if mod_name in k: yield k # anyone else? Bueller? for k in self.file_mapping: if mod_name not in k: yield k def _reload_submodules(self, mod): submodules = ( getattr(mod, sname) for sname in dir(mod) if isinstance(getattr(mod, sname), mod.__class__) ) # reload only custom "sub"modules for submodule in submodules: # it is a submodule if the name is in a namespace under mod if submodule.__name__.startswith(mod.__name__ + '.'): reload_module(submodule) self._reload_submodules(submodule) def _load_module(self, name): mod = None fpath, suffix = self.file_mapping[name][:2] self.loaded_files.add(name) fpath_dirname = os.path.dirname(fpath) try: sys.path.append(fpath_dirname) if suffix == '.pyx': mod = pyximport.load_module(name, fpath, tempfile.gettempdir()) elif suffix == '.o': top_mod = __import__(fpath, globals(), locals(), []) comps = fpath.split('.') if len(comps) < 2: mod = top_mod else: mod = top_mod for subname in comps[1:]: mod = getattr(mod, subname) elif suffix == '.zip': mod = zipimporter(fpath).load_module(name) else: desc = self.suffix_map[suffix] # if it is a directory, we don't open a file try: mod_namespace = '.'.join(( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name)) except TypeError: mod_namespace = '{0}.{1}.{2}.{3}'.format( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name) if suffix == '': if USE_IMPORTLIB: # pylint: disable=no-member # Package directory, look for __init__ loader_details = [ (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES), (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES), (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), ] file_finder = importlib.machinery.FileFinder( fpath_dirname, *loader_details ) spec = file_finder.find_spec(mod_namespace) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: mod = imp.load_module(mod_namespace, None, fpath, desc) # reload all submodules if necessary if not self.initial_load: self._reload_submodules(mod) else: if USE_IMPORTLIB: # pylint: disable=no-member loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath) spec = importlib.util.spec_from_file_location( mod_namespace, fpath, loader=loader ) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() #mod = importlib.util.module_from_spec(spec) #spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: with salt.utils.files.fopen(fpath, desc[1]) as fn_: mod = imp.load_module(mod_namespace, fn_, fpath, desc) except IOError: raise except ImportError as exc: if 'magic number' in six.text_type(exc): error_msg = 'Failed to import {0} {1}. Bad magic number. If migrating from Python2 to Python3, remove all .pyc files and try again.'.format(self.tag, name) log.warning(error_msg) self.missing_modules[name] = error_msg log.debug( 'Failed to import %s %s:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = exc return False except Exception as error: log.error( 'Failed to import %s %s, this is due most likely to a ' 'syntax error:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False except SystemExit as error: try: fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1] except Exception: pass else: tgt_fn = os.path.join('salt', 'utils', 'process.py') if fn_.endswith(tgt_fn) and '_handle_signals' in caller: # Race conditon, SIGTERM or SIGINT received while loader # was in process of loading a module. Call sys.exit to # ensure that the process is killed. sys.exit(salt.defaults.exitcodes.EX_OK) log.error( 'Failed to import %s %s as the module called exit()\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False finally: sys.path.remove(fpath_dirname) if hasattr(mod, '__opts__'): mod.__opts__.update(self.opts) else: mod.__opts__ = self.opts # pack whatever other globals we were asked to for p_name, p_value in six.iteritems(self.pack): _inject_into_mod(mod, p_name, p_value) module_name = mod.__name__.rsplit('.', 1)[-1] # Call a module's initialization method if it exists module_init = getattr(mod, '__init__', None) if inspect.isfunction(module_init): try: module_init(self.opts) except TypeError as e: log.error(e) except Exception: err_string = '__init__ failed' log.debug( 'Error loading %s.%s: %s', self.tag, module_name, err_string, exc_info=True ) self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False # if virtual modules are enabled, we need to look for the # __virtual__() function inside that module and run it. if self.virtual_enable: virtual_funcs_to_process = ['__virtual__'] + self.virtual_funcs for virtual_func in virtual_funcs_to_process: virtual_ret, module_name, virtual_err, virtual_aliases = \ self._process_virtual(mod, module_name, virtual_func) if virtual_err is not None: log.trace( 'Error loading %s.%s: %s', self.tag, module_name, virtual_err ) # if _process_virtual returned a non-True value then we are # supposed to not process this module if virtual_ret is not True and module_name not in self.missing_modules: # If a module has information about why it could not be loaded, record it self.missing_modules[module_name] = virtual_err self.missing_modules[name] = virtual_err return False else: virtual_aliases = () # If this is a proxy minion then MOST modules cannot work. Therefore, require that # any module that does work with salt-proxy-minion define __proxyenabled__ as a list # containing the names of the proxy types that the module supports. # # Render modules and state modules are OK though if 'proxy' in self.opts: if self.tag in ['grains', 'proxy']: if not hasattr(mod, '__proxyenabled__') or \ (self.opts['proxy']['proxytype'] not in mod.__proxyenabled__ and '*' not in mod.__proxyenabled__): err_string = 'not a proxy_minion enabled module' self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False if getattr(mod, '__load__', False) is not False: log.info( 'The functions from module \'%s\' are being loaded from the ' 'provided __load__ attribute', module_name ) # If we had another module by the same virtual name, we should put any # new functions under the existing dictionary. mod_names = [module_name] + list(virtual_aliases) mod_dict = dict(( (x, self.loaded_modules.get(x, self.mod_dict_class())) for x in mod_names )) for attr in getattr(mod, '__load__', dir(mod)): if attr.startswith('_') and attr != '__call__': # private functions are skipped, # except __call__ which is default entrance # for multi-function batch-like state syntax continue func = getattr(mod, attr) if not inspect.isfunction(func) and not isinstance(func, functools.partial): # Not a function!? Skip it!!! continue # Let's get the function name. # If the module has the __func_alias__ attribute, it must be a # dictionary mapping in the form of(key -> value): # <real-func-name> -> <desired-func-name> # # It default's of course to the found callable attribute name # if no alias is defined. funcname = getattr(mod, '__func_alias__', {}).get(attr, attr) for tgt_mod in mod_names: try: full_funcname = '.'.join((tgt_mod, funcname)) except TypeError: full_funcname = '{0}.{1}'.format(tgt_mod, funcname) # Save many references for lookups # Careful not to overwrite existing (higher priority) functions if full_funcname not in self._dict: self._dict[full_funcname] = func if funcname not in mod_dict[tgt_mod]: setattr(mod_dict[tgt_mod], funcname, func) mod_dict[tgt_mod][funcname] = func self._apply_outputter(func, mod) # enforce depends try: Depends.enforce_dependencies(self._dict, self.tag) except RuntimeError as exc: log.info( 'Depends.enforce_dependencies() failed for the following ' 'reason: %s', exc ) for tgt_mod in mod_names: self.loaded_modules[tgt_mod] = mod_dict[tgt_mod] return True def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise KeyError('The key \'{0}\' should contain a \'.\''.format(key)) mod_name, _ = key.split('.', 1) with self._lock: # It is possible that the key is in the dictionary after # acquiring the lock due to another thread loading it. if mod_name in self.missing_modules or key in self._dict: return True # if the modulename isn't in the whitelist, don't bother if self.whitelist and mod_name not in self.whitelist: log.error( 'Failed to load function %s because its module (%s) is ' 'not in the whitelist: %s', key, mod_name, self.whitelist ) raise KeyError(key) def _inner_load(mod_name): for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and key in self._dict: return True return False # try to load the module ret = None reloaded = False # re-scan up to once, IOErrors or a failed load cause re-scans of the # filesystem while True: try: ret = _inner_load(mod_name) if not reloaded and ret is not True: self._refresh_file_mapping() reloaded = True continue break except IOError: if not reloaded: self._refresh_file_mapping() reloaded = True continue return ret def _load_all(self): ''' Load all of them ''' with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True def reload_modules(self): with self._lock: self.loaded_files = set() self._load_all() def _apply_outputter(self, func, mod): ''' Apply the __outputter__ variable to the functions ''' if hasattr(mod, '__outputter__'): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__] def _process_virtual(self, mod, module_name, virtual_func='__virtual__'): ''' Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1] ''' # The __virtual__ function will return either a True or False value. # If it returns a True value it can also set a module level attribute # named __virtualname__ with the name that the module should be # referred to as. # # This allows us to have things like the pkg module working on all # platforms under the name 'pkg'. It also allows for modules like # augeas_cfg to be referred to as 'augeas', which would otherwise have # namespace collisions. And finally it allows modules to return False # if they are not intended to run on the given platform or are missing # dependencies. virtual_aliases = getattr(mod, '__virtual_aliases__', tuple()) try: error_reason = None if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__): try: start = time.time() virtual = getattr(mod, virtual_func)() if isinstance(virtual, tuple): error_reason = virtual[1] virtual = virtual[0] if self.opts.get('virtual_timer', False): end = time.time() - start msg = 'Virtual function took {0} seconds for {1}'.format( end, module_name) log.warning(msg) except Exception as exc: error_reason = ( 'Exception raised when processing __virtual__ function' ' for {0}. Module will not be loaded: {1}'.format( mod.__name__, exc)) log.error(error_reason, exc_info_on_loglevel=logging.DEBUG) virtual = None # Get the module's virtual name virtualname = getattr(mod, '__virtualname__', virtual) if not virtual: # if __virtual__() evaluates to False then the module # wasn't meant for this platform or it's not supposed to # load for some other reason. # Some modules might accidentally return None and are # improperly loaded if virtual is None: log.warning( '%s.__virtual__() is wrongly returning `None`. ' 'It should either return `True`, `False` or a new ' 'name. If you\'re the developer of the module ' '\'%s\', please fix this.', mod.__name__, module_name ) return (False, module_name, error_reason, virtual_aliases) # At this point, __virtual__ did not return a # boolean value, let's check for deprecated usage # or module renames if virtual is not True and module_name != virtual: # The module is renaming itself. Updating the module name # with the new name log.trace('Loaded %s as virtual %s', module_name, virtual) if virtualname != virtual: # The __virtualname__ attribute does not match what's # being returned by the __virtual__() function. This # should be considered an error. log.error( 'The module \'%s\' is showing some bad usage. Its ' '__virtualname__ attribute is set to \'%s\' yet the ' '__virtual__() function is returning \'%s\'. These ' 'values should match!', mod.__name__, virtualname, virtual ) module_name = virtualname # If the __virtual__ function returns True and __virtualname__ # is set then use it elif virtual is True and virtualname != module_name: if virtualname is not True: module_name = virtualname except KeyError: # Key errors come out of the virtual function when passing # in incomplete grains sets, these can be safely ignored # and logged to debug, still, it includes the traceback to # help debugging. log.debug('KeyError when loading %s', module_name, exc_info=True) except Exception: # If the module throws an exception during __virtual__() # then log the information and continue to the next. log.error( 'Failed to read the virtual function for %s: %s', self.tag, module_name, exc_info=True ) return (False, module_name, error_reason, virtual_aliases) return (True, module_name, None, virtual_aliases) def global_injector_decorator(inject_globals): ''' Decorator used by the LazyLoader to inject globals into a function at execute time. globals Dictionary with global variables to inject ''' def inner_decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): with salt.utils.context.func_globals_inject(f, **inject_globals): return f(*args, **kwargs) return wrapper return inner_decorator
saltstack/salt
salt/loader.py
grains
python
def grains(opts, force_refresh=False, proxy=None): ''' Return the functions for the dynamic grains and the values for the static grains. Since grains are computed early in the startup process, grains functions do not have __salt__ or __proxy__ available. At proxy-minion startup, this function is called with the proxymodule LazyLoader object so grains functions can communicate with their controlled device. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) print __grains__['id'] ''' # Need to re-import salt.config, somehow it got lost when a minion is starting import salt.config # if we have no grains, lets try loading from disk (TODO: move to decorator?) cfn = os.path.join( opts['cachedir'], 'grains.cache.p' ) if not force_refresh and opts.get('grains_cache', False): cached_grains = _load_cached_grains(opts, cfn) if cached_grains: return cached_grains else: log.debug('Grains refresh requested. Refreshing grains.') if opts.get('skip_grains', False): return {} grains_deep_merge = opts.get('grains_deep_merge', False) is True if 'conf_file' in opts: pre_opts = {} pre_opts.update(salt.config.load_config( opts['conf_file'], 'SALT_MINION_CONFIG', salt.config.DEFAULT_MINION_OPTS['conf_file'] )) default_include = pre_opts.get( 'default_include', opts['default_include'] ) include = pre_opts.get('include', []) pre_opts.update(salt.config.include_config( default_include, opts['conf_file'], verbose=False )) pre_opts.update(salt.config.include_config( include, opts['conf_file'], verbose=True )) if 'grains' in pre_opts: opts['grains'] = pre_opts['grains'] else: opts['grains'] = {} else: opts['grains'] = {} grains_data = {} blist = opts.get('grains_blacklist', []) funcs = grain_funcs(opts, proxy=proxy) if force_refresh: # if we refresh, lets reload grain modules funcs.clear() # Run core grains for key in funcs: if not key.startswith('core.'): continue log.trace('Loading %s grain', key) ret = funcs[key]() if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) # Run the rest of the grains for key in funcs: if key.startswith('core.') or key == '_errors': continue try: # Grains are loaded too early to take advantage of the injected # __proxy__ variable. Pass an instance of that LazyLoader # here instead to grains functions if the grains functions take # one parameter. Then the grains can have access to the # proxymodule for retrieving information from the connected # device. log.trace('Loading %s grain', key) parameters = salt.utils.args.get_function_argspec(funcs[key]).args kwargs = {} if 'proxy' in parameters: kwargs['proxy'] = proxy if 'grains' in parameters: kwargs['grains'] = grains_data ret = funcs[key](**kwargs) except Exception: if salt.utils.platform.is_proxy(): log.info('The following CRITICAL message may not be an error; the proxy may not be completely established yet.') log.critical( 'Failed to load grains defined in grain file %s in ' 'function %s, error:\n', key, funcs[key], exc_info=True ) continue if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) if opts.get('proxy_merge_grains_in_module', True) and proxy: try: proxytype = proxy.opts['proxy']['proxytype'] if proxytype + '.grains' in proxy: if proxytype + '.initialized' in proxy and proxy[proxytype + '.initialized'](): try: proxytype = proxy.opts['proxy']['proxytype'] ret = proxy[proxytype + '.grains']() if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) except Exception: log.critical('Failed to run proxy\'s grains function!', exc_info=True ) except KeyError: pass grains_data.update(opts['grains']) # Write cache if enabled if opts.get('grains_cache', False): with salt.utils.files.set_umask(0o077): try: if salt.utils.platform.is_windows(): # Late import import salt.modules.cmdmod # Make sure cache file isn't read-only salt.modules.cmdmod._run_quiet('attrib -R "{0}"'.format(cfn)) with salt.utils.files.fopen(cfn, 'w+b') as fp_: try: serial = salt.payload.Serial(opts) serial.dump(grains_data, fp_) except TypeError as e: log.error('Failed to serialize grains cache: %s', e) raise # re-throw for cleanup except Exception as e: log.error('Unable to write to grains cache file %s: %s', cfn, e) # Based on the original exception, the file may or may not have been # created. If it was, we will remove it now, as the exception means # the serialized data is not to be trusted, no matter what the # exception is. if os.path.isfile(cfn): os.unlink(cfn) if grains_deep_merge: salt.utils.dictupdate.update(grains_data, opts['grains']) else: grains_data.update(opts['grains']) return salt.utils.data.decode(grains_data, preserve_tuples=True)
Return the functions for the dynamic grains and the values for the static grains. Since grains are computed early in the startup process, grains functions do not have __salt__ or __proxy__ available. At proxy-minion startup, this function is called with the proxymodule LazyLoader object so grains functions can communicate with their controlled device. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) print __grains__['id']
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L732-L909
[ "def include_config(include, orig_path, verbose, exit_on_config_errors=False):\n '''\n Parses extra configuration file(s) specified in an include list in the\n main config file.\n '''\n # Protect against empty option\n if not include:\n return {}\n\n if orig_path is None:\n # When the passed path is None, we just want the configuration\n # defaults, not actually loading the whole configuration.\n return {}\n\n if isinstance(include, six.string_types):\n include = [include]\n\n configuration = {}\n for path in include:\n # Allow for includes like ~/foo\n path = os.path.expanduser(path)\n if not os.path.isabs(path):\n path = os.path.join(os.path.dirname(orig_path), path)\n\n # Catch situation where user typos path in configuration; also warns\n # for empty include directory (which might be by design)\n glob_matches = glob.glob(path)\n if not glob_matches:\n if verbose:\n log.warning(\n 'Warning parsing configuration file: \"include\" path/glob '\n \"'%s' matches no files\", path\n )\n\n for fn_ in sorted(glob_matches):\n log.debug('Including configuration from \\'%s\\'', fn_)\n try:\n opts = _read_conf_file(fn_)\n except salt.exceptions.SaltConfigurationError as error:\n log.error(error)\n if exit_on_config_errors:\n sys.exit(salt.defaults.exitcodes.EX_GENERIC)\n else:\n # Initialize default config if we wish to skip config errors\n opts = {}\n schedule = opts.get('schedule', {})\n if schedule and 'schedule' in configuration:\n configuration['schedule'].update(schedule)\n include = opts.get('include', [])\n if include:\n opts.update(include_config(include, fn_, verbose))\n\n salt.utils.dictupdate.update(configuration, opts, True, True)\n\n return configuration\n", "def load_config(path, env_var, default_path=None, exit_on_config_errors=True):\n '''\n Returns configuration dict from parsing either the file described by\n ``path`` or the environment variable described by ``env_var`` as YAML.\n '''\n if path is None:\n # When the passed path is None, we just want the configuration\n # defaults, not actually loading the whole configuration.\n return {}\n\n if default_path is None:\n # This is most likely not being used from salt, i.e., could be salt-cloud\n # or salt-api which have not yet migrated to the new default_path\n # argument. Let's issue a warning message that the environ vars won't\n # work.\n import inspect\n previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)\n log.warning(\n \"The function '%s()' defined in '%s' is not yet using the \"\n \"new 'default_path' argument to `salt.config.load_config()`. \"\n \"As such, the '%s' environment variable will be ignored\",\n previous_frame.function, previous_frame.filename, env_var\n )\n # In this case, maintain old behavior\n default_path = DEFAULT_MASTER_OPTS['conf_file']\n\n # Default to the environment variable path, if it exists\n env_path = os.environ.get(env_var, path)\n if not env_path or not os.path.isfile(env_path):\n env_path = path\n # If non-default path from `-c`, use that over the env variable\n if path != default_path:\n env_path = path\n\n path = env_path\n\n # If the configuration file is missing, attempt to copy the template,\n # after removing the first header line.\n if not os.path.isfile(path):\n template = '{0}.template'.format(path)\n if os.path.isfile(template):\n log.debug('Writing %s based on %s', path, template)\n with salt.utils.files.fopen(path, 'w') as out:\n with salt.utils.files.fopen(template, 'r') as ifile:\n ifile.readline() # skip first line\n out.write(ifile.read())\n\n opts = {}\n\n if salt.utils.validate.path.is_readable(path):\n try:\n opts = _read_conf_file(path)\n opts['conf_file'] = path\n except salt.exceptions.SaltConfigurationError as error:\n log.error(error)\n if exit_on_config_errors:\n sys.exit(salt.defaults.exitcodes.EX_GENERIC)\n else:\n log.debug('Missing configuration file: %s', path)\n\n return opts\n" ]
# -*- coding: utf-8 -*- ''' The Salt loader is the core to Salt's plugin system, the loader scans directories for python loadable code and organizes the code into the plugin interfaces used by Salt. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import sys import time import logging import inspect import tempfile import threading import functools import threading import traceback import types from zipimport import zipimporter # Import salt libs import salt.config import salt.defaults.events import salt.defaults.exitcodes import salt.syspaths import salt.utils.args import salt.utils.context import salt.utils.data import salt.utils.dictupdate import salt.utils.event import salt.utils.files import salt.utils.lazy import salt.utils.odict import salt.utils.platform import salt.utils.versions import salt.utils.stringutils from salt.exceptions import LoaderError from salt.template import check_render_pipe_str from salt.utils.decorators import Depends from salt.utils.thread_local_proxy import ThreadLocalProxy # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import reload_module if sys.version_info[:2] >= (3, 5): import importlib.machinery # pylint: disable=no-name-in-module,import-error import importlib.util # pylint: disable=no-name-in-module,import-error USE_IMPORTLIB = True else: import imp USE_IMPORTLIB = False try: from collections.abc import MutableMapping except ImportError: from collections import MutableMapping try: import pkg_resources HAS_PKG_RESOURCES = True except ImportError: HAS_PKG_RESOURCES = False log = logging.getLogger(__name__) SALT_BASE_PATH = os.path.abspath(salt.syspaths.INSTALL_DIR) LOADED_BASE_NAME = 'salt.loaded' if USE_IMPORTLIB: # pylint: disable=no-member MODULE_KIND_SOURCE = 1 MODULE_KIND_COMPILED = 2 MODULE_KIND_EXTENSION = 3 MODULE_KIND_PKG_DIRECTORY = 5 SUFFIXES = [] for suffix in importlib.machinery.EXTENSION_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_EXTENSION)) for suffix in importlib.machinery.SOURCE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_SOURCE)) for suffix in importlib.machinery.BYTECODE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_COMPILED)) MODULE_KIND_MAP = { MODULE_KIND_SOURCE: importlib.machinery.SourceFileLoader, MODULE_KIND_COMPILED: importlib.machinery.SourcelessFileLoader, MODULE_KIND_EXTENSION: importlib.machinery.ExtensionFileLoader } # pylint: enable=no-member else: SUFFIXES = imp.get_suffixes() PY3_PRE_EXT = \ re.compile(r'\.cpython-{0}{1}(\.opt-[1-9])?'.format(*sys.version_info[:2])) # Because on the cloud drivers we do `from salt.cloud.libcloudfuncs import *` # which simplifies code readability, it adds some unsupported functions into # the driver's module scope. # We list un-supported functions here. These will be removed from the loaded. # TODO: remove the need for this cross-module code. Maybe use NotImplemented LIBCLOUD_FUNCS_NOT_SUPPORTED = ( 'parallels.avail_sizes', 'parallels.avail_locations', 'proxmox.avail_sizes', ) # Will be set to pyximport module at runtime if cython is enabled in config. pyximport = None def static_loader( opts, ext_type, tag, pack=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, filter_name=None, ): funcs = LazyLoader( _module_dirs( opts, ext_type, tag, int_type, ext_dirs, ext_type_dirs, base_path, ), opts, tag=tag, pack=pack, ) ret = {} funcs._load_all() if filter_name: funcs = FilterDictWrapper(funcs, filter_name) for key in funcs: ret[key] = funcs[key] return ret def _format_entrypoint_target(ep): ''' Makes a string describing the target of an EntryPoint object. Base strongly on EntryPoint.__str__(). ''' s = ep.module_name if ep.attrs: s += ':' + '.'.join(ep.attrs) return s def _module_dirs( opts, ext_type, tag=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, ): if tag is None: tag = ext_type sys_types = os.path.join(base_path or SALT_BASE_PATH, int_type or ext_type) ext_types = os.path.join(opts['extension_modules'], ext_type) ext_type_types = [] if ext_dirs: if ext_type_dirs is None: ext_type_dirs = '{0}_dirs'.format(tag) if ext_type_dirs in opts: ext_type_types.extend(opts[ext_type_dirs]) if HAS_PKG_RESOURCES and ext_type_dirs: for entry_point in pkg_resources.iter_entry_points('salt.loader', ext_type_dirs): try: loaded_entry_point = entry_point.load() for path in loaded_entry_point(): ext_type_types.append(path) except Exception as exc: log.error("Error getting module directories from %s: %s", _format_entrypoint_target(entry_point), exc) log.debug("Full backtrace for module directories error", exc_info=True) cli_module_dirs = [] # The dirs can be any module dir, or a in-tree _{ext_type} dir for _dir in opts.get('module_dirs', []): # Prepend to the list to match cli argument ordering maybe_dir = os.path.join(_dir, ext_type) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) continue maybe_dir = os.path.join(_dir, '_{0}'.format(ext_type)) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) return cli_module_dirs + ext_type_types + [ext_types, sys_types] def minion_mods( opts, context=None, utils=None, whitelist=None, initial_load=False, loaded_base_name=None, notify=False, static_modules=None, proxy=None): ''' Load execution modules Returns a dictionary of execution modules appropriate for the current system by evaluating the __virtual__() function in each module. :param dict opts: The Salt options dictionary :param dict context: A Salt context that should be made present inside generated modules in __context__ :param dict utils: Utility functions which should be made available to Salt modules in __utils__. See `utils_dirs` in salt.config for additional information about configuration. :param list whitelist: A list of modules which should be whitelisted. :param bool initial_load: Deprecated flag! Unused. :param str loaded_base_name: A string marker for the loaded base name. :param bool notify: Flag indicating that an event should be fired upon completion of module loading. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) __opts__['grains'] = __grains__ __utils__ = salt.loader.utils(__opts__) __salt__ = salt.loader.minion_mods(__opts__, utils=__utils__) __salt__['test.ping']() ''' # TODO Publish documentation for module whitelisting if not whitelist: whitelist = opts.get('whitelist_modules', None) ret = LazyLoader( _module_dirs(opts, 'modules', 'module'), opts, tag='module', pack={'__context__': context, '__utils__': utils, '__proxy__': proxy}, whitelist=whitelist, loaded_base_name=loaded_base_name, static_modules=static_modules, ) ret.pack['__salt__'] = ret # Load any provider overrides from the configuration file providers option # Note: Providers can be pkg, service, user or group - not to be confused # with cloud providers. providers = opts.get('providers', False) if providers and isinstance(providers, dict): for mod in providers: # sometimes providers opts is not to diverge modules but # for other configuration try: funcs = raw_mod(opts, providers[mod], ret) except TypeError: break else: if funcs: for func in funcs: f_key = '{0}{1}'.format(mod, func[func.rindex('.'):]) ret[f_key] = funcs[func] if notify: evt = salt.utils.event.get_event('minion', opts=opts, listen=False) evt.fire_event({'complete': True}, tag=salt.defaults.events.MINION_MOD_COMPLETE) return ret def raw_mod(opts, name, functions, mod='modules'): ''' Returns a single module loaded raw and bypassing the __virtual__ function .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') testmod = salt.loader.raw_mod(__opts__, 'test', None) testmod['test.ping']() ''' loader = LazyLoader( _module_dirs(opts, mod, 'module'), opts, tag='rawmodule', virtual_enable=False, pack={'__salt__': functions}, ) # if we don't have the module, return an empty dict if name not in loader.file_mapping: return {} loader._load_module(name) # load a single module (the one passed in) return dict(loader._dict) # return a copy of *just* the funcs for `name` def metaproxy(opts): ''' Return functions used in the meta proxy ''' return LazyLoader( _module_dirs(opts, 'metaproxy'), opts, tag='metaproxy' ) def matchers(opts): ''' Return the matcher services plugins ''' return LazyLoader( _module_dirs(opts, 'matchers'), opts, tag='matchers' ) def engines(opts, functions, runners, utils, proxy=None): ''' Return the master services plugins ''' pack = {'__salt__': functions, '__runners__': runners, '__proxy__': proxy, '__utils__': utils} return LazyLoader( _module_dirs(opts, 'engines'), opts, tag='engines', pack=pack, ) def proxy(opts, functions=None, returners=None, whitelist=None, utils=None): ''' Returns the proxy module for this salt-proxy-minion ''' ret = LazyLoader( _module_dirs(opts, 'proxy'), opts, tag='proxy', pack={'__salt__': functions, '__ret__': returners, '__utils__': utils}, ) ret.pack['__proxy__'] = ret return ret def returners(opts, functions, whitelist=None, context=None, proxy=None): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'returners', 'returner'), opts, tag='returner', whitelist=whitelist, pack={'__salt__': functions, '__context__': context, '__proxy__': proxy or {}}, ) def utils(opts, whitelist=None, context=None, proxy=proxy): ''' Returns the utility modules ''' return LazyLoader( _module_dirs(opts, 'utils', ext_type_dirs='utils_dirs'), opts, tag='utils', whitelist=whitelist, pack={'__context__': context, '__proxy__': proxy or {}}, ) def pillars(opts, functions, context=None): ''' Returns the pillars modules ''' ret = LazyLoader(_module_dirs(opts, 'pillar'), opts, tag='pillar', pack={'__salt__': functions, '__context__': context, '__utils__': utils(opts)}) ret.pack['__ext_pillar__'] = ret return FilterDictWrapper(ret, '.ext_pillar') def tops(opts): ''' Returns the tops modules ''' if 'master_tops' not in opts: return {} whitelist = list(opts['master_tops'].keys()) ret = LazyLoader( _module_dirs(opts, 'tops', 'top'), opts, tag='top', whitelist=whitelist, ) return FilterDictWrapper(ret, '.top') def wheels(opts, whitelist=None, context=None): ''' Returns the wheels modules ''' if context is None: context = {} return LazyLoader( _module_dirs(opts, 'wheel'), opts, tag='wheel', whitelist=whitelist, pack={'__context__': context}, ) def outputters(opts): ''' Returns the outputters modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only outputters present in the keyspace ''' ret = LazyLoader( _module_dirs(opts, 'output', ext_type_dirs='outputter_dirs'), opts, tag='output', ) wrapped_ret = FilterDictWrapper(ret, '.output') # TODO: this name seems terrible... __salt__ should always be execution mods ret.pack['__salt__'] = wrapped_ret return wrapped_ret def serializers(opts): ''' Returns the serializers modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only serializers present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'serializers'), opts, tag='serializers', ) def eauth_tokens(opts): ''' Returns the tokens modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only token backends present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'tokens'), opts, tag='tokens', ) def auth(opts, whitelist=None): ''' Returns the auth modules :param dict opts: The Salt options dictionary :returns: LazyLoader ''' return LazyLoader( _module_dirs(opts, 'auth'), opts, tag='auth', whitelist=whitelist, pack={'__salt__': minion_mods(opts)}, ) def fileserver(opts, backends): ''' Returns the file server modules ''' return LazyLoader(_module_dirs(opts, 'fileserver'), opts, tag='fileserver', whitelist=backends, pack={'__utils__': utils(opts)}) def roster(opts, runner=None, utils=None, whitelist=None): ''' Returns the roster modules ''' return LazyLoader( _module_dirs(opts, 'roster'), opts, tag='roster', whitelist=whitelist, pack={ '__runner__': runner, '__utils__': utils, }, ) def thorium(opts, functions, runners): ''' Load the thorium runtime modules ''' pack = {'__salt__': functions, '__runner__': runners, '__context__': {}} ret = LazyLoader(_module_dirs(opts, 'thorium'), opts, tag='thorium', pack=pack) ret.pack['__thorium__'] = ret return ret def states(opts, functions, utils, serializers, whitelist=None, proxy=None, context=None): ''' Returns the state modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') statemods = salt.loader.states(__opts__, None, None) ''' if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'states'), opts, tag='states', pack={'__salt__': functions, '__proxy__': proxy or {}}, whitelist=whitelist, ) ret.pack['__states__'] = ret ret.pack['__utils__'] = utils ret.pack['__serializers__'] = serializers ret.pack['__context__'] = context return ret def beacons(opts, functions, context=None, proxy=None): ''' Load the beacon modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. ''' return LazyLoader( _module_dirs(opts, 'beacons'), opts, tag='beacons', pack={'__context__': context, '__salt__': functions, '__proxy__': proxy or {}}, virtual_funcs=[], ) def log_handlers(opts): ''' Returns the custom logging handler modules :param dict opts: The Salt options dictionary ''' ret = LazyLoader( _module_dirs( opts, 'log_handlers', int_type='handlers', base_path=os.path.join(SALT_BASE_PATH, 'log'), ), opts, tag='log_handlers', ) return FilterDictWrapper(ret, '.setup_handlers') def ssh_wrapper(opts, functions=None, context=None): ''' Returns the custom logging handler modules ''' return LazyLoader( _module_dirs( opts, 'wrapper', base_path=os.path.join(SALT_BASE_PATH, os.path.join('client', 'ssh')), ), opts, tag='wrapper', pack={ '__salt__': functions, '__grains__': opts.get('grains', {}), '__pillar__': opts.get('pillar', {}), '__context__': context, }, ) def render(opts, functions, states=None, proxy=None, context=None): ''' Returns the render modules ''' if context is None: context = {} pack = {'__salt__': functions, '__grains__': opts.get('grains', {}), '__context__': context} if states: pack['__states__'] = states pack['__proxy__'] = proxy or {} ret = LazyLoader( _module_dirs( opts, 'renderers', 'render', ext_type_dirs='render_dirs', ), opts, tag='render', pack=pack, ) rend = FilterDictWrapper(ret, '.render') if not check_render_pipe_str(opts['renderer'], rend, opts['renderer_blacklist'], opts['renderer_whitelist']): err = ('The renderer {0} is unavailable, this error is often because ' 'the needed software is unavailable'.format(opts['renderer'])) log.critical(err) raise LoaderError(err) return rend def grain_funcs(opts, proxy=None): ''' Returns the grain functions .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') grainfuncs = salt.loader.grain_funcs(__opts__) ''' ret = LazyLoader( _module_dirs( opts, 'grains', 'grain', ext_type_dirs='grains_dirs', ), opts, tag='grains', ) ret.pack['__utils__'] = utils(opts, proxy=proxy) return ret def _load_cached_grains(opts, cfn): ''' Returns the grains cached in cfn, or None if the cache is too old or is corrupted. ''' if not os.path.isfile(cfn): log.debug('Grains cache file does not exist.') return None grains_cache_age = int(time.time() - os.path.getmtime(cfn)) if grains_cache_age > opts.get('grains_cache_expiration', 300): log.debug( 'Grains cache last modified %s seconds ago and cache ' 'expiration is set to %s. Grains cache expired. ' 'Refreshing.', grains_cache_age, opts.get('grains_cache_expiration', 300) ) return None if opts.get('refresh_grains_cache', False): log.debug('refresh_grains_cache requested, Refreshing.') return None log.debug('Retrieving grains from cache') try: serial = salt.payload.Serial(opts) with salt.utils.files.fopen(cfn, 'rb') as fp_: cached_grains = salt.utils.data.decode(serial.load(fp_), preserve_tuples=True) if not cached_grains: log.debug('Cached grains are empty, cache might be corrupted. Refreshing.') return None return cached_grains except (IOError, OSError): return None # TODO: get rid of? Does anyone use this? You should use raw() instead def call(fun, **kwargs): ''' Directly call a function inside a loader directory ''' args = kwargs.get('args', []) dirs = kwargs.get('dirs', []) funcs = LazyLoader( [os.path.join(SALT_BASE_PATH, 'modules')] + dirs, None, tag='modules', virtual_enable=False, ) return funcs[fun](*args) def runner(opts, utils=None, context=None, whitelist=None): ''' Directly call a function inside a loader directory ''' if utils is None: utils = {} if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'runners', 'runner', ext_type_dirs='runner_dirs'), opts, tag='runners', pack={'__utils__': utils, '__context__': context}, whitelist=whitelist, ) # TODO: change from __salt__ to something else, we overload __salt__ too much ret.pack['__salt__'] = ret return ret def queues(opts): ''' Directly call a function inside a loader directory ''' return LazyLoader( _module_dirs(opts, 'queues', 'queue', ext_type_dirs='queue_dirs'), opts, tag='queues', ) def sdb(opts, functions=None, whitelist=None, utils=None): ''' Make a very small database call ''' if utils is None: utils = {} return LazyLoader( _module_dirs(opts, 'sdb'), opts, tag='sdb', pack={ '__sdb__': functions, '__opts__': opts, '__utils__': utils, '__salt__': minion_mods(opts, utils), }, whitelist=whitelist, ) def pkgdb(opts): ''' Return modules for SPM's package database .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgdb', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgdb' ) def pkgfiles(opts): ''' Return modules for SPM's file handling .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgfiles', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgfiles' ) def clouds(opts): ''' Return the cloud functions ''' # Let's bring __active_provider_name__, defaulting to None, to all cloud # drivers. This will get temporarily updated/overridden with a context # manager when needed. functions = LazyLoader( _module_dirs(opts, 'clouds', 'cloud', base_path=os.path.join(SALT_BASE_PATH, 'cloud'), int_type='clouds'), opts, tag='clouds', pack={'__utils__': salt.loader.utils(opts), '__active_provider_name__': None}, ) for funcname in LIBCLOUD_FUNCS_NOT_SUPPORTED: log.trace( '\'%s\' has been marked as not supported. Removing from the ' 'list of supported cloud functions', funcname ) functions.pop(funcname, None) return functions def netapi(opts): ''' Return the network api functions ''' return LazyLoader( _module_dirs(opts, 'netapi'), opts, tag='netapi', ) def executors(opts, functions=None, context=None, proxy=None): ''' Returns the executor modules ''' executors = LazyLoader( _module_dirs(opts, 'executors', 'executor'), opts, tag='executor', pack={'__salt__': functions, '__context__': context or {}, '__proxy__': proxy or {}}, ) executors.pack['__executors__'] = executors return executors def cache(opts, serial): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'cache', 'cache'), opts, tag='cache', pack={'__opts__': opts, '__context__': {'serial': serial}}, ) def _generate_module(name): if name in sys.modules: return code = "'''Salt loaded {0} parent module'''".format(name.split('.')[-1]) # ModuleType can't accept a unicode type on PY2 module = types.ModuleType(str(name)) # future lint: disable=blacklisted-function exec(code, module.__dict__) sys.modules[name] = module def _mod_type(module_path): if module_path.startswith(SALT_BASE_PATH): return 'int' return 'ext' def _inject_into_mod(mod, name, value, force_lock=False): ''' Inject a variable into a module. This is used to inject "globals" like ``__salt__``, ``__pillar``, or ``grains``. Instead of injecting the value directly, a ``ThreadLocalProxy`` is created. If such a proxy is already present under the specified name, it is updated with the new value. This update only affects the current thread, so that the same name can refer to different values depending on the thread of execution. This is important for data that is not truly global. For example, pillar data might be dynamically overriden through function parameters and thus the actual values available in pillar might depend on the thread that is calling a module. mod: module object into which the value is going to be injected. name: name of the variable that is injected into the module. value: value that is injected into the variable. The value is not injected directly, but instead set as the new reference of the proxy that has been created for the variable. force_lock: whether the lock should be acquired before checking whether a proxy object for the specified name has already been injected into the module. If ``False`` (the default), this function checks for the module's variable without acquiring the lock and only acquires the lock if a new proxy has to be created and injected. ''' old_value = getattr(mod, name, None) # We use a double-checked locking scheme in order to avoid taking the lock # when a proxy object has already been injected. # In most programming languages, double-checked locking is considered # unsafe when used without explicit memory barriers because one might read # an uninitialized value. In CPython it is safe due to the global # interpreter lock (GIL). In Python implementations that do not have the # GIL, it could be unsafe, but at least Jython also guarantees that (for # Python objects) memory is not corrupted when writing and reading without # explicit synchronization # (http://www.jython.org/jythonbook/en/1.0/Concurrency.html). # Please note that in order to make this code safe in a runtime environment # that does not make this guarantees, it is not sufficient. The # ThreadLocalProxy must also be created with fallback_to_shared set to # False or a lock must be added to the ThreadLocalProxy. if force_lock: with _inject_into_mod.lock: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: setattr(mod, name, ThreadLocalProxy(value, True)) else: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: _inject_into_mod(mod, name, value, True) # Lock used when injecting globals. This is needed to avoid a race condition # when two threads try to load the same module concurrently. This must be # outside the loader because there might be more than one loader for the same # namespace. _inject_into_mod.lock = threading.RLock() # TODO: move somewhere else? class FilterDictWrapper(MutableMapping): ''' Create a dict which wraps another dict with a specific key suffix on get This is to replace "filter_load" ''' def __init__(self, d, suffix): self._dict = d self.suffix = suffix def __setitem__(self, key, val): self._dict[key] = val def __delitem__(self, key): del self._dict[key] def __getitem__(self, key): return self._dict[key + self.suffix] def __len__(self): return len(self._dict) def __iter__(self): for key in self._dict: if key.endswith(self.suffix): yield key.replace(self.suffix, '') class LazyLoader(salt.utils.lazy.LazyDict): ''' A pseduo-dictionary which has a set of keys which are the name of the module and function, delimited by a dot. When the value of the key is accessed, the function is then loaded from disk and into memory. .. note:: Iterating over keys will cause all modules to be loaded. :param list module_dirs: A list of directories on disk to search for modules :param dict opts: The salt options dictionary. :param str tag: The tag for the type of module to load :param func mod_type_check: A function which can be used to verify files :param dict pack: A dictionary of function to be packed into modules as they are loaded :param list whitelist: A list of modules to whitelist :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules. :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality. If not true, the module will not load. :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values are function references themselves which are loaded on-demand. # TODO: - move modules_max_memory into here - singletons (per tag) ''' mod_dict_class = salt.utils.odict.OrderedDict def __init__(self, module_dirs, opts=None, tag='module', loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, proxy=None, virtual_funcs=None, ): # pylint: disable=W0231 ''' In pack, if any of the values are None they will be replaced with an empty context-specific dict ''' self.inject_globals = {} self.pack = {} if pack is None else pack if opts is None: opts = {} threadsafety = not opts.get('multiprocessing') self.context_dict = salt.utils.context.ContextDict(threadsafe=threadsafety) self.opts = self.__prep_mod_opts(opts) self.module_dirs = module_dirs self.tag = tag self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME self.mod_type_check = mod_type_check or _mod_type if '__context__' not in self.pack: self.pack['__context__'] = None for k, v in six.iteritems(self.pack): if v is None: # if the value of a pack is None, lets make an empty dict value = self.context_dict.get(k, {}) if isinstance(value, ThreadLocalProxy): value = ThreadLocalProxy.unproxy(value) self.context_dict[k] = value self.pack[k] = salt.utils.context.NamespacedDictWrapper(self.context_dict, k) self.whitelist = whitelist self.virtual_enable = virtual_enable self.initial_load = True # names of modules that we don't have (errors, __virtual__, etc.) self.missing_modules = {} # mapping of name -> error self.loaded_modules = {} # mapping of module_name -> dict_of_functions self.loaded_files = set() # TODO: just remove them from file_mapping? self.static_modules = static_modules if static_modules else [] if virtual_funcs is None: virtual_funcs = [] self.virtual_funcs = virtual_funcs self.disabled = set( self.opts.get( 'disable_{0}{1}'.format( self.tag, '' if self.tag[-1] == 's' else 's' ), [] ) ) # A map of suffix to description for imp self.suffix_map = {} # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [''] for (suffix, mode, kind) in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) self._lock = threading.RLock() self._refresh_file_mapping() super(LazyLoader, self).__init__() # late init the lazy loader # create all of the import namespaces _generate_module('{0}.int'.format(self.loaded_base_name)) _generate_module('{0}.int.{1}'.format(self.loaded_base_name, tag)) _generate_module('{0}.ext'.format(self.loaded_base_name)) _generate_module('{0}.ext.{1}'.format(self.loaded_base_name, tag)) def __getitem__(self, item): ''' Override the __getitem__ in order to decorate the returned function if we need to last-minute inject globals ''' func = super(LazyLoader, self).__getitem__(item) if self.inject_globals: return global_injector_decorator(self.inject_globals)(func) else: return func def __getattr__(self, mod_name): ''' Allow for "direct" attribute access-- this allows jinja templates to access things like `salt.test.ping()` ''' if mod_name in ('__getstate__', '__setstate__'): return object.__getattribute__(self, mod_name) # if we have an attribute named that, lets return it. try: return object.__getattr__(self, mod_name) # pylint: disable=no-member except AttributeError: pass # otherwise we assume its jinja template access if mod_name not in self.loaded_modules and not self.loaded: for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and mod_name in self.loaded_modules: break if mod_name in self.loaded_modules: return self.loaded_modules[mod_name] else: raise AttributeError(mod_name) def missing_fun_string(self, function_name): ''' Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ''' mod_name = function_name.split('.')[0] if mod_name in self.loaded_modules: return '\'{0}\' is not available.'.format(function_name) else: try: reason = self.missing_modules[mod_name] except KeyError: return '\'{0}\' is not available.'.format(function_name) else: if reason is not None: return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason) else: return '\'{0}\' __virtual__ returned False'.format(mod_name) def _refresh_file_mapping(self): ''' refresh the mapping of the FS on disk ''' # map of suffix to description for imp if self.opts.get('cython_enable', True) is True: try: global pyximport pyximport = __import__('pyximport') # pylint: disable=import-error pyximport.install() # add to suffix_map so file_mapping will pick it up self.suffix_map['.pyx'] = tuple() except ImportError: log.info('Cython is enabled in the options but not present ' 'in the system path. Skipping Cython modules.') # Allow for zipimport of modules if self.opts.get('enable_zip_modules', True) is True: self.suffix_map['.zip'] = tuple() # allow for module dirs if USE_IMPORTLIB: self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY) else: self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY) # create mapping of filename (without suffix) to (path, suffix) # The files are added in order of priority, so order *must* be retained. self.file_mapping = salt.utils.odict.OrderedDict() opt_match = [] def _replace_pre_ext(obj): ''' Hack so we can get the optimization level that we replaced (if any) out of the re.sub call below. We use a list here because it is a persistent data structure that we will be able to access after re.sub is called. ''' opt_match.append(obj) return '' for mod_dir in self.module_dirs: try: # Make sure we have a sorted listdir in order to have # expectable override results files = sorted( x for x in os.listdir(mod_dir) if x != '__pycache__' ) except OSError: continue # Next mod_dir if six.PY3: try: pycache_files = [ os.path.join('__pycache__', x) for x in sorted(os.listdir(os.path.join(mod_dir, '__pycache__'))) ] except OSError: pass else: files.extend(pycache_files) for filename in files: try: dirname, basename = os.path.split(filename) if basename.startswith('_'): # skip private modules # log messages omitted for obviousness continue # Next filename f_noext, ext = os.path.splitext(basename) if six.PY3: f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext) try: opt_level = int( opt_match.pop().group(1).rsplit('-', 1)[-1] ) except (AttributeError, IndexError, ValueError): # No regex match or no optimization level matched opt_level = 0 try: opt_index = self.opts['optimization_order'].index(opt_level) except KeyError: log.trace( 'Disallowed optimization level %d for module ' 'name \'%s\', skipping. Add %d to the ' '\'optimization_order\' config option if you ' 'do not want to ignore this optimization ' 'level.', opt_level, f_noext, opt_level ) continue else: # Optimization level not reflected in filename on PY2 opt_index = 0 # make sure it is a suffix we support if ext not in self.suffix_map: continue # Next filename if f_noext in self.disabled: log.trace( 'Skipping %s, it is disabled by configuration', filename ) continue # Next filename fpath = os.path.join(mod_dir, filename) # if its a directory, lets allow us to load that if ext == '': # is there something __init__? subfiles = os.listdir(fpath) for suffix in self.suffix_order: if '' == suffix: continue # Next suffix (__init__ must have a suffix) init_file = '__init__{0}'.format(suffix) if init_file in subfiles: break else: continue # Next filename try: curr_ext = self.file_mapping[f_noext][1] curr_opt_index = self.file_mapping[f_noext][2] except KeyError: pass else: if '' in (curr_ext, ext) and curr_ext != ext: log.error( 'Module/package collision: \'%s\' and \'%s\'', fpath, self.file_mapping[f_noext][0] ) if six.PY3 and ext == '.pyc' and curr_ext == '.pyc': # Check the optimization level if opt_index >= curr_opt_index: # Module name match, but a higher-priority # optimization level was already matched, skipping. continue elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext): # Match found but a higher-priorty match already # exists, so skip this. continue if six.PY3 and not dirname and ext == '.pyc': # On Python 3, we should only load .pyc files from the # __pycache__ subdirectory (i.e. when dirname is not an # empty string). continue # Made it this far - add it self.file_mapping[f_noext] = (fpath, ext, opt_index) except OSError: continue for smod in self.static_modules: f_noext = smod.split('.')[-1] self.file_mapping[f_noext] = (smod, '.o', 0) def clear(self): ''' Clear the dict ''' with self._lock: super(LazyLoader, self).clear() # clear the lazy loader self.loaded_files = set() self.missing_modules = {} self.loaded_modules = {} # if we have been loaded before, lets clear the file mapping since # we obviously want a re-do if hasattr(self, 'opts'): self._refresh_file_mapping() self.initial_load = False def __prep_mod_opts(self, opts): ''' Strip out of the opts any logger instance ''' if '__grains__' not in self.pack: grains = opts.get('grains', {}) if isinstance(grains, ThreadLocalProxy): grains = ThreadLocalProxy.unproxy(grains) self.context_dict['grains'] = grains self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains') if '__pillar__' not in self.pack: pillar = opts.get('pillar', {}) if isinstance(pillar, ThreadLocalProxy): pillar = ThreadLocalProxy.unproxy(pillar) self.context_dict['pillar'] = pillar self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar') mod_opts = {} for key, val in list(opts.items()): if key == 'logger': continue mod_opts[key] = val return mod_opts def _iter_files(self, mod_name): ''' Iterate over all file_mapping files in order of closeness to mod_name ''' # do we have an exact match? if mod_name in self.file_mapping: yield mod_name # do we have a partial match? for k in self.file_mapping: if mod_name in k: yield k # anyone else? Bueller? for k in self.file_mapping: if mod_name not in k: yield k def _reload_submodules(self, mod): submodules = ( getattr(mod, sname) for sname in dir(mod) if isinstance(getattr(mod, sname), mod.__class__) ) # reload only custom "sub"modules for submodule in submodules: # it is a submodule if the name is in a namespace under mod if submodule.__name__.startswith(mod.__name__ + '.'): reload_module(submodule) self._reload_submodules(submodule) def _load_module(self, name): mod = None fpath, suffix = self.file_mapping[name][:2] self.loaded_files.add(name) fpath_dirname = os.path.dirname(fpath) try: sys.path.append(fpath_dirname) if suffix == '.pyx': mod = pyximport.load_module(name, fpath, tempfile.gettempdir()) elif suffix == '.o': top_mod = __import__(fpath, globals(), locals(), []) comps = fpath.split('.') if len(comps) < 2: mod = top_mod else: mod = top_mod for subname in comps[1:]: mod = getattr(mod, subname) elif suffix == '.zip': mod = zipimporter(fpath).load_module(name) else: desc = self.suffix_map[suffix] # if it is a directory, we don't open a file try: mod_namespace = '.'.join(( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name)) except TypeError: mod_namespace = '{0}.{1}.{2}.{3}'.format( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name) if suffix == '': if USE_IMPORTLIB: # pylint: disable=no-member # Package directory, look for __init__ loader_details = [ (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES), (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES), (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), ] file_finder = importlib.machinery.FileFinder( fpath_dirname, *loader_details ) spec = file_finder.find_spec(mod_namespace) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: mod = imp.load_module(mod_namespace, None, fpath, desc) # reload all submodules if necessary if not self.initial_load: self._reload_submodules(mod) else: if USE_IMPORTLIB: # pylint: disable=no-member loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath) spec = importlib.util.spec_from_file_location( mod_namespace, fpath, loader=loader ) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() #mod = importlib.util.module_from_spec(spec) #spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: with salt.utils.files.fopen(fpath, desc[1]) as fn_: mod = imp.load_module(mod_namespace, fn_, fpath, desc) except IOError: raise except ImportError as exc: if 'magic number' in six.text_type(exc): error_msg = 'Failed to import {0} {1}. Bad magic number. If migrating from Python2 to Python3, remove all .pyc files and try again.'.format(self.tag, name) log.warning(error_msg) self.missing_modules[name] = error_msg log.debug( 'Failed to import %s %s:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = exc return False except Exception as error: log.error( 'Failed to import %s %s, this is due most likely to a ' 'syntax error:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False except SystemExit as error: try: fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1] except Exception: pass else: tgt_fn = os.path.join('salt', 'utils', 'process.py') if fn_.endswith(tgt_fn) and '_handle_signals' in caller: # Race conditon, SIGTERM or SIGINT received while loader # was in process of loading a module. Call sys.exit to # ensure that the process is killed. sys.exit(salt.defaults.exitcodes.EX_OK) log.error( 'Failed to import %s %s as the module called exit()\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False finally: sys.path.remove(fpath_dirname) if hasattr(mod, '__opts__'): mod.__opts__.update(self.opts) else: mod.__opts__ = self.opts # pack whatever other globals we were asked to for p_name, p_value in six.iteritems(self.pack): _inject_into_mod(mod, p_name, p_value) module_name = mod.__name__.rsplit('.', 1)[-1] # Call a module's initialization method if it exists module_init = getattr(mod, '__init__', None) if inspect.isfunction(module_init): try: module_init(self.opts) except TypeError as e: log.error(e) except Exception: err_string = '__init__ failed' log.debug( 'Error loading %s.%s: %s', self.tag, module_name, err_string, exc_info=True ) self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False # if virtual modules are enabled, we need to look for the # __virtual__() function inside that module and run it. if self.virtual_enable: virtual_funcs_to_process = ['__virtual__'] + self.virtual_funcs for virtual_func in virtual_funcs_to_process: virtual_ret, module_name, virtual_err, virtual_aliases = \ self._process_virtual(mod, module_name, virtual_func) if virtual_err is not None: log.trace( 'Error loading %s.%s: %s', self.tag, module_name, virtual_err ) # if _process_virtual returned a non-True value then we are # supposed to not process this module if virtual_ret is not True and module_name not in self.missing_modules: # If a module has information about why it could not be loaded, record it self.missing_modules[module_name] = virtual_err self.missing_modules[name] = virtual_err return False else: virtual_aliases = () # If this is a proxy minion then MOST modules cannot work. Therefore, require that # any module that does work with salt-proxy-minion define __proxyenabled__ as a list # containing the names of the proxy types that the module supports. # # Render modules and state modules are OK though if 'proxy' in self.opts: if self.tag in ['grains', 'proxy']: if not hasattr(mod, '__proxyenabled__') or \ (self.opts['proxy']['proxytype'] not in mod.__proxyenabled__ and '*' not in mod.__proxyenabled__): err_string = 'not a proxy_minion enabled module' self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False if getattr(mod, '__load__', False) is not False: log.info( 'The functions from module \'%s\' are being loaded from the ' 'provided __load__ attribute', module_name ) # If we had another module by the same virtual name, we should put any # new functions under the existing dictionary. mod_names = [module_name] + list(virtual_aliases) mod_dict = dict(( (x, self.loaded_modules.get(x, self.mod_dict_class())) for x in mod_names )) for attr in getattr(mod, '__load__', dir(mod)): if attr.startswith('_') and attr != '__call__': # private functions are skipped, # except __call__ which is default entrance # for multi-function batch-like state syntax continue func = getattr(mod, attr) if not inspect.isfunction(func) and not isinstance(func, functools.partial): # Not a function!? Skip it!!! continue # Let's get the function name. # If the module has the __func_alias__ attribute, it must be a # dictionary mapping in the form of(key -> value): # <real-func-name> -> <desired-func-name> # # It default's of course to the found callable attribute name # if no alias is defined. funcname = getattr(mod, '__func_alias__', {}).get(attr, attr) for tgt_mod in mod_names: try: full_funcname = '.'.join((tgt_mod, funcname)) except TypeError: full_funcname = '{0}.{1}'.format(tgt_mod, funcname) # Save many references for lookups # Careful not to overwrite existing (higher priority) functions if full_funcname not in self._dict: self._dict[full_funcname] = func if funcname not in mod_dict[tgt_mod]: setattr(mod_dict[tgt_mod], funcname, func) mod_dict[tgt_mod][funcname] = func self._apply_outputter(func, mod) # enforce depends try: Depends.enforce_dependencies(self._dict, self.tag) except RuntimeError as exc: log.info( 'Depends.enforce_dependencies() failed for the following ' 'reason: %s', exc ) for tgt_mod in mod_names: self.loaded_modules[tgt_mod] = mod_dict[tgt_mod] return True def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise KeyError('The key \'{0}\' should contain a \'.\''.format(key)) mod_name, _ = key.split('.', 1) with self._lock: # It is possible that the key is in the dictionary after # acquiring the lock due to another thread loading it. if mod_name in self.missing_modules or key in self._dict: return True # if the modulename isn't in the whitelist, don't bother if self.whitelist and mod_name not in self.whitelist: log.error( 'Failed to load function %s because its module (%s) is ' 'not in the whitelist: %s', key, mod_name, self.whitelist ) raise KeyError(key) def _inner_load(mod_name): for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and key in self._dict: return True return False # try to load the module ret = None reloaded = False # re-scan up to once, IOErrors or a failed load cause re-scans of the # filesystem while True: try: ret = _inner_load(mod_name) if not reloaded and ret is not True: self._refresh_file_mapping() reloaded = True continue break except IOError: if not reloaded: self._refresh_file_mapping() reloaded = True continue return ret def _load_all(self): ''' Load all of them ''' with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True def reload_modules(self): with self._lock: self.loaded_files = set() self._load_all() def _apply_outputter(self, func, mod): ''' Apply the __outputter__ variable to the functions ''' if hasattr(mod, '__outputter__'): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__] def _process_virtual(self, mod, module_name, virtual_func='__virtual__'): ''' Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1] ''' # The __virtual__ function will return either a True or False value. # If it returns a True value it can also set a module level attribute # named __virtualname__ with the name that the module should be # referred to as. # # This allows us to have things like the pkg module working on all # platforms under the name 'pkg'. It also allows for modules like # augeas_cfg to be referred to as 'augeas', which would otherwise have # namespace collisions. And finally it allows modules to return False # if they are not intended to run on the given platform or are missing # dependencies. virtual_aliases = getattr(mod, '__virtual_aliases__', tuple()) try: error_reason = None if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__): try: start = time.time() virtual = getattr(mod, virtual_func)() if isinstance(virtual, tuple): error_reason = virtual[1] virtual = virtual[0] if self.opts.get('virtual_timer', False): end = time.time() - start msg = 'Virtual function took {0} seconds for {1}'.format( end, module_name) log.warning(msg) except Exception as exc: error_reason = ( 'Exception raised when processing __virtual__ function' ' for {0}. Module will not be loaded: {1}'.format( mod.__name__, exc)) log.error(error_reason, exc_info_on_loglevel=logging.DEBUG) virtual = None # Get the module's virtual name virtualname = getattr(mod, '__virtualname__', virtual) if not virtual: # if __virtual__() evaluates to False then the module # wasn't meant for this platform or it's not supposed to # load for some other reason. # Some modules might accidentally return None and are # improperly loaded if virtual is None: log.warning( '%s.__virtual__() is wrongly returning `None`. ' 'It should either return `True`, `False` or a new ' 'name. If you\'re the developer of the module ' '\'%s\', please fix this.', mod.__name__, module_name ) return (False, module_name, error_reason, virtual_aliases) # At this point, __virtual__ did not return a # boolean value, let's check for deprecated usage # or module renames if virtual is not True and module_name != virtual: # The module is renaming itself. Updating the module name # with the new name log.trace('Loaded %s as virtual %s', module_name, virtual) if virtualname != virtual: # The __virtualname__ attribute does not match what's # being returned by the __virtual__() function. This # should be considered an error. log.error( 'The module \'%s\' is showing some bad usage. Its ' '__virtualname__ attribute is set to \'%s\' yet the ' '__virtual__() function is returning \'%s\'. These ' 'values should match!', mod.__name__, virtualname, virtual ) module_name = virtualname # If the __virtual__ function returns True and __virtualname__ # is set then use it elif virtual is True and virtualname != module_name: if virtualname is not True: module_name = virtualname except KeyError: # Key errors come out of the virtual function when passing # in incomplete grains sets, these can be safely ignored # and logged to debug, still, it includes the traceback to # help debugging. log.debug('KeyError when loading %s', module_name, exc_info=True) except Exception: # If the module throws an exception during __virtual__() # then log the information and continue to the next. log.error( 'Failed to read the virtual function for %s: %s', self.tag, module_name, exc_info=True ) return (False, module_name, error_reason, virtual_aliases) return (True, module_name, None, virtual_aliases) def global_injector_decorator(inject_globals): ''' Decorator used by the LazyLoader to inject globals into a function at execute time. globals Dictionary with global variables to inject ''' def inner_decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): with salt.utils.context.func_globals_inject(f, **inject_globals): return f(*args, **kwargs) return wrapper return inner_decorator
saltstack/salt
salt/loader.py
call
python
def call(fun, **kwargs): ''' Directly call a function inside a loader directory ''' args = kwargs.get('args', []) dirs = kwargs.get('dirs', []) funcs = LazyLoader( [os.path.join(SALT_BASE_PATH, 'modules')] + dirs, None, tag='modules', virtual_enable=False, ) return funcs[fun](*args)
Directly call a function inside a loader directory
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L913-L926
null
# -*- coding: utf-8 -*- ''' The Salt loader is the core to Salt's plugin system, the loader scans directories for python loadable code and organizes the code into the plugin interfaces used by Salt. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import sys import time import logging import inspect import tempfile import threading import functools import threading import traceback import types from zipimport import zipimporter # Import salt libs import salt.config import salt.defaults.events import salt.defaults.exitcodes import salt.syspaths import salt.utils.args import salt.utils.context import salt.utils.data import salt.utils.dictupdate import salt.utils.event import salt.utils.files import salt.utils.lazy import salt.utils.odict import salt.utils.platform import salt.utils.versions import salt.utils.stringutils from salt.exceptions import LoaderError from salt.template import check_render_pipe_str from salt.utils.decorators import Depends from salt.utils.thread_local_proxy import ThreadLocalProxy # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import reload_module if sys.version_info[:2] >= (3, 5): import importlib.machinery # pylint: disable=no-name-in-module,import-error import importlib.util # pylint: disable=no-name-in-module,import-error USE_IMPORTLIB = True else: import imp USE_IMPORTLIB = False try: from collections.abc import MutableMapping except ImportError: from collections import MutableMapping try: import pkg_resources HAS_PKG_RESOURCES = True except ImportError: HAS_PKG_RESOURCES = False log = logging.getLogger(__name__) SALT_BASE_PATH = os.path.abspath(salt.syspaths.INSTALL_DIR) LOADED_BASE_NAME = 'salt.loaded' if USE_IMPORTLIB: # pylint: disable=no-member MODULE_KIND_SOURCE = 1 MODULE_KIND_COMPILED = 2 MODULE_KIND_EXTENSION = 3 MODULE_KIND_PKG_DIRECTORY = 5 SUFFIXES = [] for suffix in importlib.machinery.EXTENSION_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_EXTENSION)) for suffix in importlib.machinery.SOURCE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_SOURCE)) for suffix in importlib.machinery.BYTECODE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_COMPILED)) MODULE_KIND_MAP = { MODULE_KIND_SOURCE: importlib.machinery.SourceFileLoader, MODULE_KIND_COMPILED: importlib.machinery.SourcelessFileLoader, MODULE_KIND_EXTENSION: importlib.machinery.ExtensionFileLoader } # pylint: enable=no-member else: SUFFIXES = imp.get_suffixes() PY3_PRE_EXT = \ re.compile(r'\.cpython-{0}{1}(\.opt-[1-9])?'.format(*sys.version_info[:2])) # Because on the cloud drivers we do `from salt.cloud.libcloudfuncs import *` # which simplifies code readability, it adds some unsupported functions into # the driver's module scope. # We list un-supported functions here. These will be removed from the loaded. # TODO: remove the need for this cross-module code. Maybe use NotImplemented LIBCLOUD_FUNCS_NOT_SUPPORTED = ( 'parallels.avail_sizes', 'parallels.avail_locations', 'proxmox.avail_sizes', ) # Will be set to pyximport module at runtime if cython is enabled in config. pyximport = None def static_loader( opts, ext_type, tag, pack=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, filter_name=None, ): funcs = LazyLoader( _module_dirs( opts, ext_type, tag, int_type, ext_dirs, ext_type_dirs, base_path, ), opts, tag=tag, pack=pack, ) ret = {} funcs._load_all() if filter_name: funcs = FilterDictWrapper(funcs, filter_name) for key in funcs: ret[key] = funcs[key] return ret def _format_entrypoint_target(ep): ''' Makes a string describing the target of an EntryPoint object. Base strongly on EntryPoint.__str__(). ''' s = ep.module_name if ep.attrs: s += ':' + '.'.join(ep.attrs) return s def _module_dirs( opts, ext_type, tag=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, ): if tag is None: tag = ext_type sys_types = os.path.join(base_path or SALT_BASE_PATH, int_type or ext_type) ext_types = os.path.join(opts['extension_modules'], ext_type) ext_type_types = [] if ext_dirs: if ext_type_dirs is None: ext_type_dirs = '{0}_dirs'.format(tag) if ext_type_dirs in opts: ext_type_types.extend(opts[ext_type_dirs]) if HAS_PKG_RESOURCES and ext_type_dirs: for entry_point in pkg_resources.iter_entry_points('salt.loader', ext_type_dirs): try: loaded_entry_point = entry_point.load() for path in loaded_entry_point(): ext_type_types.append(path) except Exception as exc: log.error("Error getting module directories from %s: %s", _format_entrypoint_target(entry_point), exc) log.debug("Full backtrace for module directories error", exc_info=True) cli_module_dirs = [] # The dirs can be any module dir, or a in-tree _{ext_type} dir for _dir in opts.get('module_dirs', []): # Prepend to the list to match cli argument ordering maybe_dir = os.path.join(_dir, ext_type) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) continue maybe_dir = os.path.join(_dir, '_{0}'.format(ext_type)) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) return cli_module_dirs + ext_type_types + [ext_types, sys_types] def minion_mods( opts, context=None, utils=None, whitelist=None, initial_load=False, loaded_base_name=None, notify=False, static_modules=None, proxy=None): ''' Load execution modules Returns a dictionary of execution modules appropriate for the current system by evaluating the __virtual__() function in each module. :param dict opts: The Salt options dictionary :param dict context: A Salt context that should be made present inside generated modules in __context__ :param dict utils: Utility functions which should be made available to Salt modules in __utils__. See `utils_dirs` in salt.config for additional information about configuration. :param list whitelist: A list of modules which should be whitelisted. :param bool initial_load: Deprecated flag! Unused. :param str loaded_base_name: A string marker for the loaded base name. :param bool notify: Flag indicating that an event should be fired upon completion of module loading. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) __opts__['grains'] = __grains__ __utils__ = salt.loader.utils(__opts__) __salt__ = salt.loader.minion_mods(__opts__, utils=__utils__) __salt__['test.ping']() ''' # TODO Publish documentation for module whitelisting if not whitelist: whitelist = opts.get('whitelist_modules', None) ret = LazyLoader( _module_dirs(opts, 'modules', 'module'), opts, tag='module', pack={'__context__': context, '__utils__': utils, '__proxy__': proxy}, whitelist=whitelist, loaded_base_name=loaded_base_name, static_modules=static_modules, ) ret.pack['__salt__'] = ret # Load any provider overrides from the configuration file providers option # Note: Providers can be pkg, service, user or group - not to be confused # with cloud providers. providers = opts.get('providers', False) if providers and isinstance(providers, dict): for mod in providers: # sometimes providers opts is not to diverge modules but # for other configuration try: funcs = raw_mod(opts, providers[mod], ret) except TypeError: break else: if funcs: for func in funcs: f_key = '{0}{1}'.format(mod, func[func.rindex('.'):]) ret[f_key] = funcs[func] if notify: evt = salt.utils.event.get_event('minion', opts=opts, listen=False) evt.fire_event({'complete': True}, tag=salt.defaults.events.MINION_MOD_COMPLETE) return ret def raw_mod(opts, name, functions, mod='modules'): ''' Returns a single module loaded raw and bypassing the __virtual__ function .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') testmod = salt.loader.raw_mod(__opts__, 'test', None) testmod['test.ping']() ''' loader = LazyLoader( _module_dirs(opts, mod, 'module'), opts, tag='rawmodule', virtual_enable=False, pack={'__salt__': functions}, ) # if we don't have the module, return an empty dict if name not in loader.file_mapping: return {} loader._load_module(name) # load a single module (the one passed in) return dict(loader._dict) # return a copy of *just* the funcs for `name` def metaproxy(opts): ''' Return functions used in the meta proxy ''' return LazyLoader( _module_dirs(opts, 'metaproxy'), opts, tag='metaproxy' ) def matchers(opts): ''' Return the matcher services plugins ''' return LazyLoader( _module_dirs(opts, 'matchers'), opts, tag='matchers' ) def engines(opts, functions, runners, utils, proxy=None): ''' Return the master services plugins ''' pack = {'__salt__': functions, '__runners__': runners, '__proxy__': proxy, '__utils__': utils} return LazyLoader( _module_dirs(opts, 'engines'), opts, tag='engines', pack=pack, ) def proxy(opts, functions=None, returners=None, whitelist=None, utils=None): ''' Returns the proxy module for this salt-proxy-minion ''' ret = LazyLoader( _module_dirs(opts, 'proxy'), opts, tag='proxy', pack={'__salt__': functions, '__ret__': returners, '__utils__': utils}, ) ret.pack['__proxy__'] = ret return ret def returners(opts, functions, whitelist=None, context=None, proxy=None): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'returners', 'returner'), opts, tag='returner', whitelist=whitelist, pack={'__salt__': functions, '__context__': context, '__proxy__': proxy or {}}, ) def utils(opts, whitelist=None, context=None, proxy=proxy): ''' Returns the utility modules ''' return LazyLoader( _module_dirs(opts, 'utils', ext_type_dirs='utils_dirs'), opts, tag='utils', whitelist=whitelist, pack={'__context__': context, '__proxy__': proxy or {}}, ) def pillars(opts, functions, context=None): ''' Returns the pillars modules ''' ret = LazyLoader(_module_dirs(opts, 'pillar'), opts, tag='pillar', pack={'__salt__': functions, '__context__': context, '__utils__': utils(opts)}) ret.pack['__ext_pillar__'] = ret return FilterDictWrapper(ret, '.ext_pillar') def tops(opts): ''' Returns the tops modules ''' if 'master_tops' not in opts: return {} whitelist = list(opts['master_tops'].keys()) ret = LazyLoader( _module_dirs(opts, 'tops', 'top'), opts, tag='top', whitelist=whitelist, ) return FilterDictWrapper(ret, '.top') def wheels(opts, whitelist=None, context=None): ''' Returns the wheels modules ''' if context is None: context = {} return LazyLoader( _module_dirs(opts, 'wheel'), opts, tag='wheel', whitelist=whitelist, pack={'__context__': context}, ) def outputters(opts): ''' Returns the outputters modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only outputters present in the keyspace ''' ret = LazyLoader( _module_dirs(opts, 'output', ext_type_dirs='outputter_dirs'), opts, tag='output', ) wrapped_ret = FilterDictWrapper(ret, '.output') # TODO: this name seems terrible... __salt__ should always be execution mods ret.pack['__salt__'] = wrapped_ret return wrapped_ret def serializers(opts): ''' Returns the serializers modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only serializers present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'serializers'), opts, tag='serializers', ) def eauth_tokens(opts): ''' Returns the tokens modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only token backends present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'tokens'), opts, tag='tokens', ) def auth(opts, whitelist=None): ''' Returns the auth modules :param dict opts: The Salt options dictionary :returns: LazyLoader ''' return LazyLoader( _module_dirs(opts, 'auth'), opts, tag='auth', whitelist=whitelist, pack={'__salt__': minion_mods(opts)}, ) def fileserver(opts, backends): ''' Returns the file server modules ''' return LazyLoader(_module_dirs(opts, 'fileserver'), opts, tag='fileserver', whitelist=backends, pack={'__utils__': utils(opts)}) def roster(opts, runner=None, utils=None, whitelist=None): ''' Returns the roster modules ''' return LazyLoader( _module_dirs(opts, 'roster'), opts, tag='roster', whitelist=whitelist, pack={ '__runner__': runner, '__utils__': utils, }, ) def thorium(opts, functions, runners): ''' Load the thorium runtime modules ''' pack = {'__salt__': functions, '__runner__': runners, '__context__': {}} ret = LazyLoader(_module_dirs(opts, 'thorium'), opts, tag='thorium', pack=pack) ret.pack['__thorium__'] = ret return ret def states(opts, functions, utils, serializers, whitelist=None, proxy=None, context=None): ''' Returns the state modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') statemods = salt.loader.states(__opts__, None, None) ''' if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'states'), opts, tag='states', pack={'__salt__': functions, '__proxy__': proxy or {}}, whitelist=whitelist, ) ret.pack['__states__'] = ret ret.pack['__utils__'] = utils ret.pack['__serializers__'] = serializers ret.pack['__context__'] = context return ret def beacons(opts, functions, context=None, proxy=None): ''' Load the beacon modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. ''' return LazyLoader( _module_dirs(opts, 'beacons'), opts, tag='beacons', pack={'__context__': context, '__salt__': functions, '__proxy__': proxy or {}}, virtual_funcs=[], ) def log_handlers(opts): ''' Returns the custom logging handler modules :param dict opts: The Salt options dictionary ''' ret = LazyLoader( _module_dirs( opts, 'log_handlers', int_type='handlers', base_path=os.path.join(SALT_BASE_PATH, 'log'), ), opts, tag='log_handlers', ) return FilterDictWrapper(ret, '.setup_handlers') def ssh_wrapper(opts, functions=None, context=None): ''' Returns the custom logging handler modules ''' return LazyLoader( _module_dirs( opts, 'wrapper', base_path=os.path.join(SALT_BASE_PATH, os.path.join('client', 'ssh')), ), opts, tag='wrapper', pack={ '__salt__': functions, '__grains__': opts.get('grains', {}), '__pillar__': opts.get('pillar', {}), '__context__': context, }, ) def render(opts, functions, states=None, proxy=None, context=None): ''' Returns the render modules ''' if context is None: context = {} pack = {'__salt__': functions, '__grains__': opts.get('grains', {}), '__context__': context} if states: pack['__states__'] = states pack['__proxy__'] = proxy or {} ret = LazyLoader( _module_dirs( opts, 'renderers', 'render', ext_type_dirs='render_dirs', ), opts, tag='render', pack=pack, ) rend = FilterDictWrapper(ret, '.render') if not check_render_pipe_str(opts['renderer'], rend, opts['renderer_blacklist'], opts['renderer_whitelist']): err = ('The renderer {0} is unavailable, this error is often because ' 'the needed software is unavailable'.format(opts['renderer'])) log.critical(err) raise LoaderError(err) return rend def grain_funcs(opts, proxy=None): ''' Returns the grain functions .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') grainfuncs = salt.loader.grain_funcs(__opts__) ''' ret = LazyLoader( _module_dirs( opts, 'grains', 'grain', ext_type_dirs='grains_dirs', ), opts, tag='grains', ) ret.pack['__utils__'] = utils(opts, proxy=proxy) return ret def _load_cached_grains(opts, cfn): ''' Returns the grains cached in cfn, or None if the cache is too old or is corrupted. ''' if not os.path.isfile(cfn): log.debug('Grains cache file does not exist.') return None grains_cache_age = int(time.time() - os.path.getmtime(cfn)) if grains_cache_age > opts.get('grains_cache_expiration', 300): log.debug( 'Grains cache last modified %s seconds ago and cache ' 'expiration is set to %s. Grains cache expired. ' 'Refreshing.', grains_cache_age, opts.get('grains_cache_expiration', 300) ) return None if opts.get('refresh_grains_cache', False): log.debug('refresh_grains_cache requested, Refreshing.') return None log.debug('Retrieving grains from cache') try: serial = salt.payload.Serial(opts) with salt.utils.files.fopen(cfn, 'rb') as fp_: cached_grains = salt.utils.data.decode(serial.load(fp_), preserve_tuples=True) if not cached_grains: log.debug('Cached grains are empty, cache might be corrupted. Refreshing.') return None return cached_grains except (IOError, OSError): return None def grains(opts, force_refresh=False, proxy=None): ''' Return the functions for the dynamic grains and the values for the static grains. Since grains are computed early in the startup process, grains functions do not have __salt__ or __proxy__ available. At proxy-minion startup, this function is called with the proxymodule LazyLoader object so grains functions can communicate with their controlled device. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) print __grains__['id'] ''' # Need to re-import salt.config, somehow it got lost when a minion is starting import salt.config # if we have no grains, lets try loading from disk (TODO: move to decorator?) cfn = os.path.join( opts['cachedir'], 'grains.cache.p' ) if not force_refresh and opts.get('grains_cache', False): cached_grains = _load_cached_grains(opts, cfn) if cached_grains: return cached_grains else: log.debug('Grains refresh requested. Refreshing grains.') if opts.get('skip_grains', False): return {} grains_deep_merge = opts.get('grains_deep_merge', False) is True if 'conf_file' in opts: pre_opts = {} pre_opts.update(salt.config.load_config( opts['conf_file'], 'SALT_MINION_CONFIG', salt.config.DEFAULT_MINION_OPTS['conf_file'] )) default_include = pre_opts.get( 'default_include', opts['default_include'] ) include = pre_opts.get('include', []) pre_opts.update(salt.config.include_config( default_include, opts['conf_file'], verbose=False )) pre_opts.update(salt.config.include_config( include, opts['conf_file'], verbose=True )) if 'grains' in pre_opts: opts['grains'] = pre_opts['grains'] else: opts['grains'] = {} else: opts['grains'] = {} grains_data = {} blist = opts.get('grains_blacklist', []) funcs = grain_funcs(opts, proxy=proxy) if force_refresh: # if we refresh, lets reload grain modules funcs.clear() # Run core grains for key in funcs: if not key.startswith('core.'): continue log.trace('Loading %s grain', key) ret = funcs[key]() if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) # Run the rest of the grains for key in funcs: if key.startswith('core.') or key == '_errors': continue try: # Grains are loaded too early to take advantage of the injected # __proxy__ variable. Pass an instance of that LazyLoader # here instead to grains functions if the grains functions take # one parameter. Then the grains can have access to the # proxymodule for retrieving information from the connected # device. log.trace('Loading %s grain', key) parameters = salt.utils.args.get_function_argspec(funcs[key]).args kwargs = {} if 'proxy' in parameters: kwargs['proxy'] = proxy if 'grains' in parameters: kwargs['grains'] = grains_data ret = funcs[key](**kwargs) except Exception: if salt.utils.platform.is_proxy(): log.info('The following CRITICAL message may not be an error; the proxy may not be completely established yet.') log.critical( 'Failed to load grains defined in grain file %s in ' 'function %s, error:\n', key, funcs[key], exc_info=True ) continue if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) if opts.get('proxy_merge_grains_in_module', True) and proxy: try: proxytype = proxy.opts['proxy']['proxytype'] if proxytype + '.grains' in proxy: if proxytype + '.initialized' in proxy and proxy[proxytype + '.initialized'](): try: proxytype = proxy.opts['proxy']['proxytype'] ret = proxy[proxytype + '.grains']() if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) except Exception: log.critical('Failed to run proxy\'s grains function!', exc_info=True ) except KeyError: pass grains_data.update(opts['grains']) # Write cache if enabled if opts.get('grains_cache', False): with salt.utils.files.set_umask(0o077): try: if salt.utils.platform.is_windows(): # Late import import salt.modules.cmdmod # Make sure cache file isn't read-only salt.modules.cmdmod._run_quiet('attrib -R "{0}"'.format(cfn)) with salt.utils.files.fopen(cfn, 'w+b') as fp_: try: serial = salt.payload.Serial(opts) serial.dump(grains_data, fp_) except TypeError as e: log.error('Failed to serialize grains cache: %s', e) raise # re-throw for cleanup except Exception as e: log.error('Unable to write to grains cache file %s: %s', cfn, e) # Based on the original exception, the file may or may not have been # created. If it was, we will remove it now, as the exception means # the serialized data is not to be trusted, no matter what the # exception is. if os.path.isfile(cfn): os.unlink(cfn) if grains_deep_merge: salt.utils.dictupdate.update(grains_data, opts['grains']) else: grains_data.update(opts['grains']) return salt.utils.data.decode(grains_data, preserve_tuples=True) # TODO: get rid of? Does anyone use this? You should use raw() instead def runner(opts, utils=None, context=None, whitelist=None): ''' Directly call a function inside a loader directory ''' if utils is None: utils = {} if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'runners', 'runner', ext_type_dirs='runner_dirs'), opts, tag='runners', pack={'__utils__': utils, '__context__': context}, whitelist=whitelist, ) # TODO: change from __salt__ to something else, we overload __salt__ too much ret.pack['__salt__'] = ret return ret def queues(opts): ''' Directly call a function inside a loader directory ''' return LazyLoader( _module_dirs(opts, 'queues', 'queue', ext_type_dirs='queue_dirs'), opts, tag='queues', ) def sdb(opts, functions=None, whitelist=None, utils=None): ''' Make a very small database call ''' if utils is None: utils = {} return LazyLoader( _module_dirs(opts, 'sdb'), opts, tag='sdb', pack={ '__sdb__': functions, '__opts__': opts, '__utils__': utils, '__salt__': minion_mods(opts, utils), }, whitelist=whitelist, ) def pkgdb(opts): ''' Return modules for SPM's package database .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgdb', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgdb' ) def pkgfiles(opts): ''' Return modules for SPM's file handling .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgfiles', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgfiles' ) def clouds(opts): ''' Return the cloud functions ''' # Let's bring __active_provider_name__, defaulting to None, to all cloud # drivers. This will get temporarily updated/overridden with a context # manager when needed. functions = LazyLoader( _module_dirs(opts, 'clouds', 'cloud', base_path=os.path.join(SALT_BASE_PATH, 'cloud'), int_type='clouds'), opts, tag='clouds', pack={'__utils__': salt.loader.utils(opts), '__active_provider_name__': None}, ) for funcname in LIBCLOUD_FUNCS_NOT_SUPPORTED: log.trace( '\'%s\' has been marked as not supported. Removing from the ' 'list of supported cloud functions', funcname ) functions.pop(funcname, None) return functions def netapi(opts): ''' Return the network api functions ''' return LazyLoader( _module_dirs(opts, 'netapi'), opts, tag='netapi', ) def executors(opts, functions=None, context=None, proxy=None): ''' Returns the executor modules ''' executors = LazyLoader( _module_dirs(opts, 'executors', 'executor'), opts, tag='executor', pack={'__salt__': functions, '__context__': context or {}, '__proxy__': proxy or {}}, ) executors.pack['__executors__'] = executors return executors def cache(opts, serial): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'cache', 'cache'), opts, tag='cache', pack={'__opts__': opts, '__context__': {'serial': serial}}, ) def _generate_module(name): if name in sys.modules: return code = "'''Salt loaded {0} parent module'''".format(name.split('.')[-1]) # ModuleType can't accept a unicode type on PY2 module = types.ModuleType(str(name)) # future lint: disable=blacklisted-function exec(code, module.__dict__) sys.modules[name] = module def _mod_type(module_path): if module_path.startswith(SALT_BASE_PATH): return 'int' return 'ext' def _inject_into_mod(mod, name, value, force_lock=False): ''' Inject a variable into a module. This is used to inject "globals" like ``__salt__``, ``__pillar``, or ``grains``. Instead of injecting the value directly, a ``ThreadLocalProxy`` is created. If such a proxy is already present under the specified name, it is updated with the new value. This update only affects the current thread, so that the same name can refer to different values depending on the thread of execution. This is important for data that is not truly global. For example, pillar data might be dynamically overriden through function parameters and thus the actual values available in pillar might depend on the thread that is calling a module. mod: module object into which the value is going to be injected. name: name of the variable that is injected into the module. value: value that is injected into the variable. The value is not injected directly, but instead set as the new reference of the proxy that has been created for the variable. force_lock: whether the lock should be acquired before checking whether a proxy object for the specified name has already been injected into the module. If ``False`` (the default), this function checks for the module's variable without acquiring the lock and only acquires the lock if a new proxy has to be created and injected. ''' old_value = getattr(mod, name, None) # We use a double-checked locking scheme in order to avoid taking the lock # when a proxy object has already been injected. # In most programming languages, double-checked locking is considered # unsafe when used without explicit memory barriers because one might read # an uninitialized value. In CPython it is safe due to the global # interpreter lock (GIL). In Python implementations that do not have the # GIL, it could be unsafe, but at least Jython also guarantees that (for # Python objects) memory is not corrupted when writing and reading without # explicit synchronization # (http://www.jython.org/jythonbook/en/1.0/Concurrency.html). # Please note that in order to make this code safe in a runtime environment # that does not make this guarantees, it is not sufficient. The # ThreadLocalProxy must also be created with fallback_to_shared set to # False or a lock must be added to the ThreadLocalProxy. if force_lock: with _inject_into_mod.lock: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: setattr(mod, name, ThreadLocalProxy(value, True)) else: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: _inject_into_mod(mod, name, value, True) # Lock used when injecting globals. This is needed to avoid a race condition # when two threads try to load the same module concurrently. This must be # outside the loader because there might be more than one loader for the same # namespace. _inject_into_mod.lock = threading.RLock() # TODO: move somewhere else? class FilterDictWrapper(MutableMapping): ''' Create a dict which wraps another dict with a specific key suffix on get This is to replace "filter_load" ''' def __init__(self, d, suffix): self._dict = d self.suffix = suffix def __setitem__(self, key, val): self._dict[key] = val def __delitem__(self, key): del self._dict[key] def __getitem__(self, key): return self._dict[key + self.suffix] def __len__(self): return len(self._dict) def __iter__(self): for key in self._dict: if key.endswith(self.suffix): yield key.replace(self.suffix, '') class LazyLoader(salt.utils.lazy.LazyDict): ''' A pseduo-dictionary which has a set of keys which are the name of the module and function, delimited by a dot. When the value of the key is accessed, the function is then loaded from disk and into memory. .. note:: Iterating over keys will cause all modules to be loaded. :param list module_dirs: A list of directories on disk to search for modules :param dict opts: The salt options dictionary. :param str tag: The tag for the type of module to load :param func mod_type_check: A function which can be used to verify files :param dict pack: A dictionary of function to be packed into modules as they are loaded :param list whitelist: A list of modules to whitelist :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules. :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality. If not true, the module will not load. :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values are function references themselves which are loaded on-demand. # TODO: - move modules_max_memory into here - singletons (per tag) ''' mod_dict_class = salt.utils.odict.OrderedDict def __init__(self, module_dirs, opts=None, tag='module', loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, proxy=None, virtual_funcs=None, ): # pylint: disable=W0231 ''' In pack, if any of the values are None they will be replaced with an empty context-specific dict ''' self.inject_globals = {} self.pack = {} if pack is None else pack if opts is None: opts = {} threadsafety = not opts.get('multiprocessing') self.context_dict = salt.utils.context.ContextDict(threadsafe=threadsafety) self.opts = self.__prep_mod_opts(opts) self.module_dirs = module_dirs self.tag = tag self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME self.mod_type_check = mod_type_check or _mod_type if '__context__' not in self.pack: self.pack['__context__'] = None for k, v in six.iteritems(self.pack): if v is None: # if the value of a pack is None, lets make an empty dict value = self.context_dict.get(k, {}) if isinstance(value, ThreadLocalProxy): value = ThreadLocalProxy.unproxy(value) self.context_dict[k] = value self.pack[k] = salt.utils.context.NamespacedDictWrapper(self.context_dict, k) self.whitelist = whitelist self.virtual_enable = virtual_enable self.initial_load = True # names of modules that we don't have (errors, __virtual__, etc.) self.missing_modules = {} # mapping of name -> error self.loaded_modules = {} # mapping of module_name -> dict_of_functions self.loaded_files = set() # TODO: just remove them from file_mapping? self.static_modules = static_modules if static_modules else [] if virtual_funcs is None: virtual_funcs = [] self.virtual_funcs = virtual_funcs self.disabled = set( self.opts.get( 'disable_{0}{1}'.format( self.tag, '' if self.tag[-1] == 's' else 's' ), [] ) ) # A map of suffix to description for imp self.suffix_map = {} # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [''] for (suffix, mode, kind) in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) self._lock = threading.RLock() self._refresh_file_mapping() super(LazyLoader, self).__init__() # late init the lazy loader # create all of the import namespaces _generate_module('{0}.int'.format(self.loaded_base_name)) _generate_module('{0}.int.{1}'.format(self.loaded_base_name, tag)) _generate_module('{0}.ext'.format(self.loaded_base_name)) _generate_module('{0}.ext.{1}'.format(self.loaded_base_name, tag)) def __getitem__(self, item): ''' Override the __getitem__ in order to decorate the returned function if we need to last-minute inject globals ''' func = super(LazyLoader, self).__getitem__(item) if self.inject_globals: return global_injector_decorator(self.inject_globals)(func) else: return func def __getattr__(self, mod_name): ''' Allow for "direct" attribute access-- this allows jinja templates to access things like `salt.test.ping()` ''' if mod_name in ('__getstate__', '__setstate__'): return object.__getattribute__(self, mod_name) # if we have an attribute named that, lets return it. try: return object.__getattr__(self, mod_name) # pylint: disable=no-member except AttributeError: pass # otherwise we assume its jinja template access if mod_name not in self.loaded_modules and not self.loaded: for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and mod_name in self.loaded_modules: break if mod_name in self.loaded_modules: return self.loaded_modules[mod_name] else: raise AttributeError(mod_name) def missing_fun_string(self, function_name): ''' Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ''' mod_name = function_name.split('.')[0] if mod_name in self.loaded_modules: return '\'{0}\' is not available.'.format(function_name) else: try: reason = self.missing_modules[mod_name] except KeyError: return '\'{0}\' is not available.'.format(function_name) else: if reason is not None: return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason) else: return '\'{0}\' __virtual__ returned False'.format(mod_name) def _refresh_file_mapping(self): ''' refresh the mapping of the FS on disk ''' # map of suffix to description for imp if self.opts.get('cython_enable', True) is True: try: global pyximport pyximport = __import__('pyximport') # pylint: disable=import-error pyximport.install() # add to suffix_map so file_mapping will pick it up self.suffix_map['.pyx'] = tuple() except ImportError: log.info('Cython is enabled in the options but not present ' 'in the system path. Skipping Cython modules.') # Allow for zipimport of modules if self.opts.get('enable_zip_modules', True) is True: self.suffix_map['.zip'] = tuple() # allow for module dirs if USE_IMPORTLIB: self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY) else: self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY) # create mapping of filename (without suffix) to (path, suffix) # The files are added in order of priority, so order *must* be retained. self.file_mapping = salt.utils.odict.OrderedDict() opt_match = [] def _replace_pre_ext(obj): ''' Hack so we can get the optimization level that we replaced (if any) out of the re.sub call below. We use a list here because it is a persistent data structure that we will be able to access after re.sub is called. ''' opt_match.append(obj) return '' for mod_dir in self.module_dirs: try: # Make sure we have a sorted listdir in order to have # expectable override results files = sorted( x for x in os.listdir(mod_dir) if x != '__pycache__' ) except OSError: continue # Next mod_dir if six.PY3: try: pycache_files = [ os.path.join('__pycache__', x) for x in sorted(os.listdir(os.path.join(mod_dir, '__pycache__'))) ] except OSError: pass else: files.extend(pycache_files) for filename in files: try: dirname, basename = os.path.split(filename) if basename.startswith('_'): # skip private modules # log messages omitted for obviousness continue # Next filename f_noext, ext = os.path.splitext(basename) if six.PY3: f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext) try: opt_level = int( opt_match.pop().group(1).rsplit('-', 1)[-1] ) except (AttributeError, IndexError, ValueError): # No regex match or no optimization level matched opt_level = 0 try: opt_index = self.opts['optimization_order'].index(opt_level) except KeyError: log.trace( 'Disallowed optimization level %d for module ' 'name \'%s\', skipping. Add %d to the ' '\'optimization_order\' config option if you ' 'do not want to ignore this optimization ' 'level.', opt_level, f_noext, opt_level ) continue else: # Optimization level not reflected in filename on PY2 opt_index = 0 # make sure it is a suffix we support if ext not in self.suffix_map: continue # Next filename if f_noext in self.disabled: log.trace( 'Skipping %s, it is disabled by configuration', filename ) continue # Next filename fpath = os.path.join(mod_dir, filename) # if its a directory, lets allow us to load that if ext == '': # is there something __init__? subfiles = os.listdir(fpath) for suffix in self.suffix_order: if '' == suffix: continue # Next suffix (__init__ must have a suffix) init_file = '__init__{0}'.format(suffix) if init_file in subfiles: break else: continue # Next filename try: curr_ext = self.file_mapping[f_noext][1] curr_opt_index = self.file_mapping[f_noext][2] except KeyError: pass else: if '' in (curr_ext, ext) and curr_ext != ext: log.error( 'Module/package collision: \'%s\' and \'%s\'', fpath, self.file_mapping[f_noext][0] ) if six.PY3 and ext == '.pyc' and curr_ext == '.pyc': # Check the optimization level if opt_index >= curr_opt_index: # Module name match, but a higher-priority # optimization level was already matched, skipping. continue elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext): # Match found but a higher-priorty match already # exists, so skip this. continue if six.PY3 and not dirname and ext == '.pyc': # On Python 3, we should only load .pyc files from the # __pycache__ subdirectory (i.e. when dirname is not an # empty string). continue # Made it this far - add it self.file_mapping[f_noext] = (fpath, ext, opt_index) except OSError: continue for smod in self.static_modules: f_noext = smod.split('.')[-1] self.file_mapping[f_noext] = (smod, '.o', 0) def clear(self): ''' Clear the dict ''' with self._lock: super(LazyLoader, self).clear() # clear the lazy loader self.loaded_files = set() self.missing_modules = {} self.loaded_modules = {} # if we have been loaded before, lets clear the file mapping since # we obviously want a re-do if hasattr(self, 'opts'): self._refresh_file_mapping() self.initial_load = False def __prep_mod_opts(self, opts): ''' Strip out of the opts any logger instance ''' if '__grains__' not in self.pack: grains = opts.get('grains', {}) if isinstance(grains, ThreadLocalProxy): grains = ThreadLocalProxy.unproxy(grains) self.context_dict['grains'] = grains self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains') if '__pillar__' not in self.pack: pillar = opts.get('pillar', {}) if isinstance(pillar, ThreadLocalProxy): pillar = ThreadLocalProxy.unproxy(pillar) self.context_dict['pillar'] = pillar self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar') mod_opts = {} for key, val in list(opts.items()): if key == 'logger': continue mod_opts[key] = val return mod_opts def _iter_files(self, mod_name): ''' Iterate over all file_mapping files in order of closeness to mod_name ''' # do we have an exact match? if mod_name in self.file_mapping: yield mod_name # do we have a partial match? for k in self.file_mapping: if mod_name in k: yield k # anyone else? Bueller? for k in self.file_mapping: if mod_name not in k: yield k def _reload_submodules(self, mod): submodules = ( getattr(mod, sname) for sname in dir(mod) if isinstance(getattr(mod, sname), mod.__class__) ) # reload only custom "sub"modules for submodule in submodules: # it is a submodule if the name is in a namespace under mod if submodule.__name__.startswith(mod.__name__ + '.'): reload_module(submodule) self._reload_submodules(submodule) def _load_module(self, name): mod = None fpath, suffix = self.file_mapping[name][:2] self.loaded_files.add(name) fpath_dirname = os.path.dirname(fpath) try: sys.path.append(fpath_dirname) if suffix == '.pyx': mod = pyximport.load_module(name, fpath, tempfile.gettempdir()) elif suffix == '.o': top_mod = __import__(fpath, globals(), locals(), []) comps = fpath.split('.') if len(comps) < 2: mod = top_mod else: mod = top_mod for subname in comps[1:]: mod = getattr(mod, subname) elif suffix == '.zip': mod = zipimporter(fpath).load_module(name) else: desc = self.suffix_map[suffix] # if it is a directory, we don't open a file try: mod_namespace = '.'.join(( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name)) except TypeError: mod_namespace = '{0}.{1}.{2}.{3}'.format( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name) if suffix == '': if USE_IMPORTLIB: # pylint: disable=no-member # Package directory, look for __init__ loader_details = [ (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES), (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES), (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), ] file_finder = importlib.machinery.FileFinder( fpath_dirname, *loader_details ) spec = file_finder.find_spec(mod_namespace) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: mod = imp.load_module(mod_namespace, None, fpath, desc) # reload all submodules if necessary if not self.initial_load: self._reload_submodules(mod) else: if USE_IMPORTLIB: # pylint: disable=no-member loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath) spec = importlib.util.spec_from_file_location( mod_namespace, fpath, loader=loader ) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() #mod = importlib.util.module_from_spec(spec) #spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: with salt.utils.files.fopen(fpath, desc[1]) as fn_: mod = imp.load_module(mod_namespace, fn_, fpath, desc) except IOError: raise except ImportError as exc: if 'magic number' in six.text_type(exc): error_msg = 'Failed to import {0} {1}. Bad magic number. If migrating from Python2 to Python3, remove all .pyc files and try again.'.format(self.tag, name) log.warning(error_msg) self.missing_modules[name] = error_msg log.debug( 'Failed to import %s %s:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = exc return False except Exception as error: log.error( 'Failed to import %s %s, this is due most likely to a ' 'syntax error:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False except SystemExit as error: try: fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1] except Exception: pass else: tgt_fn = os.path.join('salt', 'utils', 'process.py') if fn_.endswith(tgt_fn) and '_handle_signals' in caller: # Race conditon, SIGTERM or SIGINT received while loader # was in process of loading a module. Call sys.exit to # ensure that the process is killed. sys.exit(salt.defaults.exitcodes.EX_OK) log.error( 'Failed to import %s %s as the module called exit()\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False finally: sys.path.remove(fpath_dirname) if hasattr(mod, '__opts__'): mod.__opts__.update(self.opts) else: mod.__opts__ = self.opts # pack whatever other globals we were asked to for p_name, p_value in six.iteritems(self.pack): _inject_into_mod(mod, p_name, p_value) module_name = mod.__name__.rsplit('.', 1)[-1] # Call a module's initialization method if it exists module_init = getattr(mod, '__init__', None) if inspect.isfunction(module_init): try: module_init(self.opts) except TypeError as e: log.error(e) except Exception: err_string = '__init__ failed' log.debug( 'Error loading %s.%s: %s', self.tag, module_name, err_string, exc_info=True ) self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False # if virtual modules are enabled, we need to look for the # __virtual__() function inside that module and run it. if self.virtual_enable: virtual_funcs_to_process = ['__virtual__'] + self.virtual_funcs for virtual_func in virtual_funcs_to_process: virtual_ret, module_name, virtual_err, virtual_aliases = \ self._process_virtual(mod, module_name, virtual_func) if virtual_err is not None: log.trace( 'Error loading %s.%s: %s', self.tag, module_name, virtual_err ) # if _process_virtual returned a non-True value then we are # supposed to not process this module if virtual_ret is not True and module_name not in self.missing_modules: # If a module has information about why it could not be loaded, record it self.missing_modules[module_name] = virtual_err self.missing_modules[name] = virtual_err return False else: virtual_aliases = () # If this is a proxy minion then MOST modules cannot work. Therefore, require that # any module that does work with salt-proxy-minion define __proxyenabled__ as a list # containing the names of the proxy types that the module supports. # # Render modules and state modules are OK though if 'proxy' in self.opts: if self.tag in ['grains', 'proxy']: if not hasattr(mod, '__proxyenabled__') or \ (self.opts['proxy']['proxytype'] not in mod.__proxyenabled__ and '*' not in mod.__proxyenabled__): err_string = 'not a proxy_minion enabled module' self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False if getattr(mod, '__load__', False) is not False: log.info( 'The functions from module \'%s\' are being loaded from the ' 'provided __load__ attribute', module_name ) # If we had another module by the same virtual name, we should put any # new functions under the existing dictionary. mod_names = [module_name] + list(virtual_aliases) mod_dict = dict(( (x, self.loaded_modules.get(x, self.mod_dict_class())) for x in mod_names )) for attr in getattr(mod, '__load__', dir(mod)): if attr.startswith('_') and attr != '__call__': # private functions are skipped, # except __call__ which is default entrance # for multi-function batch-like state syntax continue func = getattr(mod, attr) if not inspect.isfunction(func) and not isinstance(func, functools.partial): # Not a function!? Skip it!!! continue # Let's get the function name. # If the module has the __func_alias__ attribute, it must be a # dictionary mapping in the form of(key -> value): # <real-func-name> -> <desired-func-name> # # It default's of course to the found callable attribute name # if no alias is defined. funcname = getattr(mod, '__func_alias__', {}).get(attr, attr) for tgt_mod in mod_names: try: full_funcname = '.'.join((tgt_mod, funcname)) except TypeError: full_funcname = '{0}.{1}'.format(tgt_mod, funcname) # Save many references for lookups # Careful not to overwrite existing (higher priority) functions if full_funcname not in self._dict: self._dict[full_funcname] = func if funcname not in mod_dict[tgt_mod]: setattr(mod_dict[tgt_mod], funcname, func) mod_dict[tgt_mod][funcname] = func self._apply_outputter(func, mod) # enforce depends try: Depends.enforce_dependencies(self._dict, self.tag) except RuntimeError as exc: log.info( 'Depends.enforce_dependencies() failed for the following ' 'reason: %s', exc ) for tgt_mod in mod_names: self.loaded_modules[tgt_mod] = mod_dict[tgt_mod] return True def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise KeyError('The key \'{0}\' should contain a \'.\''.format(key)) mod_name, _ = key.split('.', 1) with self._lock: # It is possible that the key is in the dictionary after # acquiring the lock due to another thread loading it. if mod_name in self.missing_modules or key in self._dict: return True # if the modulename isn't in the whitelist, don't bother if self.whitelist and mod_name not in self.whitelist: log.error( 'Failed to load function %s because its module (%s) is ' 'not in the whitelist: %s', key, mod_name, self.whitelist ) raise KeyError(key) def _inner_load(mod_name): for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and key in self._dict: return True return False # try to load the module ret = None reloaded = False # re-scan up to once, IOErrors or a failed load cause re-scans of the # filesystem while True: try: ret = _inner_load(mod_name) if not reloaded and ret is not True: self._refresh_file_mapping() reloaded = True continue break except IOError: if not reloaded: self._refresh_file_mapping() reloaded = True continue return ret def _load_all(self): ''' Load all of them ''' with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True def reload_modules(self): with self._lock: self.loaded_files = set() self._load_all() def _apply_outputter(self, func, mod): ''' Apply the __outputter__ variable to the functions ''' if hasattr(mod, '__outputter__'): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__] def _process_virtual(self, mod, module_name, virtual_func='__virtual__'): ''' Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1] ''' # The __virtual__ function will return either a True or False value. # If it returns a True value it can also set a module level attribute # named __virtualname__ with the name that the module should be # referred to as. # # This allows us to have things like the pkg module working on all # platforms under the name 'pkg'. It also allows for modules like # augeas_cfg to be referred to as 'augeas', which would otherwise have # namespace collisions. And finally it allows modules to return False # if they are not intended to run on the given platform or are missing # dependencies. virtual_aliases = getattr(mod, '__virtual_aliases__', tuple()) try: error_reason = None if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__): try: start = time.time() virtual = getattr(mod, virtual_func)() if isinstance(virtual, tuple): error_reason = virtual[1] virtual = virtual[0] if self.opts.get('virtual_timer', False): end = time.time() - start msg = 'Virtual function took {0} seconds for {1}'.format( end, module_name) log.warning(msg) except Exception as exc: error_reason = ( 'Exception raised when processing __virtual__ function' ' for {0}. Module will not be loaded: {1}'.format( mod.__name__, exc)) log.error(error_reason, exc_info_on_loglevel=logging.DEBUG) virtual = None # Get the module's virtual name virtualname = getattr(mod, '__virtualname__', virtual) if not virtual: # if __virtual__() evaluates to False then the module # wasn't meant for this platform or it's not supposed to # load for some other reason. # Some modules might accidentally return None and are # improperly loaded if virtual is None: log.warning( '%s.__virtual__() is wrongly returning `None`. ' 'It should either return `True`, `False` or a new ' 'name. If you\'re the developer of the module ' '\'%s\', please fix this.', mod.__name__, module_name ) return (False, module_name, error_reason, virtual_aliases) # At this point, __virtual__ did not return a # boolean value, let's check for deprecated usage # or module renames if virtual is not True and module_name != virtual: # The module is renaming itself. Updating the module name # with the new name log.trace('Loaded %s as virtual %s', module_name, virtual) if virtualname != virtual: # The __virtualname__ attribute does not match what's # being returned by the __virtual__() function. This # should be considered an error. log.error( 'The module \'%s\' is showing some bad usage. Its ' '__virtualname__ attribute is set to \'%s\' yet the ' '__virtual__() function is returning \'%s\'. These ' 'values should match!', mod.__name__, virtualname, virtual ) module_name = virtualname # If the __virtual__ function returns True and __virtualname__ # is set then use it elif virtual is True and virtualname != module_name: if virtualname is not True: module_name = virtualname except KeyError: # Key errors come out of the virtual function when passing # in incomplete grains sets, these can be safely ignored # and logged to debug, still, it includes the traceback to # help debugging. log.debug('KeyError when loading %s', module_name, exc_info=True) except Exception: # If the module throws an exception during __virtual__() # then log the information and continue to the next. log.error( 'Failed to read the virtual function for %s: %s', self.tag, module_name, exc_info=True ) return (False, module_name, error_reason, virtual_aliases) return (True, module_name, None, virtual_aliases) def global_injector_decorator(inject_globals): ''' Decorator used by the LazyLoader to inject globals into a function at execute time. globals Dictionary with global variables to inject ''' def inner_decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): with salt.utils.context.func_globals_inject(f, **inject_globals): return f(*args, **kwargs) return wrapper return inner_decorator
saltstack/salt
salt/loader.py
runner
python
def runner(opts, utils=None, context=None, whitelist=None): ''' Directly call a function inside a loader directory ''' if utils is None: utils = {} if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'runners', 'runner', ext_type_dirs='runner_dirs'), opts, tag='runners', pack={'__utils__': utils, '__context__': context}, whitelist=whitelist, ) # TODO: change from __salt__ to something else, we overload __salt__ too much ret.pack['__salt__'] = ret return ret
Directly call a function inside a loader directory
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L929-L946
null
# -*- coding: utf-8 -*- ''' The Salt loader is the core to Salt's plugin system, the loader scans directories for python loadable code and organizes the code into the plugin interfaces used by Salt. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import sys import time import logging import inspect import tempfile import threading import functools import threading import traceback import types from zipimport import zipimporter # Import salt libs import salt.config import salt.defaults.events import salt.defaults.exitcodes import salt.syspaths import salt.utils.args import salt.utils.context import salt.utils.data import salt.utils.dictupdate import salt.utils.event import salt.utils.files import salt.utils.lazy import salt.utils.odict import salt.utils.platform import salt.utils.versions import salt.utils.stringutils from salt.exceptions import LoaderError from salt.template import check_render_pipe_str from salt.utils.decorators import Depends from salt.utils.thread_local_proxy import ThreadLocalProxy # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import reload_module if sys.version_info[:2] >= (3, 5): import importlib.machinery # pylint: disable=no-name-in-module,import-error import importlib.util # pylint: disable=no-name-in-module,import-error USE_IMPORTLIB = True else: import imp USE_IMPORTLIB = False try: from collections.abc import MutableMapping except ImportError: from collections import MutableMapping try: import pkg_resources HAS_PKG_RESOURCES = True except ImportError: HAS_PKG_RESOURCES = False log = logging.getLogger(__name__) SALT_BASE_PATH = os.path.abspath(salt.syspaths.INSTALL_DIR) LOADED_BASE_NAME = 'salt.loaded' if USE_IMPORTLIB: # pylint: disable=no-member MODULE_KIND_SOURCE = 1 MODULE_KIND_COMPILED = 2 MODULE_KIND_EXTENSION = 3 MODULE_KIND_PKG_DIRECTORY = 5 SUFFIXES = [] for suffix in importlib.machinery.EXTENSION_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_EXTENSION)) for suffix in importlib.machinery.SOURCE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_SOURCE)) for suffix in importlib.machinery.BYTECODE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_COMPILED)) MODULE_KIND_MAP = { MODULE_KIND_SOURCE: importlib.machinery.SourceFileLoader, MODULE_KIND_COMPILED: importlib.machinery.SourcelessFileLoader, MODULE_KIND_EXTENSION: importlib.machinery.ExtensionFileLoader } # pylint: enable=no-member else: SUFFIXES = imp.get_suffixes() PY3_PRE_EXT = \ re.compile(r'\.cpython-{0}{1}(\.opt-[1-9])?'.format(*sys.version_info[:2])) # Because on the cloud drivers we do `from salt.cloud.libcloudfuncs import *` # which simplifies code readability, it adds some unsupported functions into # the driver's module scope. # We list un-supported functions here. These will be removed from the loaded. # TODO: remove the need for this cross-module code. Maybe use NotImplemented LIBCLOUD_FUNCS_NOT_SUPPORTED = ( 'parallels.avail_sizes', 'parallels.avail_locations', 'proxmox.avail_sizes', ) # Will be set to pyximport module at runtime if cython is enabled in config. pyximport = None def static_loader( opts, ext_type, tag, pack=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, filter_name=None, ): funcs = LazyLoader( _module_dirs( opts, ext_type, tag, int_type, ext_dirs, ext_type_dirs, base_path, ), opts, tag=tag, pack=pack, ) ret = {} funcs._load_all() if filter_name: funcs = FilterDictWrapper(funcs, filter_name) for key in funcs: ret[key] = funcs[key] return ret def _format_entrypoint_target(ep): ''' Makes a string describing the target of an EntryPoint object. Base strongly on EntryPoint.__str__(). ''' s = ep.module_name if ep.attrs: s += ':' + '.'.join(ep.attrs) return s def _module_dirs( opts, ext_type, tag=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, ): if tag is None: tag = ext_type sys_types = os.path.join(base_path or SALT_BASE_PATH, int_type or ext_type) ext_types = os.path.join(opts['extension_modules'], ext_type) ext_type_types = [] if ext_dirs: if ext_type_dirs is None: ext_type_dirs = '{0}_dirs'.format(tag) if ext_type_dirs in opts: ext_type_types.extend(opts[ext_type_dirs]) if HAS_PKG_RESOURCES and ext_type_dirs: for entry_point in pkg_resources.iter_entry_points('salt.loader', ext_type_dirs): try: loaded_entry_point = entry_point.load() for path in loaded_entry_point(): ext_type_types.append(path) except Exception as exc: log.error("Error getting module directories from %s: %s", _format_entrypoint_target(entry_point), exc) log.debug("Full backtrace for module directories error", exc_info=True) cli_module_dirs = [] # The dirs can be any module dir, or a in-tree _{ext_type} dir for _dir in opts.get('module_dirs', []): # Prepend to the list to match cli argument ordering maybe_dir = os.path.join(_dir, ext_type) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) continue maybe_dir = os.path.join(_dir, '_{0}'.format(ext_type)) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) return cli_module_dirs + ext_type_types + [ext_types, sys_types] def minion_mods( opts, context=None, utils=None, whitelist=None, initial_load=False, loaded_base_name=None, notify=False, static_modules=None, proxy=None): ''' Load execution modules Returns a dictionary of execution modules appropriate for the current system by evaluating the __virtual__() function in each module. :param dict opts: The Salt options dictionary :param dict context: A Salt context that should be made present inside generated modules in __context__ :param dict utils: Utility functions which should be made available to Salt modules in __utils__. See `utils_dirs` in salt.config for additional information about configuration. :param list whitelist: A list of modules which should be whitelisted. :param bool initial_load: Deprecated flag! Unused. :param str loaded_base_name: A string marker for the loaded base name. :param bool notify: Flag indicating that an event should be fired upon completion of module loading. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) __opts__['grains'] = __grains__ __utils__ = salt.loader.utils(__opts__) __salt__ = salt.loader.minion_mods(__opts__, utils=__utils__) __salt__['test.ping']() ''' # TODO Publish documentation for module whitelisting if not whitelist: whitelist = opts.get('whitelist_modules', None) ret = LazyLoader( _module_dirs(opts, 'modules', 'module'), opts, tag='module', pack={'__context__': context, '__utils__': utils, '__proxy__': proxy}, whitelist=whitelist, loaded_base_name=loaded_base_name, static_modules=static_modules, ) ret.pack['__salt__'] = ret # Load any provider overrides from the configuration file providers option # Note: Providers can be pkg, service, user or group - not to be confused # with cloud providers. providers = opts.get('providers', False) if providers and isinstance(providers, dict): for mod in providers: # sometimes providers opts is not to diverge modules but # for other configuration try: funcs = raw_mod(opts, providers[mod], ret) except TypeError: break else: if funcs: for func in funcs: f_key = '{0}{1}'.format(mod, func[func.rindex('.'):]) ret[f_key] = funcs[func] if notify: evt = salt.utils.event.get_event('minion', opts=opts, listen=False) evt.fire_event({'complete': True}, tag=salt.defaults.events.MINION_MOD_COMPLETE) return ret def raw_mod(opts, name, functions, mod='modules'): ''' Returns a single module loaded raw and bypassing the __virtual__ function .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') testmod = salt.loader.raw_mod(__opts__, 'test', None) testmod['test.ping']() ''' loader = LazyLoader( _module_dirs(opts, mod, 'module'), opts, tag='rawmodule', virtual_enable=False, pack={'__salt__': functions}, ) # if we don't have the module, return an empty dict if name not in loader.file_mapping: return {} loader._load_module(name) # load a single module (the one passed in) return dict(loader._dict) # return a copy of *just* the funcs for `name` def metaproxy(opts): ''' Return functions used in the meta proxy ''' return LazyLoader( _module_dirs(opts, 'metaproxy'), opts, tag='metaproxy' ) def matchers(opts): ''' Return the matcher services plugins ''' return LazyLoader( _module_dirs(opts, 'matchers'), opts, tag='matchers' ) def engines(opts, functions, runners, utils, proxy=None): ''' Return the master services plugins ''' pack = {'__salt__': functions, '__runners__': runners, '__proxy__': proxy, '__utils__': utils} return LazyLoader( _module_dirs(opts, 'engines'), opts, tag='engines', pack=pack, ) def proxy(opts, functions=None, returners=None, whitelist=None, utils=None): ''' Returns the proxy module for this salt-proxy-minion ''' ret = LazyLoader( _module_dirs(opts, 'proxy'), opts, tag='proxy', pack={'__salt__': functions, '__ret__': returners, '__utils__': utils}, ) ret.pack['__proxy__'] = ret return ret def returners(opts, functions, whitelist=None, context=None, proxy=None): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'returners', 'returner'), opts, tag='returner', whitelist=whitelist, pack={'__salt__': functions, '__context__': context, '__proxy__': proxy or {}}, ) def utils(opts, whitelist=None, context=None, proxy=proxy): ''' Returns the utility modules ''' return LazyLoader( _module_dirs(opts, 'utils', ext_type_dirs='utils_dirs'), opts, tag='utils', whitelist=whitelist, pack={'__context__': context, '__proxy__': proxy or {}}, ) def pillars(opts, functions, context=None): ''' Returns the pillars modules ''' ret = LazyLoader(_module_dirs(opts, 'pillar'), opts, tag='pillar', pack={'__salt__': functions, '__context__': context, '__utils__': utils(opts)}) ret.pack['__ext_pillar__'] = ret return FilterDictWrapper(ret, '.ext_pillar') def tops(opts): ''' Returns the tops modules ''' if 'master_tops' not in opts: return {} whitelist = list(opts['master_tops'].keys()) ret = LazyLoader( _module_dirs(opts, 'tops', 'top'), opts, tag='top', whitelist=whitelist, ) return FilterDictWrapper(ret, '.top') def wheels(opts, whitelist=None, context=None): ''' Returns the wheels modules ''' if context is None: context = {} return LazyLoader( _module_dirs(opts, 'wheel'), opts, tag='wheel', whitelist=whitelist, pack={'__context__': context}, ) def outputters(opts): ''' Returns the outputters modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only outputters present in the keyspace ''' ret = LazyLoader( _module_dirs(opts, 'output', ext_type_dirs='outputter_dirs'), opts, tag='output', ) wrapped_ret = FilterDictWrapper(ret, '.output') # TODO: this name seems terrible... __salt__ should always be execution mods ret.pack['__salt__'] = wrapped_ret return wrapped_ret def serializers(opts): ''' Returns the serializers modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only serializers present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'serializers'), opts, tag='serializers', ) def eauth_tokens(opts): ''' Returns the tokens modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only token backends present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'tokens'), opts, tag='tokens', ) def auth(opts, whitelist=None): ''' Returns the auth modules :param dict opts: The Salt options dictionary :returns: LazyLoader ''' return LazyLoader( _module_dirs(opts, 'auth'), opts, tag='auth', whitelist=whitelist, pack={'__salt__': minion_mods(opts)}, ) def fileserver(opts, backends): ''' Returns the file server modules ''' return LazyLoader(_module_dirs(opts, 'fileserver'), opts, tag='fileserver', whitelist=backends, pack={'__utils__': utils(opts)}) def roster(opts, runner=None, utils=None, whitelist=None): ''' Returns the roster modules ''' return LazyLoader( _module_dirs(opts, 'roster'), opts, tag='roster', whitelist=whitelist, pack={ '__runner__': runner, '__utils__': utils, }, ) def thorium(opts, functions, runners): ''' Load the thorium runtime modules ''' pack = {'__salt__': functions, '__runner__': runners, '__context__': {}} ret = LazyLoader(_module_dirs(opts, 'thorium'), opts, tag='thorium', pack=pack) ret.pack['__thorium__'] = ret return ret def states(opts, functions, utils, serializers, whitelist=None, proxy=None, context=None): ''' Returns the state modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') statemods = salt.loader.states(__opts__, None, None) ''' if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'states'), opts, tag='states', pack={'__salt__': functions, '__proxy__': proxy or {}}, whitelist=whitelist, ) ret.pack['__states__'] = ret ret.pack['__utils__'] = utils ret.pack['__serializers__'] = serializers ret.pack['__context__'] = context return ret def beacons(opts, functions, context=None, proxy=None): ''' Load the beacon modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. ''' return LazyLoader( _module_dirs(opts, 'beacons'), opts, tag='beacons', pack={'__context__': context, '__salt__': functions, '__proxy__': proxy or {}}, virtual_funcs=[], ) def log_handlers(opts): ''' Returns the custom logging handler modules :param dict opts: The Salt options dictionary ''' ret = LazyLoader( _module_dirs( opts, 'log_handlers', int_type='handlers', base_path=os.path.join(SALT_BASE_PATH, 'log'), ), opts, tag='log_handlers', ) return FilterDictWrapper(ret, '.setup_handlers') def ssh_wrapper(opts, functions=None, context=None): ''' Returns the custom logging handler modules ''' return LazyLoader( _module_dirs( opts, 'wrapper', base_path=os.path.join(SALT_BASE_PATH, os.path.join('client', 'ssh')), ), opts, tag='wrapper', pack={ '__salt__': functions, '__grains__': opts.get('grains', {}), '__pillar__': opts.get('pillar', {}), '__context__': context, }, ) def render(opts, functions, states=None, proxy=None, context=None): ''' Returns the render modules ''' if context is None: context = {} pack = {'__salt__': functions, '__grains__': opts.get('grains', {}), '__context__': context} if states: pack['__states__'] = states pack['__proxy__'] = proxy or {} ret = LazyLoader( _module_dirs( opts, 'renderers', 'render', ext_type_dirs='render_dirs', ), opts, tag='render', pack=pack, ) rend = FilterDictWrapper(ret, '.render') if not check_render_pipe_str(opts['renderer'], rend, opts['renderer_blacklist'], opts['renderer_whitelist']): err = ('The renderer {0} is unavailable, this error is often because ' 'the needed software is unavailable'.format(opts['renderer'])) log.critical(err) raise LoaderError(err) return rend def grain_funcs(opts, proxy=None): ''' Returns the grain functions .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') grainfuncs = salt.loader.grain_funcs(__opts__) ''' ret = LazyLoader( _module_dirs( opts, 'grains', 'grain', ext_type_dirs='grains_dirs', ), opts, tag='grains', ) ret.pack['__utils__'] = utils(opts, proxy=proxy) return ret def _load_cached_grains(opts, cfn): ''' Returns the grains cached in cfn, or None if the cache is too old or is corrupted. ''' if not os.path.isfile(cfn): log.debug('Grains cache file does not exist.') return None grains_cache_age = int(time.time() - os.path.getmtime(cfn)) if grains_cache_age > opts.get('grains_cache_expiration', 300): log.debug( 'Grains cache last modified %s seconds ago and cache ' 'expiration is set to %s. Grains cache expired. ' 'Refreshing.', grains_cache_age, opts.get('grains_cache_expiration', 300) ) return None if opts.get('refresh_grains_cache', False): log.debug('refresh_grains_cache requested, Refreshing.') return None log.debug('Retrieving grains from cache') try: serial = salt.payload.Serial(opts) with salt.utils.files.fopen(cfn, 'rb') as fp_: cached_grains = salt.utils.data.decode(serial.load(fp_), preserve_tuples=True) if not cached_grains: log.debug('Cached grains are empty, cache might be corrupted. Refreshing.') return None return cached_grains except (IOError, OSError): return None def grains(opts, force_refresh=False, proxy=None): ''' Return the functions for the dynamic grains and the values for the static grains. Since grains are computed early in the startup process, grains functions do not have __salt__ or __proxy__ available. At proxy-minion startup, this function is called with the proxymodule LazyLoader object so grains functions can communicate with their controlled device. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) print __grains__['id'] ''' # Need to re-import salt.config, somehow it got lost when a minion is starting import salt.config # if we have no grains, lets try loading from disk (TODO: move to decorator?) cfn = os.path.join( opts['cachedir'], 'grains.cache.p' ) if not force_refresh and opts.get('grains_cache', False): cached_grains = _load_cached_grains(opts, cfn) if cached_grains: return cached_grains else: log.debug('Grains refresh requested. Refreshing grains.') if opts.get('skip_grains', False): return {} grains_deep_merge = opts.get('grains_deep_merge', False) is True if 'conf_file' in opts: pre_opts = {} pre_opts.update(salt.config.load_config( opts['conf_file'], 'SALT_MINION_CONFIG', salt.config.DEFAULT_MINION_OPTS['conf_file'] )) default_include = pre_opts.get( 'default_include', opts['default_include'] ) include = pre_opts.get('include', []) pre_opts.update(salt.config.include_config( default_include, opts['conf_file'], verbose=False )) pre_opts.update(salt.config.include_config( include, opts['conf_file'], verbose=True )) if 'grains' in pre_opts: opts['grains'] = pre_opts['grains'] else: opts['grains'] = {} else: opts['grains'] = {} grains_data = {} blist = opts.get('grains_blacklist', []) funcs = grain_funcs(opts, proxy=proxy) if force_refresh: # if we refresh, lets reload grain modules funcs.clear() # Run core grains for key in funcs: if not key.startswith('core.'): continue log.trace('Loading %s grain', key) ret = funcs[key]() if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) # Run the rest of the grains for key in funcs: if key.startswith('core.') or key == '_errors': continue try: # Grains are loaded too early to take advantage of the injected # __proxy__ variable. Pass an instance of that LazyLoader # here instead to grains functions if the grains functions take # one parameter. Then the grains can have access to the # proxymodule for retrieving information from the connected # device. log.trace('Loading %s grain', key) parameters = salt.utils.args.get_function_argspec(funcs[key]).args kwargs = {} if 'proxy' in parameters: kwargs['proxy'] = proxy if 'grains' in parameters: kwargs['grains'] = grains_data ret = funcs[key](**kwargs) except Exception: if salt.utils.platform.is_proxy(): log.info('The following CRITICAL message may not be an error; the proxy may not be completely established yet.') log.critical( 'Failed to load grains defined in grain file %s in ' 'function %s, error:\n', key, funcs[key], exc_info=True ) continue if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) if opts.get('proxy_merge_grains_in_module', True) and proxy: try: proxytype = proxy.opts['proxy']['proxytype'] if proxytype + '.grains' in proxy: if proxytype + '.initialized' in proxy and proxy[proxytype + '.initialized'](): try: proxytype = proxy.opts['proxy']['proxytype'] ret = proxy[proxytype + '.grains']() if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) except Exception: log.critical('Failed to run proxy\'s grains function!', exc_info=True ) except KeyError: pass grains_data.update(opts['grains']) # Write cache if enabled if opts.get('grains_cache', False): with salt.utils.files.set_umask(0o077): try: if salt.utils.platform.is_windows(): # Late import import salt.modules.cmdmod # Make sure cache file isn't read-only salt.modules.cmdmod._run_quiet('attrib -R "{0}"'.format(cfn)) with salt.utils.files.fopen(cfn, 'w+b') as fp_: try: serial = salt.payload.Serial(opts) serial.dump(grains_data, fp_) except TypeError as e: log.error('Failed to serialize grains cache: %s', e) raise # re-throw for cleanup except Exception as e: log.error('Unable to write to grains cache file %s: %s', cfn, e) # Based on the original exception, the file may or may not have been # created. If it was, we will remove it now, as the exception means # the serialized data is not to be trusted, no matter what the # exception is. if os.path.isfile(cfn): os.unlink(cfn) if grains_deep_merge: salt.utils.dictupdate.update(grains_data, opts['grains']) else: grains_data.update(opts['grains']) return salt.utils.data.decode(grains_data, preserve_tuples=True) # TODO: get rid of? Does anyone use this? You should use raw() instead def call(fun, **kwargs): ''' Directly call a function inside a loader directory ''' args = kwargs.get('args', []) dirs = kwargs.get('dirs', []) funcs = LazyLoader( [os.path.join(SALT_BASE_PATH, 'modules')] + dirs, None, tag='modules', virtual_enable=False, ) return funcs[fun](*args) def queues(opts): ''' Directly call a function inside a loader directory ''' return LazyLoader( _module_dirs(opts, 'queues', 'queue', ext_type_dirs='queue_dirs'), opts, tag='queues', ) def sdb(opts, functions=None, whitelist=None, utils=None): ''' Make a very small database call ''' if utils is None: utils = {} return LazyLoader( _module_dirs(opts, 'sdb'), opts, tag='sdb', pack={ '__sdb__': functions, '__opts__': opts, '__utils__': utils, '__salt__': minion_mods(opts, utils), }, whitelist=whitelist, ) def pkgdb(opts): ''' Return modules for SPM's package database .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgdb', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgdb' ) def pkgfiles(opts): ''' Return modules for SPM's file handling .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgfiles', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgfiles' ) def clouds(opts): ''' Return the cloud functions ''' # Let's bring __active_provider_name__, defaulting to None, to all cloud # drivers. This will get temporarily updated/overridden with a context # manager when needed. functions = LazyLoader( _module_dirs(opts, 'clouds', 'cloud', base_path=os.path.join(SALT_BASE_PATH, 'cloud'), int_type='clouds'), opts, tag='clouds', pack={'__utils__': salt.loader.utils(opts), '__active_provider_name__': None}, ) for funcname in LIBCLOUD_FUNCS_NOT_SUPPORTED: log.trace( '\'%s\' has been marked as not supported. Removing from the ' 'list of supported cloud functions', funcname ) functions.pop(funcname, None) return functions def netapi(opts): ''' Return the network api functions ''' return LazyLoader( _module_dirs(opts, 'netapi'), opts, tag='netapi', ) def executors(opts, functions=None, context=None, proxy=None): ''' Returns the executor modules ''' executors = LazyLoader( _module_dirs(opts, 'executors', 'executor'), opts, tag='executor', pack={'__salt__': functions, '__context__': context or {}, '__proxy__': proxy or {}}, ) executors.pack['__executors__'] = executors return executors def cache(opts, serial): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'cache', 'cache'), opts, tag='cache', pack={'__opts__': opts, '__context__': {'serial': serial}}, ) def _generate_module(name): if name in sys.modules: return code = "'''Salt loaded {0} parent module'''".format(name.split('.')[-1]) # ModuleType can't accept a unicode type on PY2 module = types.ModuleType(str(name)) # future lint: disable=blacklisted-function exec(code, module.__dict__) sys.modules[name] = module def _mod_type(module_path): if module_path.startswith(SALT_BASE_PATH): return 'int' return 'ext' def _inject_into_mod(mod, name, value, force_lock=False): ''' Inject a variable into a module. This is used to inject "globals" like ``__salt__``, ``__pillar``, or ``grains``. Instead of injecting the value directly, a ``ThreadLocalProxy`` is created. If such a proxy is already present under the specified name, it is updated with the new value. This update only affects the current thread, so that the same name can refer to different values depending on the thread of execution. This is important for data that is not truly global. For example, pillar data might be dynamically overriden through function parameters and thus the actual values available in pillar might depend on the thread that is calling a module. mod: module object into which the value is going to be injected. name: name of the variable that is injected into the module. value: value that is injected into the variable. The value is not injected directly, but instead set as the new reference of the proxy that has been created for the variable. force_lock: whether the lock should be acquired before checking whether a proxy object for the specified name has already been injected into the module. If ``False`` (the default), this function checks for the module's variable without acquiring the lock and only acquires the lock if a new proxy has to be created and injected. ''' old_value = getattr(mod, name, None) # We use a double-checked locking scheme in order to avoid taking the lock # when a proxy object has already been injected. # In most programming languages, double-checked locking is considered # unsafe when used without explicit memory barriers because one might read # an uninitialized value. In CPython it is safe due to the global # interpreter lock (GIL). In Python implementations that do not have the # GIL, it could be unsafe, but at least Jython also guarantees that (for # Python objects) memory is not corrupted when writing and reading without # explicit synchronization # (http://www.jython.org/jythonbook/en/1.0/Concurrency.html). # Please note that in order to make this code safe in a runtime environment # that does not make this guarantees, it is not sufficient. The # ThreadLocalProxy must also be created with fallback_to_shared set to # False or a lock must be added to the ThreadLocalProxy. if force_lock: with _inject_into_mod.lock: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: setattr(mod, name, ThreadLocalProxy(value, True)) else: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: _inject_into_mod(mod, name, value, True) # Lock used when injecting globals. This is needed to avoid a race condition # when two threads try to load the same module concurrently. This must be # outside the loader because there might be more than one loader for the same # namespace. _inject_into_mod.lock = threading.RLock() # TODO: move somewhere else? class FilterDictWrapper(MutableMapping): ''' Create a dict which wraps another dict with a specific key suffix on get This is to replace "filter_load" ''' def __init__(self, d, suffix): self._dict = d self.suffix = suffix def __setitem__(self, key, val): self._dict[key] = val def __delitem__(self, key): del self._dict[key] def __getitem__(self, key): return self._dict[key + self.suffix] def __len__(self): return len(self._dict) def __iter__(self): for key in self._dict: if key.endswith(self.suffix): yield key.replace(self.suffix, '') class LazyLoader(salt.utils.lazy.LazyDict): ''' A pseduo-dictionary which has a set of keys which are the name of the module and function, delimited by a dot. When the value of the key is accessed, the function is then loaded from disk and into memory. .. note:: Iterating over keys will cause all modules to be loaded. :param list module_dirs: A list of directories on disk to search for modules :param dict opts: The salt options dictionary. :param str tag: The tag for the type of module to load :param func mod_type_check: A function which can be used to verify files :param dict pack: A dictionary of function to be packed into modules as they are loaded :param list whitelist: A list of modules to whitelist :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules. :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality. If not true, the module will not load. :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values are function references themselves which are loaded on-demand. # TODO: - move modules_max_memory into here - singletons (per tag) ''' mod_dict_class = salt.utils.odict.OrderedDict def __init__(self, module_dirs, opts=None, tag='module', loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, proxy=None, virtual_funcs=None, ): # pylint: disable=W0231 ''' In pack, if any of the values are None they will be replaced with an empty context-specific dict ''' self.inject_globals = {} self.pack = {} if pack is None else pack if opts is None: opts = {} threadsafety = not opts.get('multiprocessing') self.context_dict = salt.utils.context.ContextDict(threadsafe=threadsafety) self.opts = self.__prep_mod_opts(opts) self.module_dirs = module_dirs self.tag = tag self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME self.mod_type_check = mod_type_check or _mod_type if '__context__' not in self.pack: self.pack['__context__'] = None for k, v in six.iteritems(self.pack): if v is None: # if the value of a pack is None, lets make an empty dict value = self.context_dict.get(k, {}) if isinstance(value, ThreadLocalProxy): value = ThreadLocalProxy.unproxy(value) self.context_dict[k] = value self.pack[k] = salt.utils.context.NamespacedDictWrapper(self.context_dict, k) self.whitelist = whitelist self.virtual_enable = virtual_enable self.initial_load = True # names of modules that we don't have (errors, __virtual__, etc.) self.missing_modules = {} # mapping of name -> error self.loaded_modules = {} # mapping of module_name -> dict_of_functions self.loaded_files = set() # TODO: just remove them from file_mapping? self.static_modules = static_modules if static_modules else [] if virtual_funcs is None: virtual_funcs = [] self.virtual_funcs = virtual_funcs self.disabled = set( self.opts.get( 'disable_{0}{1}'.format( self.tag, '' if self.tag[-1] == 's' else 's' ), [] ) ) # A map of suffix to description for imp self.suffix_map = {} # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [''] for (suffix, mode, kind) in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) self._lock = threading.RLock() self._refresh_file_mapping() super(LazyLoader, self).__init__() # late init the lazy loader # create all of the import namespaces _generate_module('{0}.int'.format(self.loaded_base_name)) _generate_module('{0}.int.{1}'.format(self.loaded_base_name, tag)) _generate_module('{0}.ext'.format(self.loaded_base_name)) _generate_module('{0}.ext.{1}'.format(self.loaded_base_name, tag)) def __getitem__(self, item): ''' Override the __getitem__ in order to decorate the returned function if we need to last-minute inject globals ''' func = super(LazyLoader, self).__getitem__(item) if self.inject_globals: return global_injector_decorator(self.inject_globals)(func) else: return func def __getattr__(self, mod_name): ''' Allow for "direct" attribute access-- this allows jinja templates to access things like `salt.test.ping()` ''' if mod_name in ('__getstate__', '__setstate__'): return object.__getattribute__(self, mod_name) # if we have an attribute named that, lets return it. try: return object.__getattr__(self, mod_name) # pylint: disable=no-member except AttributeError: pass # otherwise we assume its jinja template access if mod_name not in self.loaded_modules and not self.loaded: for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and mod_name in self.loaded_modules: break if mod_name in self.loaded_modules: return self.loaded_modules[mod_name] else: raise AttributeError(mod_name) def missing_fun_string(self, function_name): ''' Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ''' mod_name = function_name.split('.')[0] if mod_name in self.loaded_modules: return '\'{0}\' is not available.'.format(function_name) else: try: reason = self.missing_modules[mod_name] except KeyError: return '\'{0}\' is not available.'.format(function_name) else: if reason is not None: return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason) else: return '\'{0}\' __virtual__ returned False'.format(mod_name) def _refresh_file_mapping(self): ''' refresh the mapping of the FS on disk ''' # map of suffix to description for imp if self.opts.get('cython_enable', True) is True: try: global pyximport pyximport = __import__('pyximport') # pylint: disable=import-error pyximport.install() # add to suffix_map so file_mapping will pick it up self.suffix_map['.pyx'] = tuple() except ImportError: log.info('Cython is enabled in the options but not present ' 'in the system path. Skipping Cython modules.') # Allow for zipimport of modules if self.opts.get('enable_zip_modules', True) is True: self.suffix_map['.zip'] = tuple() # allow for module dirs if USE_IMPORTLIB: self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY) else: self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY) # create mapping of filename (without suffix) to (path, suffix) # The files are added in order of priority, so order *must* be retained. self.file_mapping = salt.utils.odict.OrderedDict() opt_match = [] def _replace_pre_ext(obj): ''' Hack so we can get the optimization level that we replaced (if any) out of the re.sub call below. We use a list here because it is a persistent data structure that we will be able to access after re.sub is called. ''' opt_match.append(obj) return '' for mod_dir in self.module_dirs: try: # Make sure we have a sorted listdir in order to have # expectable override results files = sorted( x for x in os.listdir(mod_dir) if x != '__pycache__' ) except OSError: continue # Next mod_dir if six.PY3: try: pycache_files = [ os.path.join('__pycache__', x) for x in sorted(os.listdir(os.path.join(mod_dir, '__pycache__'))) ] except OSError: pass else: files.extend(pycache_files) for filename in files: try: dirname, basename = os.path.split(filename) if basename.startswith('_'): # skip private modules # log messages omitted for obviousness continue # Next filename f_noext, ext = os.path.splitext(basename) if six.PY3: f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext) try: opt_level = int( opt_match.pop().group(1).rsplit('-', 1)[-1] ) except (AttributeError, IndexError, ValueError): # No regex match or no optimization level matched opt_level = 0 try: opt_index = self.opts['optimization_order'].index(opt_level) except KeyError: log.trace( 'Disallowed optimization level %d for module ' 'name \'%s\', skipping. Add %d to the ' '\'optimization_order\' config option if you ' 'do not want to ignore this optimization ' 'level.', opt_level, f_noext, opt_level ) continue else: # Optimization level not reflected in filename on PY2 opt_index = 0 # make sure it is a suffix we support if ext not in self.suffix_map: continue # Next filename if f_noext in self.disabled: log.trace( 'Skipping %s, it is disabled by configuration', filename ) continue # Next filename fpath = os.path.join(mod_dir, filename) # if its a directory, lets allow us to load that if ext == '': # is there something __init__? subfiles = os.listdir(fpath) for suffix in self.suffix_order: if '' == suffix: continue # Next suffix (__init__ must have a suffix) init_file = '__init__{0}'.format(suffix) if init_file in subfiles: break else: continue # Next filename try: curr_ext = self.file_mapping[f_noext][1] curr_opt_index = self.file_mapping[f_noext][2] except KeyError: pass else: if '' in (curr_ext, ext) and curr_ext != ext: log.error( 'Module/package collision: \'%s\' and \'%s\'', fpath, self.file_mapping[f_noext][0] ) if six.PY3 and ext == '.pyc' and curr_ext == '.pyc': # Check the optimization level if opt_index >= curr_opt_index: # Module name match, but a higher-priority # optimization level was already matched, skipping. continue elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext): # Match found but a higher-priorty match already # exists, so skip this. continue if six.PY3 and not dirname and ext == '.pyc': # On Python 3, we should only load .pyc files from the # __pycache__ subdirectory (i.e. when dirname is not an # empty string). continue # Made it this far - add it self.file_mapping[f_noext] = (fpath, ext, opt_index) except OSError: continue for smod in self.static_modules: f_noext = smod.split('.')[-1] self.file_mapping[f_noext] = (smod, '.o', 0) def clear(self): ''' Clear the dict ''' with self._lock: super(LazyLoader, self).clear() # clear the lazy loader self.loaded_files = set() self.missing_modules = {} self.loaded_modules = {} # if we have been loaded before, lets clear the file mapping since # we obviously want a re-do if hasattr(self, 'opts'): self._refresh_file_mapping() self.initial_load = False def __prep_mod_opts(self, opts): ''' Strip out of the opts any logger instance ''' if '__grains__' not in self.pack: grains = opts.get('grains', {}) if isinstance(grains, ThreadLocalProxy): grains = ThreadLocalProxy.unproxy(grains) self.context_dict['grains'] = grains self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains') if '__pillar__' not in self.pack: pillar = opts.get('pillar', {}) if isinstance(pillar, ThreadLocalProxy): pillar = ThreadLocalProxy.unproxy(pillar) self.context_dict['pillar'] = pillar self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar') mod_opts = {} for key, val in list(opts.items()): if key == 'logger': continue mod_opts[key] = val return mod_opts def _iter_files(self, mod_name): ''' Iterate over all file_mapping files in order of closeness to mod_name ''' # do we have an exact match? if mod_name in self.file_mapping: yield mod_name # do we have a partial match? for k in self.file_mapping: if mod_name in k: yield k # anyone else? Bueller? for k in self.file_mapping: if mod_name not in k: yield k def _reload_submodules(self, mod): submodules = ( getattr(mod, sname) for sname in dir(mod) if isinstance(getattr(mod, sname), mod.__class__) ) # reload only custom "sub"modules for submodule in submodules: # it is a submodule if the name is in a namespace under mod if submodule.__name__.startswith(mod.__name__ + '.'): reload_module(submodule) self._reload_submodules(submodule) def _load_module(self, name): mod = None fpath, suffix = self.file_mapping[name][:2] self.loaded_files.add(name) fpath_dirname = os.path.dirname(fpath) try: sys.path.append(fpath_dirname) if suffix == '.pyx': mod = pyximport.load_module(name, fpath, tempfile.gettempdir()) elif suffix == '.o': top_mod = __import__(fpath, globals(), locals(), []) comps = fpath.split('.') if len(comps) < 2: mod = top_mod else: mod = top_mod for subname in comps[1:]: mod = getattr(mod, subname) elif suffix == '.zip': mod = zipimporter(fpath).load_module(name) else: desc = self.suffix_map[suffix] # if it is a directory, we don't open a file try: mod_namespace = '.'.join(( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name)) except TypeError: mod_namespace = '{0}.{1}.{2}.{3}'.format( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name) if suffix == '': if USE_IMPORTLIB: # pylint: disable=no-member # Package directory, look for __init__ loader_details = [ (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES), (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES), (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), ] file_finder = importlib.machinery.FileFinder( fpath_dirname, *loader_details ) spec = file_finder.find_spec(mod_namespace) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: mod = imp.load_module(mod_namespace, None, fpath, desc) # reload all submodules if necessary if not self.initial_load: self._reload_submodules(mod) else: if USE_IMPORTLIB: # pylint: disable=no-member loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath) spec = importlib.util.spec_from_file_location( mod_namespace, fpath, loader=loader ) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() #mod = importlib.util.module_from_spec(spec) #spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: with salt.utils.files.fopen(fpath, desc[1]) as fn_: mod = imp.load_module(mod_namespace, fn_, fpath, desc) except IOError: raise except ImportError as exc: if 'magic number' in six.text_type(exc): error_msg = 'Failed to import {0} {1}. Bad magic number. If migrating from Python2 to Python3, remove all .pyc files and try again.'.format(self.tag, name) log.warning(error_msg) self.missing_modules[name] = error_msg log.debug( 'Failed to import %s %s:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = exc return False except Exception as error: log.error( 'Failed to import %s %s, this is due most likely to a ' 'syntax error:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False except SystemExit as error: try: fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1] except Exception: pass else: tgt_fn = os.path.join('salt', 'utils', 'process.py') if fn_.endswith(tgt_fn) and '_handle_signals' in caller: # Race conditon, SIGTERM or SIGINT received while loader # was in process of loading a module. Call sys.exit to # ensure that the process is killed. sys.exit(salt.defaults.exitcodes.EX_OK) log.error( 'Failed to import %s %s as the module called exit()\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False finally: sys.path.remove(fpath_dirname) if hasattr(mod, '__opts__'): mod.__opts__.update(self.opts) else: mod.__opts__ = self.opts # pack whatever other globals we were asked to for p_name, p_value in six.iteritems(self.pack): _inject_into_mod(mod, p_name, p_value) module_name = mod.__name__.rsplit('.', 1)[-1] # Call a module's initialization method if it exists module_init = getattr(mod, '__init__', None) if inspect.isfunction(module_init): try: module_init(self.opts) except TypeError as e: log.error(e) except Exception: err_string = '__init__ failed' log.debug( 'Error loading %s.%s: %s', self.tag, module_name, err_string, exc_info=True ) self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False # if virtual modules are enabled, we need to look for the # __virtual__() function inside that module and run it. if self.virtual_enable: virtual_funcs_to_process = ['__virtual__'] + self.virtual_funcs for virtual_func in virtual_funcs_to_process: virtual_ret, module_name, virtual_err, virtual_aliases = \ self._process_virtual(mod, module_name, virtual_func) if virtual_err is not None: log.trace( 'Error loading %s.%s: %s', self.tag, module_name, virtual_err ) # if _process_virtual returned a non-True value then we are # supposed to not process this module if virtual_ret is not True and module_name not in self.missing_modules: # If a module has information about why it could not be loaded, record it self.missing_modules[module_name] = virtual_err self.missing_modules[name] = virtual_err return False else: virtual_aliases = () # If this is a proxy minion then MOST modules cannot work. Therefore, require that # any module that does work with salt-proxy-minion define __proxyenabled__ as a list # containing the names of the proxy types that the module supports. # # Render modules and state modules are OK though if 'proxy' in self.opts: if self.tag in ['grains', 'proxy']: if not hasattr(mod, '__proxyenabled__') or \ (self.opts['proxy']['proxytype'] not in mod.__proxyenabled__ and '*' not in mod.__proxyenabled__): err_string = 'not a proxy_minion enabled module' self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False if getattr(mod, '__load__', False) is not False: log.info( 'The functions from module \'%s\' are being loaded from the ' 'provided __load__ attribute', module_name ) # If we had another module by the same virtual name, we should put any # new functions under the existing dictionary. mod_names = [module_name] + list(virtual_aliases) mod_dict = dict(( (x, self.loaded_modules.get(x, self.mod_dict_class())) for x in mod_names )) for attr in getattr(mod, '__load__', dir(mod)): if attr.startswith('_') and attr != '__call__': # private functions are skipped, # except __call__ which is default entrance # for multi-function batch-like state syntax continue func = getattr(mod, attr) if not inspect.isfunction(func) and not isinstance(func, functools.partial): # Not a function!? Skip it!!! continue # Let's get the function name. # If the module has the __func_alias__ attribute, it must be a # dictionary mapping in the form of(key -> value): # <real-func-name> -> <desired-func-name> # # It default's of course to the found callable attribute name # if no alias is defined. funcname = getattr(mod, '__func_alias__', {}).get(attr, attr) for tgt_mod in mod_names: try: full_funcname = '.'.join((tgt_mod, funcname)) except TypeError: full_funcname = '{0}.{1}'.format(tgt_mod, funcname) # Save many references for lookups # Careful not to overwrite existing (higher priority) functions if full_funcname not in self._dict: self._dict[full_funcname] = func if funcname not in mod_dict[tgt_mod]: setattr(mod_dict[tgt_mod], funcname, func) mod_dict[tgt_mod][funcname] = func self._apply_outputter(func, mod) # enforce depends try: Depends.enforce_dependencies(self._dict, self.tag) except RuntimeError as exc: log.info( 'Depends.enforce_dependencies() failed for the following ' 'reason: %s', exc ) for tgt_mod in mod_names: self.loaded_modules[tgt_mod] = mod_dict[tgt_mod] return True def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise KeyError('The key \'{0}\' should contain a \'.\''.format(key)) mod_name, _ = key.split('.', 1) with self._lock: # It is possible that the key is in the dictionary after # acquiring the lock due to another thread loading it. if mod_name in self.missing_modules or key in self._dict: return True # if the modulename isn't in the whitelist, don't bother if self.whitelist and mod_name not in self.whitelist: log.error( 'Failed to load function %s because its module (%s) is ' 'not in the whitelist: %s', key, mod_name, self.whitelist ) raise KeyError(key) def _inner_load(mod_name): for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and key in self._dict: return True return False # try to load the module ret = None reloaded = False # re-scan up to once, IOErrors or a failed load cause re-scans of the # filesystem while True: try: ret = _inner_load(mod_name) if not reloaded and ret is not True: self._refresh_file_mapping() reloaded = True continue break except IOError: if not reloaded: self._refresh_file_mapping() reloaded = True continue return ret def _load_all(self): ''' Load all of them ''' with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True def reload_modules(self): with self._lock: self.loaded_files = set() self._load_all() def _apply_outputter(self, func, mod): ''' Apply the __outputter__ variable to the functions ''' if hasattr(mod, '__outputter__'): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__] def _process_virtual(self, mod, module_name, virtual_func='__virtual__'): ''' Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1] ''' # The __virtual__ function will return either a True or False value. # If it returns a True value it can also set a module level attribute # named __virtualname__ with the name that the module should be # referred to as. # # This allows us to have things like the pkg module working on all # platforms under the name 'pkg'. It also allows for modules like # augeas_cfg to be referred to as 'augeas', which would otherwise have # namespace collisions. And finally it allows modules to return False # if they are not intended to run on the given platform or are missing # dependencies. virtual_aliases = getattr(mod, '__virtual_aliases__', tuple()) try: error_reason = None if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__): try: start = time.time() virtual = getattr(mod, virtual_func)() if isinstance(virtual, tuple): error_reason = virtual[1] virtual = virtual[0] if self.opts.get('virtual_timer', False): end = time.time() - start msg = 'Virtual function took {0} seconds for {1}'.format( end, module_name) log.warning(msg) except Exception as exc: error_reason = ( 'Exception raised when processing __virtual__ function' ' for {0}. Module will not be loaded: {1}'.format( mod.__name__, exc)) log.error(error_reason, exc_info_on_loglevel=logging.DEBUG) virtual = None # Get the module's virtual name virtualname = getattr(mod, '__virtualname__', virtual) if not virtual: # if __virtual__() evaluates to False then the module # wasn't meant for this platform or it's not supposed to # load for some other reason. # Some modules might accidentally return None and are # improperly loaded if virtual is None: log.warning( '%s.__virtual__() is wrongly returning `None`. ' 'It should either return `True`, `False` or a new ' 'name. If you\'re the developer of the module ' '\'%s\', please fix this.', mod.__name__, module_name ) return (False, module_name, error_reason, virtual_aliases) # At this point, __virtual__ did not return a # boolean value, let's check for deprecated usage # or module renames if virtual is not True and module_name != virtual: # The module is renaming itself. Updating the module name # with the new name log.trace('Loaded %s as virtual %s', module_name, virtual) if virtualname != virtual: # The __virtualname__ attribute does not match what's # being returned by the __virtual__() function. This # should be considered an error. log.error( 'The module \'%s\' is showing some bad usage. Its ' '__virtualname__ attribute is set to \'%s\' yet the ' '__virtual__() function is returning \'%s\'. These ' 'values should match!', mod.__name__, virtualname, virtual ) module_name = virtualname # If the __virtual__ function returns True and __virtualname__ # is set then use it elif virtual is True and virtualname != module_name: if virtualname is not True: module_name = virtualname except KeyError: # Key errors come out of the virtual function when passing # in incomplete grains sets, these can be safely ignored # and logged to debug, still, it includes the traceback to # help debugging. log.debug('KeyError when loading %s', module_name, exc_info=True) except Exception: # If the module throws an exception during __virtual__() # then log the information and continue to the next. log.error( 'Failed to read the virtual function for %s: %s', self.tag, module_name, exc_info=True ) return (False, module_name, error_reason, virtual_aliases) return (True, module_name, None, virtual_aliases) def global_injector_decorator(inject_globals): ''' Decorator used by the LazyLoader to inject globals into a function at execute time. globals Dictionary with global variables to inject ''' def inner_decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): with salt.utils.context.func_globals_inject(f, **inject_globals): return f(*args, **kwargs) return wrapper return inner_decorator
saltstack/salt
salt/loader.py
sdb
python
def sdb(opts, functions=None, whitelist=None, utils=None): ''' Make a very small database call ''' if utils is None: utils = {} return LazyLoader( _module_dirs(opts, 'sdb'), opts, tag='sdb', pack={ '__sdb__': functions, '__opts__': opts, '__utils__': utils, '__salt__': minion_mods(opts, utils), }, whitelist=whitelist, )
Make a very small database call
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L960-L978
null
# -*- coding: utf-8 -*- ''' The Salt loader is the core to Salt's plugin system, the loader scans directories for python loadable code and organizes the code into the plugin interfaces used by Salt. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import sys import time import logging import inspect import tempfile import threading import functools import threading import traceback import types from zipimport import zipimporter # Import salt libs import salt.config import salt.defaults.events import salt.defaults.exitcodes import salt.syspaths import salt.utils.args import salt.utils.context import salt.utils.data import salt.utils.dictupdate import salt.utils.event import salt.utils.files import salt.utils.lazy import salt.utils.odict import salt.utils.platform import salt.utils.versions import salt.utils.stringutils from salt.exceptions import LoaderError from salt.template import check_render_pipe_str from salt.utils.decorators import Depends from salt.utils.thread_local_proxy import ThreadLocalProxy # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import reload_module if sys.version_info[:2] >= (3, 5): import importlib.machinery # pylint: disable=no-name-in-module,import-error import importlib.util # pylint: disable=no-name-in-module,import-error USE_IMPORTLIB = True else: import imp USE_IMPORTLIB = False try: from collections.abc import MutableMapping except ImportError: from collections import MutableMapping try: import pkg_resources HAS_PKG_RESOURCES = True except ImportError: HAS_PKG_RESOURCES = False log = logging.getLogger(__name__) SALT_BASE_PATH = os.path.abspath(salt.syspaths.INSTALL_DIR) LOADED_BASE_NAME = 'salt.loaded' if USE_IMPORTLIB: # pylint: disable=no-member MODULE_KIND_SOURCE = 1 MODULE_KIND_COMPILED = 2 MODULE_KIND_EXTENSION = 3 MODULE_KIND_PKG_DIRECTORY = 5 SUFFIXES = [] for suffix in importlib.machinery.EXTENSION_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_EXTENSION)) for suffix in importlib.machinery.SOURCE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_SOURCE)) for suffix in importlib.machinery.BYTECODE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_COMPILED)) MODULE_KIND_MAP = { MODULE_KIND_SOURCE: importlib.machinery.SourceFileLoader, MODULE_KIND_COMPILED: importlib.machinery.SourcelessFileLoader, MODULE_KIND_EXTENSION: importlib.machinery.ExtensionFileLoader } # pylint: enable=no-member else: SUFFIXES = imp.get_suffixes() PY3_PRE_EXT = \ re.compile(r'\.cpython-{0}{1}(\.opt-[1-9])?'.format(*sys.version_info[:2])) # Because on the cloud drivers we do `from salt.cloud.libcloudfuncs import *` # which simplifies code readability, it adds some unsupported functions into # the driver's module scope. # We list un-supported functions here. These will be removed from the loaded. # TODO: remove the need for this cross-module code. Maybe use NotImplemented LIBCLOUD_FUNCS_NOT_SUPPORTED = ( 'parallels.avail_sizes', 'parallels.avail_locations', 'proxmox.avail_sizes', ) # Will be set to pyximport module at runtime if cython is enabled in config. pyximport = None def static_loader( opts, ext_type, tag, pack=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, filter_name=None, ): funcs = LazyLoader( _module_dirs( opts, ext_type, tag, int_type, ext_dirs, ext_type_dirs, base_path, ), opts, tag=tag, pack=pack, ) ret = {} funcs._load_all() if filter_name: funcs = FilterDictWrapper(funcs, filter_name) for key in funcs: ret[key] = funcs[key] return ret def _format_entrypoint_target(ep): ''' Makes a string describing the target of an EntryPoint object. Base strongly on EntryPoint.__str__(). ''' s = ep.module_name if ep.attrs: s += ':' + '.'.join(ep.attrs) return s def _module_dirs( opts, ext_type, tag=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, ): if tag is None: tag = ext_type sys_types = os.path.join(base_path or SALT_BASE_PATH, int_type or ext_type) ext_types = os.path.join(opts['extension_modules'], ext_type) ext_type_types = [] if ext_dirs: if ext_type_dirs is None: ext_type_dirs = '{0}_dirs'.format(tag) if ext_type_dirs in opts: ext_type_types.extend(opts[ext_type_dirs]) if HAS_PKG_RESOURCES and ext_type_dirs: for entry_point in pkg_resources.iter_entry_points('salt.loader', ext_type_dirs): try: loaded_entry_point = entry_point.load() for path in loaded_entry_point(): ext_type_types.append(path) except Exception as exc: log.error("Error getting module directories from %s: %s", _format_entrypoint_target(entry_point), exc) log.debug("Full backtrace for module directories error", exc_info=True) cli_module_dirs = [] # The dirs can be any module dir, or a in-tree _{ext_type} dir for _dir in opts.get('module_dirs', []): # Prepend to the list to match cli argument ordering maybe_dir = os.path.join(_dir, ext_type) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) continue maybe_dir = os.path.join(_dir, '_{0}'.format(ext_type)) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) return cli_module_dirs + ext_type_types + [ext_types, sys_types] def minion_mods( opts, context=None, utils=None, whitelist=None, initial_load=False, loaded_base_name=None, notify=False, static_modules=None, proxy=None): ''' Load execution modules Returns a dictionary of execution modules appropriate for the current system by evaluating the __virtual__() function in each module. :param dict opts: The Salt options dictionary :param dict context: A Salt context that should be made present inside generated modules in __context__ :param dict utils: Utility functions which should be made available to Salt modules in __utils__. See `utils_dirs` in salt.config for additional information about configuration. :param list whitelist: A list of modules which should be whitelisted. :param bool initial_load: Deprecated flag! Unused. :param str loaded_base_name: A string marker for the loaded base name. :param bool notify: Flag indicating that an event should be fired upon completion of module loading. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) __opts__['grains'] = __grains__ __utils__ = salt.loader.utils(__opts__) __salt__ = salt.loader.minion_mods(__opts__, utils=__utils__) __salt__['test.ping']() ''' # TODO Publish documentation for module whitelisting if not whitelist: whitelist = opts.get('whitelist_modules', None) ret = LazyLoader( _module_dirs(opts, 'modules', 'module'), opts, tag='module', pack={'__context__': context, '__utils__': utils, '__proxy__': proxy}, whitelist=whitelist, loaded_base_name=loaded_base_name, static_modules=static_modules, ) ret.pack['__salt__'] = ret # Load any provider overrides from the configuration file providers option # Note: Providers can be pkg, service, user or group - not to be confused # with cloud providers. providers = opts.get('providers', False) if providers and isinstance(providers, dict): for mod in providers: # sometimes providers opts is not to diverge modules but # for other configuration try: funcs = raw_mod(opts, providers[mod], ret) except TypeError: break else: if funcs: for func in funcs: f_key = '{0}{1}'.format(mod, func[func.rindex('.'):]) ret[f_key] = funcs[func] if notify: evt = salt.utils.event.get_event('minion', opts=opts, listen=False) evt.fire_event({'complete': True}, tag=salt.defaults.events.MINION_MOD_COMPLETE) return ret def raw_mod(opts, name, functions, mod='modules'): ''' Returns a single module loaded raw and bypassing the __virtual__ function .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') testmod = salt.loader.raw_mod(__opts__, 'test', None) testmod['test.ping']() ''' loader = LazyLoader( _module_dirs(opts, mod, 'module'), opts, tag='rawmodule', virtual_enable=False, pack={'__salt__': functions}, ) # if we don't have the module, return an empty dict if name not in loader.file_mapping: return {} loader._load_module(name) # load a single module (the one passed in) return dict(loader._dict) # return a copy of *just* the funcs for `name` def metaproxy(opts): ''' Return functions used in the meta proxy ''' return LazyLoader( _module_dirs(opts, 'metaproxy'), opts, tag='metaproxy' ) def matchers(opts): ''' Return the matcher services plugins ''' return LazyLoader( _module_dirs(opts, 'matchers'), opts, tag='matchers' ) def engines(opts, functions, runners, utils, proxy=None): ''' Return the master services plugins ''' pack = {'__salt__': functions, '__runners__': runners, '__proxy__': proxy, '__utils__': utils} return LazyLoader( _module_dirs(opts, 'engines'), opts, tag='engines', pack=pack, ) def proxy(opts, functions=None, returners=None, whitelist=None, utils=None): ''' Returns the proxy module for this salt-proxy-minion ''' ret = LazyLoader( _module_dirs(opts, 'proxy'), opts, tag='proxy', pack={'__salt__': functions, '__ret__': returners, '__utils__': utils}, ) ret.pack['__proxy__'] = ret return ret def returners(opts, functions, whitelist=None, context=None, proxy=None): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'returners', 'returner'), opts, tag='returner', whitelist=whitelist, pack={'__salt__': functions, '__context__': context, '__proxy__': proxy or {}}, ) def utils(opts, whitelist=None, context=None, proxy=proxy): ''' Returns the utility modules ''' return LazyLoader( _module_dirs(opts, 'utils', ext_type_dirs='utils_dirs'), opts, tag='utils', whitelist=whitelist, pack={'__context__': context, '__proxy__': proxy or {}}, ) def pillars(opts, functions, context=None): ''' Returns the pillars modules ''' ret = LazyLoader(_module_dirs(opts, 'pillar'), opts, tag='pillar', pack={'__salt__': functions, '__context__': context, '__utils__': utils(opts)}) ret.pack['__ext_pillar__'] = ret return FilterDictWrapper(ret, '.ext_pillar') def tops(opts): ''' Returns the tops modules ''' if 'master_tops' not in opts: return {} whitelist = list(opts['master_tops'].keys()) ret = LazyLoader( _module_dirs(opts, 'tops', 'top'), opts, tag='top', whitelist=whitelist, ) return FilterDictWrapper(ret, '.top') def wheels(opts, whitelist=None, context=None): ''' Returns the wheels modules ''' if context is None: context = {} return LazyLoader( _module_dirs(opts, 'wheel'), opts, tag='wheel', whitelist=whitelist, pack={'__context__': context}, ) def outputters(opts): ''' Returns the outputters modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only outputters present in the keyspace ''' ret = LazyLoader( _module_dirs(opts, 'output', ext_type_dirs='outputter_dirs'), opts, tag='output', ) wrapped_ret = FilterDictWrapper(ret, '.output') # TODO: this name seems terrible... __salt__ should always be execution mods ret.pack['__salt__'] = wrapped_ret return wrapped_ret def serializers(opts): ''' Returns the serializers modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only serializers present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'serializers'), opts, tag='serializers', ) def eauth_tokens(opts): ''' Returns the tokens modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only token backends present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'tokens'), opts, tag='tokens', ) def auth(opts, whitelist=None): ''' Returns the auth modules :param dict opts: The Salt options dictionary :returns: LazyLoader ''' return LazyLoader( _module_dirs(opts, 'auth'), opts, tag='auth', whitelist=whitelist, pack={'__salt__': minion_mods(opts)}, ) def fileserver(opts, backends): ''' Returns the file server modules ''' return LazyLoader(_module_dirs(opts, 'fileserver'), opts, tag='fileserver', whitelist=backends, pack={'__utils__': utils(opts)}) def roster(opts, runner=None, utils=None, whitelist=None): ''' Returns the roster modules ''' return LazyLoader( _module_dirs(opts, 'roster'), opts, tag='roster', whitelist=whitelist, pack={ '__runner__': runner, '__utils__': utils, }, ) def thorium(opts, functions, runners): ''' Load the thorium runtime modules ''' pack = {'__salt__': functions, '__runner__': runners, '__context__': {}} ret = LazyLoader(_module_dirs(opts, 'thorium'), opts, tag='thorium', pack=pack) ret.pack['__thorium__'] = ret return ret def states(opts, functions, utils, serializers, whitelist=None, proxy=None, context=None): ''' Returns the state modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') statemods = salt.loader.states(__opts__, None, None) ''' if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'states'), opts, tag='states', pack={'__salt__': functions, '__proxy__': proxy or {}}, whitelist=whitelist, ) ret.pack['__states__'] = ret ret.pack['__utils__'] = utils ret.pack['__serializers__'] = serializers ret.pack['__context__'] = context return ret def beacons(opts, functions, context=None, proxy=None): ''' Load the beacon modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. ''' return LazyLoader( _module_dirs(opts, 'beacons'), opts, tag='beacons', pack={'__context__': context, '__salt__': functions, '__proxy__': proxy or {}}, virtual_funcs=[], ) def log_handlers(opts): ''' Returns the custom logging handler modules :param dict opts: The Salt options dictionary ''' ret = LazyLoader( _module_dirs( opts, 'log_handlers', int_type='handlers', base_path=os.path.join(SALT_BASE_PATH, 'log'), ), opts, tag='log_handlers', ) return FilterDictWrapper(ret, '.setup_handlers') def ssh_wrapper(opts, functions=None, context=None): ''' Returns the custom logging handler modules ''' return LazyLoader( _module_dirs( opts, 'wrapper', base_path=os.path.join(SALT_BASE_PATH, os.path.join('client', 'ssh')), ), opts, tag='wrapper', pack={ '__salt__': functions, '__grains__': opts.get('grains', {}), '__pillar__': opts.get('pillar', {}), '__context__': context, }, ) def render(opts, functions, states=None, proxy=None, context=None): ''' Returns the render modules ''' if context is None: context = {} pack = {'__salt__': functions, '__grains__': opts.get('grains', {}), '__context__': context} if states: pack['__states__'] = states pack['__proxy__'] = proxy or {} ret = LazyLoader( _module_dirs( opts, 'renderers', 'render', ext_type_dirs='render_dirs', ), opts, tag='render', pack=pack, ) rend = FilterDictWrapper(ret, '.render') if not check_render_pipe_str(opts['renderer'], rend, opts['renderer_blacklist'], opts['renderer_whitelist']): err = ('The renderer {0} is unavailable, this error is often because ' 'the needed software is unavailable'.format(opts['renderer'])) log.critical(err) raise LoaderError(err) return rend def grain_funcs(opts, proxy=None): ''' Returns the grain functions .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') grainfuncs = salt.loader.grain_funcs(__opts__) ''' ret = LazyLoader( _module_dirs( opts, 'grains', 'grain', ext_type_dirs='grains_dirs', ), opts, tag='grains', ) ret.pack['__utils__'] = utils(opts, proxy=proxy) return ret def _load_cached_grains(opts, cfn): ''' Returns the grains cached in cfn, or None if the cache is too old or is corrupted. ''' if not os.path.isfile(cfn): log.debug('Grains cache file does not exist.') return None grains_cache_age = int(time.time() - os.path.getmtime(cfn)) if grains_cache_age > opts.get('grains_cache_expiration', 300): log.debug( 'Grains cache last modified %s seconds ago and cache ' 'expiration is set to %s. Grains cache expired. ' 'Refreshing.', grains_cache_age, opts.get('grains_cache_expiration', 300) ) return None if opts.get('refresh_grains_cache', False): log.debug('refresh_grains_cache requested, Refreshing.') return None log.debug('Retrieving grains from cache') try: serial = salt.payload.Serial(opts) with salt.utils.files.fopen(cfn, 'rb') as fp_: cached_grains = salt.utils.data.decode(serial.load(fp_), preserve_tuples=True) if not cached_grains: log.debug('Cached grains are empty, cache might be corrupted. Refreshing.') return None return cached_grains except (IOError, OSError): return None def grains(opts, force_refresh=False, proxy=None): ''' Return the functions for the dynamic grains and the values for the static grains. Since grains are computed early in the startup process, grains functions do not have __salt__ or __proxy__ available. At proxy-minion startup, this function is called with the proxymodule LazyLoader object so grains functions can communicate with their controlled device. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) print __grains__['id'] ''' # Need to re-import salt.config, somehow it got lost when a minion is starting import salt.config # if we have no grains, lets try loading from disk (TODO: move to decorator?) cfn = os.path.join( opts['cachedir'], 'grains.cache.p' ) if not force_refresh and opts.get('grains_cache', False): cached_grains = _load_cached_grains(opts, cfn) if cached_grains: return cached_grains else: log.debug('Grains refresh requested. Refreshing grains.') if opts.get('skip_grains', False): return {} grains_deep_merge = opts.get('grains_deep_merge', False) is True if 'conf_file' in opts: pre_opts = {} pre_opts.update(salt.config.load_config( opts['conf_file'], 'SALT_MINION_CONFIG', salt.config.DEFAULT_MINION_OPTS['conf_file'] )) default_include = pre_opts.get( 'default_include', opts['default_include'] ) include = pre_opts.get('include', []) pre_opts.update(salt.config.include_config( default_include, opts['conf_file'], verbose=False )) pre_opts.update(salt.config.include_config( include, opts['conf_file'], verbose=True )) if 'grains' in pre_opts: opts['grains'] = pre_opts['grains'] else: opts['grains'] = {} else: opts['grains'] = {} grains_data = {} blist = opts.get('grains_blacklist', []) funcs = grain_funcs(opts, proxy=proxy) if force_refresh: # if we refresh, lets reload grain modules funcs.clear() # Run core grains for key in funcs: if not key.startswith('core.'): continue log.trace('Loading %s grain', key) ret = funcs[key]() if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) # Run the rest of the grains for key in funcs: if key.startswith('core.') or key == '_errors': continue try: # Grains are loaded too early to take advantage of the injected # __proxy__ variable. Pass an instance of that LazyLoader # here instead to grains functions if the grains functions take # one parameter. Then the grains can have access to the # proxymodule for retrieving information from the connected # device. log.trace('Loading %s grain', key) parameters = salt.utils.args.get_function_argspec(funcs[key]).args kwargs = {} if 'proxy' in parameters: kwargs['proxy'] = proxy if 'grains' in parameters: kwargs['grains'] = grains_data ret = funcs[key](**kwargs) except Exception: if salt.utils.platform.is_proxy(): log.info('The following CRITICAL message may not be an error; the proxy may not be completely established yet.') log.critical( 'Failed to load grains defined in grain file %s in ' 'function %s, error:\n', key, funcs[key], exc_info=True ) continue if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) if opts.get('proxy_merge_grains_in_module', True) and proxy: try: proxytype = proxy.opts['proxy']['proxytype'] if proxytype + '.grains' in proxy: if proxytype + '.initialized' in proxy and proxy[proxytype + '.initialized'](): try: proxytype = proxy.opts['proxy']['proxytype'] ret = proxy[proxytype + '.grains']() if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) except Exception: log.critical('Failed to run proxy\'s grains function!', exc_info=True ) except KeyError: pass grains_data.update(opts['grains']) # Write cache if enabled if opts.get('grains_cache', False): with salt.utils.files.set_umask(0o077): try: if salt.utils.platform.is_windows(): # Late import import salt.modules.cmdmod # Make sure cache file isn't read-only salt.modules.cmdmod._run_quiet('attrib -R "{0}"'.format(cfn)) with salt.utils.files.fopen(cfn, 'w+b') as fp_: try: serial = salt.payload.Serial(opts) serial.dump(grains_data, fp_) except TypeError as e: log.error('Failed to serialize grains cache: %s', e) raise # re-throw for cleanup except Exception as e: log.error('Unable to write to grains cache file %s: %s', cfn, e) # Based on the original exception, the file may or may not have been # created. If it was, we will remove it now, as the exception means # the serialized data is not to be trusted, no matter what the # exception is. if os.path.isfile(cfn): os.unlink(cfn) if grains_deep_merge: salt.utils.dictupdate.update(grains_data, opts['grains']) else: grains_data.update(opts['grains']) return salt.utils.data.decode(grains_data, preserve_tuples=True) # TODO: get rid of? Does anyone use this? You should use raw() instead def call(fun, **kwargs): ''' Directly call a function inside a loader directory ''' args = kwargs.get('args', []) dirs = kwargs.get('dirs', []) funcs = LazyLoader( [os.path.join(SALT_BASE_PATH, 'modules')] + dirs, None, tag='modules', virtual_enable=False, ) return funcs[fun](*args) def runner(opts, utils=None, context=None, whitelist=None): ''' Directly call a function inside a loader directory ''' if utils is None: utils = {} if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'runners', 'runner', ext_type_dirs='runner_dirs'), opts, tag='runners', pack={'__utils__': utils, '__context__': context}, whitelist=whitelist, ) # TODO: change from __salt__ to something else, we overload __salt__ too much ret.pack['__salt__'] = ret return ret def queues(opts): ''' Directly call a function inside a loader directory ''' return LazyLoader( _module_dirs(opts, 'queues', 'queue', ext_type_dirs='queue_dirs'), opts, tag='queues', ) def pkgdb(opts): ''' Return modules for SPM's package database .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgdb', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgdb' ) def pkgfiles(opts): ''' Return modules for SPM's file handling .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgfiles', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgfiles' ) def clouds(opts): ''' Return the cloud functions ''' # Let's bring __active_provider_name__, defaulting to None, to all cloud # drivers. This will get temporarily updated/overridden with a context # manager when needed. functions = LazyLoader( _module_dirs(opts, 'clouds', 'cloud', base_path=os.path.join(SALT_BASE_PATH, 'cloud'), int_type='clouds'), opts, tag='clouds', pack={'__utils__': salt.loader.utils(opts), '__active_provider_name__': None}, ) for funcname in LIBCLOUD_FUNCS_NOT_SUPPORTED: log.trace( '\'%s\' has been marked as not supported. Removing from the ' 'list of supported cloud functions', funcname ) functions.pop(funcname, None) return functions def netapi(opts): ''' Return the network api functions ''' return LazyLoader( _module_dirs(opts, 'netapi'), opts, tag='netapi', ) def executors(opts, functions=None, context=None, proxy=None): ''' Returns the executor modules ''' executors = LazyLoader( _module_dirs(opts, 'executors', 'executor'), opts, tag='executor', pack={'__salt__': functions, '__context__': context or {}, '__proxy__': proxy or {}}, ) executors.pack['__executors__'] = executors return executors def cache(opts, serial): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'cache', 'cache'), opts, tag='cache', pack={'__opts__': opts, '__context__': {'serial': serial}}, ) def _generate_module(name): if name in sys.modules: return code = "'''Salt loaded {0} parent module'''".format(name.split('.')[-1]) # ModuleType can't accept a unicode type on PY2 module = types.ModuleType(str(name)) # future lint: disable=blacklisted-function exec(code, module.__dict__) sys.modules[name] = module def _mod_type(module_path): if module_path.startswith(SALT_BASE_PATH): return 'int' return 'ext' def _inject_into_mod(mod, name, value, force_lock=False): ''' Inject a variable into a module. This is used to inject "globals" like ``__salt__``, ``__pillar``, or ``grains``. Instead of injecting the value directly, a ``ThreadLocalProxy`` is created. If such a proxy is already present under the specified name, it is updated with the new value. This update only affects the current thread, so that the same name can refer to different values depending on the thread of execution. This is important for data that is not truly global. For example, pillar data might be dynamically overriden through function parameters and thus the actual values available in pillar might depend on the thread that is calling a module. mod: module object into which the value is going to be injected. name: name of the variable that is injected into the module. value: value that is injected into the variable. The value is not injected directly, but instead set as the new reference of the proxy that has been created for the variable. force_lock: whether the lock should be acquired before checking whether a proxy object for the specified name has already been injected into the module. If ``False`` (the default), this function checks for the module's variable without acquiring the lock and only acquires the lock if a new proxy has to be created and injected. ''' old_value = getattr(mod, name, None) # We use a double-checked locking scheme in order to avoid taking the lock # when a proxy object has already been injected. # In most programming languages, double-checked locking is considered # unsafe when used without explicit memory barriers because one might read # an uninitialized value. In CPython it is safe due to the global # interpreter lock (GIL). In Python implementations that do not have the # GIL, it could be unsafe, but at least Jython also guarantees that (for # Python objects) memory is not corrupted when writing and reading without # explicit synchronization # (http://www.jython.org/jythonbook/en/1.0/Concurrency.html). # Please note that in order to make this code safe in a runtime environment # that does not make this guarantees, it is not sufficient. The # ThreadLocalProxy must also be created with fallback_to_shared set to # False or a lock must be added to the ThreadLocalProxy. if force_lock: with _inject_into_mod.lock: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: setattr(mod, name, ThreadLocalProxy(value, True)) else: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: _inject_into_mod(mod, name, value, True) # Lock used when injecting globals. This is needed to avoid a race condition # when two threads try to load the same module concurrently. This must be # outside the loader because there might be more than one loader for the same # namespace. _inject_into_mod.lock = threading.RLock() # TODO: move somewhere else? class FilterDictWrapper(MutableMapping): ''' Create a dict which wraps another dict with a specific key suffix on get This is to replace "filter_load" ''' def __init__(self, d, suffix): self._dict = d self.suffix = suffix def __setitem__(self, key, val): self._dict[key] = val def __delitem__(self, key): del self._dict[key] def __getitem__(self, key): return self._dict[key + self.suffix] def __len__(self): return len(self._dict) def __iter__(self): for key in self._dict: if key.endswith(self.suffix): yield key.replace(self.suffix, '') class LazyLoader(salt.utils.lazy.LazyDict): ''' A pseduo-dictionary which has a set of keys which are the name of the module and function, delimited by a dot. When the value of the key is accessed, the function is then loaded from disk and into memory. .. note:: Iterating over keys will cause all modules to be loaded. :param list module_dirs: A list of directories on disk to search for modules :param dict opts: The salt options dictionary. :param str tag: The tag for the type of module to load :param func mod_type_check: A function which can be used to verify files :param dict pack: A dictionary of function to be packed into modules as they are loaded :param list whitelist: A list of modules to whitelist :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules. :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality. If not true, the module will not load. :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values are function references themselves which are loaded on-demand. # TODO: - move modules_max_memory into here - singletons (per tag) ''' mod_dict_class = salt.utils.odict.OrderedDict def __init__(self, module_dirs, opts=None, tag='module', loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, proxy=None, virtual_funcs=None, ): # pylint: disable=W0231 ''' In pack, if any of the values are None they will be replaced with an empty context-specific dict ''' self.inject_globals = {} self.pack = {} if pack is None else pack if opts is None: opts = {} threadsafety = not opts.get('multiprocessing') self.context_dict = salt.utils.context.ContextDict(threadsafe=threadsafety) self.opts = self.__prep_mod_opts(opts) self.module_dirs = module_dirs self.tag = tag self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME self.mod_type_check = mod_type_check or _mod_type if '__context__' not in self.pack: self.pack['__context__'] = None for k, v in six.iteritems(self.pack): if v is None: # if the value of a pack is None, lets make an empty dict value = self.context_dict.get(k, {}) if isinstance(value, ThreadLocalProxy): value = ThreadLocalProxy.unproxy(value) self.context_dict[k] = value self.pack[k] = salt.utils.context.NamespacedDictWrapper(self.context_dict, k) self.whitelist = whitelist self.virtual_enable = virtual_enable self.initial_load = True # names of modules that we don't have (errors, __virtual__, etc.) self.missing_modules = {} # mapping of name -> error self.loaded_modules = {} # mapping of module_name -> dict_of_functions self.loaded_files = set() # TODO: just remove them from file_mapping? self.static_modules = static_modules if static_modules else [] if virtual_funcs is None: virtual_funcs = [] self.virtual_funcs = virtual_funcs self.disabled = set( self.opts.get( 'disable_{0}{1}'.format( self.tag, '' if self.tag[-1] == 's' else 's' ), [] ) ) # A map of suffix to description for imp self.suffix_map = {} # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [''] for (suffix, mode, kind) in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) self._lock = threading.RLock() self._refresh_file_mapping() super(LazyLoader, self).__init__() # late init the lazy loader # create all of the import namespaces _generate_module('{0}.int'.format(self.loaded_base_name)) _generate_module('{0}.int.{1}'.format(self.loaded_base_name, tag)) _generate_module('{0}.ext'.format(self.loaded_base_name)) _generate_module('{0}.ext.{1}'.format(self.loaded_base_name, tag)) def __getitem__(self, item): ''' Override the __getitem__ in order to decorate the returned function if we need to last-minute inject globals ''' func = super(LazyLoader, self).__getitem__(item) if self.inject_globals: return global_injector_decorator(self.inject_globals)(func) else: return func def __getattr__(self, mod_name): ''' Allow for "direct" attribute access-- this allows jinja templates to access things like `salt.test.ping()` ''' if mod_name in ('__getstate__', '__setstate__'): return object.__getattribute__(self, mod_name) # if we have an attribute named that, lets return it. try: return object.__getattr__(self, mod_name) # pylint: disable=no-member except AttributeError: pass # otherwise we assume its jinja template access if mod_name not in self.loaded_modules and not self.loaded: for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and mod_name in self.loaded_modules: break if mod_name in self.loaded_modules: return self.loaded_modules[mod_name] else: raise AttributeError(mod_name) def missing_fun_string(self, function_name): ''' Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ''' mod_name = function_name.split('.')[0] if mod_name in self.loaded_modules: return '\'{0}\' is not available.'.format(function_name) else: try: reason = self.missing_modules[mod_name] except KeyError: return '\'{0}\' is not available.'.format(function_name) else: if reason is not None: return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason) else: return '\'{0}\' __virtual__ returned False'.format(mod_name) def _refresh_file_mapping(self): ''' refresh the mapping of the FS on disk ''' # map of suffix to description for imp if self.opts.get('cython_enable', True) is True: try: global pyximport pyximport = __import__('pyximport') # pylint: disable=import-error pyximport.install() # add to suffix_map so file_mapping will pick it up self.suffix_map['.pyx'] = tuple() except ImportError: log.info('Cython is enabled in the options but not present ' 'in the system path. Skipping Cython modules.') # Allow for zipimport of modules if self.opts.get('enable_zip_modules', True) is True: self.suffix_map['.zip'] = tuple() # allow for module dirs if USE_IMPORTLIB: self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY) else: self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY) # create mapping of filename (without suffix) to (path, suffix) # The files are added in order of priority, so order *must* be retained. self.file_mapping = salt.utils.odict.OrderedDict() opt_match = [] def _replace_pre_ext(obj): ''' Hack so we can get the optimization level that we replaced (if any) out of the re.sub call below. We use a list here because it is a persistent data structure that we will be able to access after re.sub is called. ''' opt_match.append(obj) return '' for mod_dir in self.module_dirs: try: # Make sure we have a sorted listdir in order to have # expectable override results files = sorted( x for x in os.listdir(mod_dir) if x != '__pycache__' ) except OSError: continue # Next mod_dir if six.PY3: try: pycache_files = [ os.path.join('__pycache__', x) for x in sorted(os.listdir(os.path.join(mod_dir, '__pycache__'))) ] except OSError: pass else: files.extend(pycache_files) for filename in files: try: dirname, basename = os.path.split(filename) if basename.startswith('_'): # skip private modules # log messages omitted for obviousness continue # Next filename f_noext, ext = os.path.splitext(basename) if six.PY3: f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext) try: opt_level = int( opt_match.pop().group(1).rsplit('-', 1)[-1] ) except (AttributeError, IndexError, ValueError): # No regex match or no optimization level matched opt_level = 0 try: opt_index = self.opts['optimization_order'].index(opt_level) except KeyError: log.trace( 'Disallowed optimization level %d for module ' 'name \'%s\', skipping. Add %d to the ' '\'optimization_order\' config option if you ' 'do not want to ignore this optimization ' 'level.', opt_level, f_noext, opt_level ) continue else: # Optimization level not reflected in filename on PY2 opt_index = 0 # make sure it is a suffix we support if ext not in self.suffix_map: continue # Next filename if f_noext in self.disabled: log.trace( 'Skipping %s, it is disabled by configuration', filename ) continue # Next filename fpath = os.path.join(mod_dir, filename) # if its a directory, lets allow us to load that if ext == '': # is there something __init__? subfiles = os.listdir(fpath) for suffix in self.suffix_order: if '' == suffix: continue # Next suffix (__init__ must have a suffix) init_file = '__init__{0}'.format(suffix) if init_file in subfiles: break else: continue # Next filename try: curr_ext = self.file_mapping[f_noext][1] curr_opt_index = self.file_mapping[f_noext][2] except KeyError: pass else: if '' in (curr_ext, ext) and curr_ext != ext: log.error( 'Module/package collision: \'%s\' and \'%s\'', fpath, self.file_mapping[f_noext][0] ) if six.PY3 and ext == '.pyc' and curr_ext == '.pyc': # Check the optimization level if opt_index >= curr_opt_index: # Module name match, but a higher-priority # optimization level was already matched, skipping. continue elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext): # Match found but a higher-priorty match already # exists, so skip this. continue if six.PY3 and not dirname and ext == '.pyc': # On Python 3, we should only load .pyc files from the # __pycache__ subdirectory (i.e. when dirname is not an # empty string). continue # Made it this far - add it self.file_mapping[f_noext] = (fpath, ext, opt_index) except OSError: continue for smod in self.static_modules: f_noext = smod.split('.')[-1] self.file_mapping[f_noext] = (smod, '.o', 0) def clear(self): ''' Clear the dict ''' with self._lock: super(LazyLoader, self).clear() # clear the lazy loader self.loaded_files = set() self.missing_modules = {} self.loaded_modules = {} # if we have been loaded before, lets clear the file mapping since # we obviously want a re-do if hasattr(self, 'opts'): self._refresh_file_mapping() self.initial_load = False def __prep_mod_opts(self, opts): ''' Strip out of the opts any logger instance ''' if '__grains__' not in self.pack: grains = opts.get('grains', {}) if isinstance(grains, ThreadLocalProxy): grains = ThreadLocalProxy.unproxy(grains) self.context_dict['grains'] = grains self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains') if '__pillar__' not in self.pack: pillar = opts.get('pillar', {}) if isinstance(pillar, ThreadLocalProxy): pillar = ThreadLocalProxy.unproxy(pillar) self.context_dict['pillar'] = pillar self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar') mod_opts = {} for key, val in list(opts.items()): if key == 'logger': continue mod_opts[key] = val return mod_opts def _iter_files(self, mod_name): ''' Iterate over all file_mapping files in order of closeness to mod_name ''' # do we have an exact match? if mod_name in self.file_mapping: yield mod_name # do we have a partial match? for k in self.file_mapping: if mod_name in k: yield k # anyone else? Bueller? for k in self.file_mapping: if mod_name not in k: yield k def _reload_submodules(self, mod): submodules = ( getattr(mod, sname) for sname in dir(mod) if isinstance(getattr(mod, sname), mod.__class__) ) # reload only custom "sub"modules for submodule in submodules: # it is a submodule if the name is in a namespace under mod if submodule.__name__.startswith(mod.__name__ + '.'): reload_module(submodule) self._reload_submodules(submodule) def _load_module(self, name): mod = None fpath, suffix = self.file_mapping[name][:2] self.loaded_files.add(name) fpath_dirname = os.path.dirname(fpath) try: sys.path.append(fpath_dirname) if suffix == '.pyx': mod = pyximport.load_module(name, fpath, tempfile.gettempdir()) elif suffix == '.o': top_mod = __import__(fpath, globals(), locals(), []) comps = fpath.split('.') if len(comps) < 2: mod = top_mod else: mod = top_mod for subname in comps[1:]: mod = getattr(mod, subname) elif suffix == '.zip': mod = zipimporter(fpath).load_module(name) else: desc = self.suffix_map[suffix] # if it is a directory, we don't open a file try: mod_namespace = '.'.join(( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name)) except TypeError: mod_namespace = '{0}.{1}.{2}.{3}'.format( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name) if suffix == '': if USE_IMPORTLIB: # pylint: disable=no-member # Package directory, look for __init__ loader_details = [ (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES), (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES), (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), ] file_finder = importlib.machinery.FileFinder( fpath_dirname, *loader_details ) spec = file_finder.find_spec(mod_namespace) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: mod = imp.load_module(mod_namespace, None, fpath, desc) # reload all submodules if necessary if not self.initial_load: self._reload_submodules(mod) else: if USE_IMPORTLIB: # pylint: disable=no-member loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath) spec = importlib.util.spec_from_file_location( mod_namespace, fpath, loader=loader ) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() #mod = importlib.util.module_from_spec(spec) #spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: with salt.utils.files.fopen(fpath, desc[1]) as fn_: mod = imp.load_module(mod_namespace, fn_, fpath, desc) except IOError: raise except ImportError as exc: if 'magic number' in six.text_type(exc): error_msg = 'Failed to import {0} {1}. Bad magic number. If migrating from Python2 to Python3, remove all .pyc files and try again.'.format(self.tag, name) log.warning(error_msg) self.missing_modules[name] = error_msg log.debug( 'Failed to import %s %s:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = exc return False except Exception as error: log.error( 'Failed to import %s %s, this is due most likely to a ' 'syntax error:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False except SystemExit as error: try: fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1] except Exception: pass else: tgt_fn = os.path.join('salt', 'utils', 'process.py') if fn_.endswith(tgt_fn) and '_handle_signals' in caller: # Race conditon, SIGTERM or SIGINT received while loader # was in process of loading a module. Call sys.exit to # ensure that the process is killed. sys.exit(salt.defaults.exitcodes.EX_OK) log.error( 'Failed to import %s %s as the module called exit()\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False finally: sys.path.remove(fpath_dirname) if hasattr(mod, '__opts__'): mod.__opts__.update(self.opts) else: mod.__opts__ = self.opts # pack whatever other globals we were asked to for p_name, p_value in six.iteritems(self.pack): _inject_into_mod(mod, p_name, p_value) module_name = mod.__name__.rsplit('.', 1)[-1] # Call a module's initialization method if it exists module_init = getattr(mod, '__init__', None) if inspect.isfunction(module_init): try: module_init(self.opts) except TypeError as e: log.error(e) except Exception: err_string = '__init__ failed' log.debug( 'Error loading %s.%s: %s', self.tag, module_name, err_string, exc_info=True ) self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False # if virtual modules are enabled, we need to look for the # __virtual__() function inside that module and run it. if self.virtual_enable: virtual_funcs_to_process = ['__virtual__'] + self.virtual_funcs for virtual_func in virtual_funcs_to_process: virtual_ret, module_name, virtual_err, virtual_aliases = \ self._process_virtual(mod, module_name, virtual_func) if virtual_err is not None: log.trace( 'Error loading %s.%s: %s', self.tag, module_name, virtual_err ) # if _process_virtual returned a non-True value then we are # supposed to not process this module if virtual_ret is not True and module_name not in self.missing_modules: # If a module has information about why it could not be loaded, record it self.missing_modules[module_name] = virtual_err self.missing_modules[name] = virtual_err return False else: virtual_aliases = () # If this is a proxy minion then MOST modules cannot work. Therefore, require that # any module that does work with salt-proxy-minion define __proxyenabled__ as a list # containing the names of the proxy types that the module supports. # # Render modules and state modules are OK though if 'proxy' in self.opts: if self.tag in ['grains', 'proxy']: if not hasattr(mod, '__proxyenabled__') or \ (self.opts['proxy']['proxytype'] not in mod.__proxyenabled__ and '*' not in mod.__proxyenabled__): err_string = 'not a proxy_minion enabled module' self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False if getattr(mod, '__load__', False) is not False: log.info( 'The functions from module \'%s\' are being loaded from the ' 'provided __load__ attribute', module_name ) # If we had another module by the same virtual name, we should put any # new functions under the existing dictionary. mod_names = [module_name] + list(virtual_aliases) mod_dict = dict(( (x, self.loaded_modules.get(x, self.mod_dict_class())) for x in mod_names )) for attr in getattr(mod, '__load__', dir(mod)): if attr.startswith('_') and attr != '__call__': # private functions are skipped, # except __call__ which is default entrance # for multi-function batch-like state syntax continue func = getattr(mod, attr) if not inspect.isfunction(func) and not isinstance(func, functools.partial): # Not a function!? Skip it!!! continue # Let's get the function name. # If the module has the __func_alias__ attribute, it must be a # dictionary mapping in the form of(key -> value): # <real-func-name> -> <desired-func-name> # # It default's of course to the found callable attribute name # if no alias is defined. funcname = getattr(mod, '__func_alias__', {}).get(attr, attr) for tgt_mod in mod_names: try: full_funcname = '.'.join((tgt_mod, funcname)) except TypeError: full_funcname = '{0}.{1}'.format(tgt_mod, funcname) # Save many references for lookups # Careful not to overwrite existing (higher priority) functions if full_funcname not in self._dict: self._dict[full_funcname] = func if funcname not in mod_dict[tgt_mod]: setattr(mod_dict[tgt_mod], funcname, func) mod_dict[tgt_mod][funcname] = func self._apply_outputter(func, mod) # enforce depends try: Depends.enforce_dependencies(self._dict, self.tag) except RuntimeError as exc: log.info( 'Depends.enforce_dependencies() failed for the following ' 'reason: %s', exc ) for tgt_mod in mod_names: self.loaded_modules[tgt_mod] = mod_dict[tgt_mod] return True def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise KeyError('The key \'{0}\' should contain a \'.\''.format(key)) mod_name, _ = key.split('.', 1) with self._lock: # It is possible that the key is in the dictionary after # acquiring the lock due to another thread loading it. if mod_name in self.missing_modules or key in self._dict: return True # if the modulename isn't in the whitelist, don't bother if self.whitelist and mod_name not in self.whitelist: log.error( 'Failed to load function %s because its module (%s) is ' 'not in the whitelist: %s', key, mod_name, self.whitelist ) raise KeyError(key) def _inner_load(mod_name): for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and key in self._dict: return True return False # try to load the module ret = None reloaded = False # re-scan up to once, IOErrors or a failed load cause re-scans of the # filesystem while True: try: ret = _inner_load(mod_name) if not reloaded and ret is not True: self._refresh_file_mapping() reloaded = True continue break except IOError: if not reloaded: self._refresh_file_mapping() reloaded = True continue return ret def _load_all(self): ''' Load all of them ''' with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True def reload_modules(self): with self._lock: self.loaded_files = set() self._load_all() def _apply_outputter(self, func, mod): ''' Apply the __outputter__ variable to the functions ''' if hasattr(mod, '__outputter__'): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__] def _process_virtual(self, mod, module_name, virtual_func='__virtual__'): ''' Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1] ''' # The __virtual__ function will return either a True or False value. # If it returns a True value it can also set a module level attribute # named __virtualname__ with the name that the module should be # referred to as. # # This allows us to have things like the pkg module working on all # platforms under the name 'pkg'. It also allows for modules like # augeas_cfg to be referred to as 'augeas', which would otherwise have # namespace collisions. And finally it allows modules to return False # if they are not intended to run on the given platform or are missing # dependencies. virtual_aliases = getattr(mod, '__virtual_aliases__', tuple()) try: error_reason = None if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__): try: start = time.time() virtual = getattr(mod, virtual_func)() if isinstance(virtual, tuple): error_reason = virtual[1] virtual = virtual[0] if self.opts.get('virtual_timer', False): end = time.time() - start msg = 'Virtual function took {0} seconds for {1}'.format( end, module_name) log.warning(msg) except Exception as exc: error_reason = ( 'Exception raised when processing __virtual__ function' ' for {0}. Module will not be loaded: {1}'.format( mod.__name__, exc)) log.error(error_reason, exc_info_on_loglevel=logging.DEBUG) virtual = None # Get the module's virtual name virtualname = getattr(mod, '__virtualname__', virtual) if not virtual: # if __virtual__() evaluates to False then the module # wasn't meant for this platform or it's not supposed to # load for some other reason. # Some modules might accidentally return None and are # improperly loaded if virtual is None: log.warning( '%s.__virtual__() is wrongly returning `None`. ' 'It should either return `True`, `False` or a new ' 'name. If you\'re the developer of the module ' '\'%s\', please fix this.', mod.__name__, module_name ) return (False, module_name, error_reason, virtual_aliases) # At this point, __virtual__ did not return a # boolean value, let's check for deprecated usage # or module renames if virtual is not True and module_name != virtual: # The module is renaming itself. Updating the module name # with the new name log.trace('Loaded %s as virtual %s', module_name, virtual) if virtualname != virtual: # The __virtualname__ attribute does not match what's # being returned by the __virtual__() function. This # should be considered an error. log.error( 'The module \'%s\' is showing some bad usage. Its ' '__virtualname__ attribute is set to \'%s\' yet the ' '__virtual__() function is returning \'%s\'. These ' 'values should match!', mod.__name__, virtualname, virtual ) module_name = virtualname # If the __virtual__ function returns True and __virtualname__ # is set then use it elif virtual is True and virtualname != module_name: if virtualname is not True: module_name = virtualname except KeyError: # Key errors come out of the virtual function when passing # in incomplete grains sets, these can be safely ignored # and logged to debug, still, it includes the traceback to # help debugging. log.debug('KeyError when loading %s', module_name, exc_info=True) except Exception: # If the module throws an exception during __virtual__() # then log the information and continue to the next. log.error( 'Failed to read the virtual function for %s: %s', self.tag, module_name, exc_info=True ) return (False, module_name, error_reason, virtual_aliases) return (True, module_name, None, virtual_aliases) def global_injector_decorator(inject_globals): ''' Decorator used by the LazyLoader to inject globals into a function at execute time. globals Dictionary with global variables to inject ''' def inner_decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): with salt.utils.context.func_globals_inject(f, **inject_globals): return f(*args, **kwargs) return wrapper return inner_decorator
saltstack/salt
salt/loader.py
pkgdb
python
def pkgdb(opts): ''' Return modules for SPM's package database .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgdb', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgdb' )
Return modules for SPM's package database .. versionadded:: 2015.8.0
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L981-L995
null
# -*- coding: utf-8 -*- ''' The Salt loader is the core to Salt's plugin system, the loader scans directories for python loadable code and organizes the code into the plugin interfaces used by Salt. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import sys import time import logging import inspect import tempfile import threading import functools import threading import traceback import types from zipimport import zipimporter # Import salt libs import salt.config import salt.defaults.events import salt.defaults.exitcodes import salt.syspaths import salt.utils.args import salt.utils.context import salt.utils.data import salt.utils.dictupdate import salt.utils.event import salt.utils.files import salt.utils.lazy import salt.utils.odict import salt.utils.platform import salt.utils.versions import salt.utils.stringutils from salt.exceptions import LoaderError from salt.template import check_render_pipe_str from salt.utils.decorators import Depends from salt.utils.thread_local_proxy import ThreadLocalProxy # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import reload_module if sys.version_info[:2] >= (3, 5): import importlib.machinery # pylint: disable=no-name-in-module,import-error import importlib.util # pylint: disable=no-name-in-module,import-error USE_IMPORTLIB = True else: import imp USE_IMPORTLIB = False try: from collections.abc import MutableMapping except ImportError: from collections import MutableMapping try: import pkg_resources HAS_PKG_RESOURCES = True except ImportError: HAS_PKG_RESOURCES = False log = logging.getLogger(__name__) SALT_BASE_PATH = os.path.abspath(salt.syspaths.INSTALL_DIR) LOADED_BASE_NAME = 'salt.loaded' if USE_IMPORTLIB: # pylint: disable=no-member MODULE_KIND_SOURCE = 1 MODULE_KIND_COMPILED = 2 MODULE_KIND_EXTENSION = 3 MODULE_KIND_PKG_DIRECTORY = 5 SUFFIXES = [] for suffix in importlib.machinery.EXTENSION_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_EXTENSION)) for suffix in importlib.machinery.SOURCE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_SOURCE)) for suffix in importlib.machinery.BYTECODE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_COMPILED)) MODULE_KIND_MAP = { MODULE_KIND_SOURCE: importlib.machinery.SourceFileLoader, MODULE_KIND_COMPILED: importlib.machinery.SourcelessFileLoader, MODULE_KIND_EXTENSION: importlib.machinery.ExtensionFileLoader } # pylint: enable=no-member else: SUFFIXES = imp.get_suffixes() PY3_PRE_EXT = \ re.compile(r'\.cpython-{0}{1}(\.opt-[1-9])?'.format(*sys.version_info[:2])) # Because on the cloud drivers we do `from salt.cloud.libcloudfuncs import *` # which simplifies code readability, it adds some unsupported functions into # the driver's module scope. # We list un-supported functions here. These will be removed from the loaded. # TODO: remove the need for this cross-module code. Maybe use NotImplemented LIBCLOUD_FUNCS_NOT_SUPPORTED = ( 'parallels.avail_sizes', 'parallels.avail_locations', 'proxmox.avail_sizes', ) # Will be set to pyximport module at runtime if cython is enabled in config. pyximport = None def static_loader( opts, ext_type, tag, pack=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, filter_name=None, ): funcs = LazyLoader( _module_dirs( opts, ext_type, tag, int_type, ext_dirs, ext_type_dirs, base_path, ), opts, tag=tag, pack=pack, ) ret = {} funcs._load_all() if filter_name: funcs = FilterDictWrapper(funcs, filter_name) for key in funcs: ret[key] = funcs[key] return ret def _format_entrypoint_target(ep): ''' Makes a string describing the target of an EntryPoint object. Base strongly on EntryPoint.__str__(). ''' s = ep.module_name if ep.attrs: s += ':' + '.'.join(ep.attrs) return s def _module_dirs( opts, ext_type, tag=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, ): if tag is None: tag = ext_type sys_types = os.path.join(base_path or SALT_BASE_PATH, int_type or ext_type) ext_types = os.path.join(opts['extension_modules'], ext_type) ext_type_types = [] if ext_dirs: if ext_type_dirs is None: ext_type_dirs = '{0}_dirs'.format(tag) if ext_type_dirs in opts: ext_type_types.extend(opts[ext_type_dirs]) if HAS_PKG_RESOURCES and ext_type_dirs: for entry_point in pkg_resources.iter_entry_points('salt.loader', ext_type_dirs): try: loaded_entry_point = entry_point.load() for path in loaded_entry_point(): ext_type_types.append(path) except Exception as exc: log.error("Error getting module directories from %s: %s", _format_entrypoint_target(entry_point), exc) log.debug("Full backtrace for module directories error", exc_info=True) cli_module_dirs = [] # The dirs can be any module dir, or a in-tree _{ext_type} dir for _dir in opts.get('module_dirs', []): # Prepend to the list to match cli argument ordering maybe_dir = os.path.join(_dir, ext_type) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) continue maybe_dir = os.path.join(_dir, '_{0}'.format(ext_type)) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) return cli_module_dirs + ext_type_types + [ext_types, sys_types] def minion_mods( opts, context=None, utils=None, whitelist=None, initial_load=False, loaded_base_name=None, notify=False, static_modules=None, proxy=None): ''' Load execution modules Returns a dictionary of execution modules appropriate for the current system by evaluating the __virtual__() function in each module. :param dict opts: The Salt options dictionary :param dict context: A Salt context that should be made present inside generated modules in __context__ :param dict utils: Utility functions which should be made available to Salt modules in __utils__. See `utils_dirs` in salt.config for additional information about configuration. :param list whitelist: A list of modules which should be whitelisted. :param bool initial_load: Deprecated flag! Unused. :param str loaded_base_name: A string marker for the loaded base name. :param bool notify: Flag indicating that an event should be fired upon completion of module loading. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) __opts__['grains'] = __grains__ __utils__ = salt.loader.utils(__opts__) __salt__ = salt.loader.minion_mods(__opts__, utils=__utils__) __salt__['test.ping']() ''' # TODO Publish documentation for module whitelisting if not whitelist: whitelist = opts.get('whitelist_modules', None) ret = LazyLoader( _module_dirs(opts, 'modules', 'module'), opts, tag='module', pack={'__context__': context, '__utils__': utils, '__proxy__': proxy}, whitelist=whitelist, loaded_base_name=loaded_base_name, static_modules=static_modules, ) ret.pack['__salt__'] = ret # Load any provider overrides from the configuration file providers option # Note: Providers can be pkg, service, user or group - not to be confused # with cloud providers. providers = opts.get('providers', False) if providers and isinstance(providers, dict): for mod in providers: # sometimes providers opts is not to diverge modules but # for other configuration try: funcs = raw_mod(opts, providers[mod], ret) except TypeError: break else: if funcs: for func in funcs: f_key = '{0}{1}'.format(mod, func[func.rindex('.'):]) ret[f_key] = funcs[func] if notify: evt = salt.utils.event.get_event('minion', opts=opts, listen=False) evt.fire_event({'complete': True}, tag=salt.defaults.events.MINION_MOD_COMPLETE) return ret def raw_mod(opts, name, functions, mod='modules'): ''' Returns a single module loaded raw and bypassing the __virtual__ function .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') testmod = salt.loader.raw_mod(__opts__, 'test', None) testmod['test.ping']() ''' loader = LazyLoader( _module_dirs(opts, mod, 'module'), opts, tag='rawmodule', virtual_enable=False, pack={'__salt__': functions}, ) # if we don't have the module, return an empty dict if name not in loader.file_mapping: return {} loader._load_module(name) # load a single module (the one passed in) return dict(loader._dict) # return a copy of *just* the funcs for `name` def metaproxy(opts): ''' Return functions used in the meta proxy ''' return LazyLoader( _module_dirs(opts, 'metaproxy'), opts, tag='metaproxy' ) def matchers(opts): ''' Return the matcher services plugins ''' return LazyLoader( _module_dirs(opts, 'matchers'), opts, tag='matchers' ) def engines(opts, functions, runners, utils, proxy=None): ''' Return the master services plugins ''' pack = {'__salt__': functions, '__runners__': runners, '__proxy__': proxy, '__utils__': utils} return LazyLoader( _module_dirs(opts, 'engines'), opts, tag='engines', pack=pack, ) def proxy(opts, functions=None, returners=None, whitelist=None, utils=None): ''' Returns the proxy module for this salt-proxy-minion ''' ret = LazyLoader( _module_dirs(opts, 'proxy'), opts, tag='proxy', pack={'__salt__': functions, '__ret__': returners, '__utils__': utils}, ) ret.pack['__proxy__'] = ret return ret def returners(opts, functions, whitelist=None, context=None, proxy=None): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'returners', 'returner'), opts, tag='returner', whitelist=whitelist, pack={'__salt__': functions, '__context__': context, '__proxy__': proxy or {}}, ) def utils(opts, whitelist=None, context=None, proxy=proxy): ''' Returns the utility modules ''' return LazyLoader( _module_dirs(opts, 'utils', ext_type_dirs='utils_dirs'), opts, tag='utils', whitelist=whitelist, pack={'__context__': context, '__proxy__': proxy or {}}, ) def pillars(opts, functions, context=None): ''' Returns the pillars modules ''' ret = LazyLoader(_module_dirs(opts, 'pillar'), opts, tag='pillar', pack={'__salt__': functions, '__context__': context, '__utils__': utils(opts)}) ret.pack['__ext_pillar__'] = ret return FilterDictWrapper(ret, '.ext_pillar') def tops(opts): ''' Returns the tops modules ''' if 'master_tops' not in opts: return {} whitelist = list(opts['master_tops'].keys()) ret = LazyLoader( _module_dirs(opts, 'tops', 'top'), opts, tag='top', whitelist=whitelist, ) return FilterDictWrapper(ret, '.top') def wheels(opts, whitelist=None, context=None): ''' Returns the wheels modules ''' if context is None: context = {} return LazyLoader( _module_dirs(opts, 'wheel'), opts, tag='wheel', whitelist=whitelist, pack={'__context__': context}, ) def outputters(opts): ''' Returns the outputters modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only outputters present in the keyspace ''' ret = LazyLoader( _module_dirs(opts, 'output', ext_type_dirs='outputter_dirs'), opts, tag='output', ) wrapped_ret = FilterDictWrapper(ret, '.output') # TODO: this name seems terrible... __salt__ should always be execution mods ret.pack['__salt__'] = wrapped_ret return wrapped_ret def serializers(opts): ''' Returns the serializers modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only serializers present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'serializers'), opts, tag='serializers', ) def eauth_tokens(opts): ''' Returns the tokens modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only token backends present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'tokens'), opts, tag='tokens', ) def auth(opts, whitelist=None): ''' Returns the auth modules :param dict opts: The Salt options dictionary :returns: LazyLoader ''' return LazyLoader( _module_dirs(opts, 'auth'), opts, tag='auth', whitelist=whitelist, pack={'__salt__': minion_mods(opts)}, ) def fileserver(opts, backends): ''' Returns the file server modules ''' return LazyLoader(_module_dirs(opts, 'fileserver'), opts, tag='fileserver', whitelist=backends, pack={'__utils__': utils(opts)}) def roster(opts, runner=None, utils=None, whitelist=None): ''' Returns the roster modules ''' return LazyLoader( _module_dirs(opts, 'roster'), opts, tag='roster', whitelist=whitelist, pack={ '__runner__': runner, '__utils__': utils, }, ) def thorium(opts, functions, runners): ''' Load the thorium runtime modules ''' pack = {'__salt__': functions, '__runner__': runners, '__context__': {}} ret = LazyLoader(_module_dirs(opts, 'thorium'), opts, tag='thorium', pack=pack) ret.pack['__thorium__'] = ret return ret def states(opts, functions, utils, serializers, whitelist=None, proxy=None, context=None): ''' Returns the state modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') statemods = salt.loader.states(__opts__, None, None) ''' if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'states'), opts, tag='states', pack={'__salt__': functions, '__proxy__': proxy or {}}, whitelist=whitelist, ) ret.pack['__states__'] = ret ret.pack['__utils__'] = utils ret.pack['__serializers__'] = serializers ret.pack['__context__'] = context return ret def beacons(opts, functions, context=None, proxy=None): ''' Load the beacon modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. ''' return LazyLoader( _module_dirs(opts, 'beacons'), opts, tag='beacons', pack={'__context__': context, '__salt__': functions, '__proxy__': proxy or {}}, virtual_funcs=[], ) def log_handlers(opts): ''' Returns the custom logging handler modules :param dict opts: The Salt options dictionary ''' ret = LazyLoader( _module_dirs( opts, 'log_handlers', int_type='handlers', base_path=os.path.join(SALT_BASE_PATH, 'log'), ), opts, tag='log_handlers', ) return FilterDictWrapper(ret, '.setup_handlers') def ssh_wrapper(opts, functions=None, context=None): ''' Returns the custom logging handler modules ''' return LazyLoader( _module_dirs( opts, 'wrapper', base_path=os.path.join(SALT_BASE_PATH, os.path.join('client', 'ssh')), ), opts, tag='wrapper', pack={ '__salt__': functions, '__grains__': opts.get('grains', {}), '__pillar__': opts.get('pillar', {}), '__context__': context, }, ) def render(opts, functions, states=None, proxy=None, context=None): ''' Returns the render modules ''' if context is None: context = {} pack = {'__salt__': functions, '__grains__': opts.get('grains', {}), '__context__': context} if states: pack['__states__'] = states pack['__proxy__'] = proxy or {} ret = LazyLoader( _module_dirs( opts, 'renderers', 'render', ext_type_dirs='render_dirs', ), opts, tag='render', pack=pack, ) rend = FilterDictWrapper(ret, '.render') if not check_render_pipe_str(opts['renderer'], rend, opts['renderer_blacklist'], opts['renderer_whitelist']): err = ('The renderer {0} is unavailable, this error is often because ' 'the needed software is unavailable'.format(opts['renderer'])) log.critical(err) raise LoaderError(err) return rend def grain_funcs(opts, proxy=None): ''' Returns the grain functions .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') grainfuncs = salt.loader.grain_funcs(__opts__) ''' ret = LazyLoader( _module_dirs( opts, 'grains', 'grain', ext_type_dirs='grains_dirs', ), opts, tag='grains', ) ret.pack['__utils__'] = utils(opts, proxy=proxy) return ret def _load_cached_grains(opts, cfn): ''' Returns the grains cached in cfn, or None if the cache is too old or is corrupted. ''' if not os.path.isfile(cfn): log.debug('Grains cache file does not exist.') return None grains_cache_age = int(time.time() - os.path.getmtime(cfn)) if grains_cache_age > opts.get('grains_cache_expiration', 300): log.debug( 'Grains cache last modified %s seconds ago and cache ' 'expiration is set to %s. Grains cache expired. ' 'Refreshing.', grains_cache_age, opts.get('grains_cache_expiration', 300) ) return None if opts.get('refresh_grains_cache', False): log.debug('refresh_grains_cache requested, Refreshing.') return None log.debug('Retrieving grains from cache') try: serial = salt.payload.Serial(opts) with salt.utils.files.fopen(cfn, 'rb') as fp_: cached_grains = salt.utils.data.decode(serial.load(fp_), preserve_tuples=True) if not cached_grains: log.debug('Cached grains are empty, cache might be corrupted. Refreshing.') return None return cached_grains except (IOError, OSError): return None def grains(opts, force_refresh=False, proxy=None): ''' Return the functions for the dynamic grains and the values for the static grains. Since grains are computed early in the startup process, grains functions do not have __salt__ or __proxy__ available. At proxy-minion startup, this function is called with the proxymodule LazyLoader object so grains functions can communicate with their controlled device. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) print __grains__['id'] ''' # Need to re-import salt.config, somehow it got lost when a minion is starting import salt.config # if we have no grains, lets try loading from disk (TODO: move to decorator?) cfn = os.path.join( opts['cachedir'], 'grains.cache.p' ) if not force_refresh and opts.get('grains_cache', False): cached_grains = _load_cached_grains(opts, cfn) if cached_grains: return cached_grains else: log.debug('Grains refresh requested. Refreshing grains.') if opts.get('skip_grains', False): return {} grains_deep_merge = opts.get('grains_deep_merge', False) is True if 'conf_file' in opts: pre_opts = {} pre_opts.update(salt.config.load_config( opts['conf_file'], 'SALT_MINION_CONFIG', salt.config.DEFAULT_MINION_OPTS['conf_file'] )) default_include = pre_opts.get( 'default_include', opts['default_include'] ) include = pre_opts.get('include', []) pre_opts.update(salt.config.include_config( default_include, opts['conf_file'], verbose=False )) pre_opts.update(salt.config.include_config( include, opts['conf_file'], verbose=True )) if 'grains' in pre_opts: opts['grains'] = pre_opts['grains'] else: opts['grains'] = {} else: opts['grains'] = {} grains_data = {} blist = opts.get('grains_blacklist', []) funcs = grain_funcs(opts, proxy=proxy) if force_refresh: # if we refresh, lets reload grain modules funcs.clear() # Run core grains for key in funcs: if not key.startswith('core.'): continue log.trace('Loading %s grain', key) ret = funcs[key]() if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) # Run the rest of the grains for key in funcs: if key.startswith('core.') or key == '_errors': continue try: # Grains are loaded too early to take advantage of the injected # __proxy__ variable. Pass an instance of that LazyLoader # here instead to grains functions if the grains functions take # one parameter. Then the grains can have access to the # proxymodule for retrieving information from the connected # device. log.trace('Loading %s grain', key) parameters = salt.utils.args.get_function_argspec(funcs[key]).args kwargs = {} if 'proxy' in parameters: kwargs['proxy'] = proxy if 'grains' in parameters: kwargs['grains'] = grains_data ret = funcs[key](**kwargs) except Exception: if salt.utils.platform.is_proxy(): log.info('The following CRITICAL message may not be an error; the proxy may not be completely established yet.') log.critical( 'Failed to load grains defined in grain file %s in ' 'function %s, error:\n', key, funcs[key], exc_info=True ) continue if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) if opts.get('proxy_merge_grains_in_module', True) and proxy: try: proxytype = proxy.opts['proxy']['proxytype'] if proxytype + '.grains' in proxy: if proxytype + '.initialized' in proxy and proxy[proxytype + '.initialized'](): try: proxytype = proxy.opts['proxy']['proxytype'] ret = proxy[proxytype + '.grains']() if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) except Exception: log.critical('Failed to run proxy\'s grains function!', exc_info=True ) except KeyError: pass grains_data.update(opts['grains']) # Write cache if enabled if opts.get('grains_cache', False): with salt.utils.files.set_umask(0o077): try: if salt.utils.platform.is_windows(): # Late import import salt.modules.cmdmod # Make sure cache file isn't read-only salt.modules.cmdmod._run_quiet('attrib -R "{0}"'.format(cfn)) with salt.utils.files.fopen(cfn, 'w+b') as fp_: try: serial = salt.payload.Serial(opts) serial.dump(grains_data, fp_) except TypeError as e: log.error('Failed to serialize grains cache: %s', e) raise # re-throw for cleanup except Exception as e: log.error('Unable to write to grains cache file %s: %s', cfn, e) # Based on the original exception, the file may or may not have been # created. If it was, we will remove it now, as the exception means # the serialized data is not to be trusted, no matter what the # exception is. if os.path.isfile(cfn): os.unlink(cfn) if grains_deep_merge: salt.utils.dictupdate.update(grains_data, opts['grains']) else: grains_data.update(opts['grains']) return salt.utils.data.decode(grains_data, preserve_tuples=True) # TODO: get rid of? Does anyone use this? You should use raw() instead def call(fun, **kwargs): ''' Directly call a function inside a loader directory ''' args = kwargs.get('args', []) dirs = kwargs.get('dirs', []) funcs = LazyLoader( [os.path.join(SALT_BASE_PATH, 'modules')] + dirs, None, tag='modules', virtual_enable=False, ) return funcs[fun](*args) def runner(opts, utils=None, context=None, whitelist=None): ''' Directly call a function inside a loader directory ''' if utils is None: utils = {} if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'runners', 'runner', ext_type_dirs='runner_dirs'), opts, tag='runners', pack={'__utils__': utils, '__context__': context}, whitelist=whitelist, ) # TODO: change from __salt__ to something else, we overload __salt__ too much ret.pack['__salt__'] = ret return ret def queues(opts): ''' Directly call a function inside a loader directory ''' return LazyLoader( _module_dirs(opts, 'queues', 'queue', ext_type_dirs='queue_dirs'), opts, tag='queues', ) def sdb(opts, functions=None, whitelist=None, utils=None): ''' Make a very small database call ''' if utils is None: utils = {} return LazyLoader( _module_dirs(opts, 'sdb'), opts, tag='sdb', pack={ '__sdb__': functions, '__opts__': opts, '__utils__': utils, '__salt__': minion_mods(opts, utils), }, whitelist=whitelist, ) def pkgfiles(opts): ''' Return modules for SPM's file handling .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgfiles', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgfiles' ) def clouds(opts): ''' Return the cloud functions ''' # Let's bring __active_provider_name__, defaulting to None, to all cloud # drivers. This will get temporarily updated/overridden with a context # manager when needed. functions = LazyLoader( _module_dirs(opts, 'clouds', 'cloud', base_path=os.path.join(SALT_BASE_PATH, 'cloud'), int_type='clouds'), opts, tag='clouds', pack={'__utils__': salt.loader.utils(opts), '__active_provider_name__': None}, ) for funcname in LIBCLOUD_FUNCS_NOT_SUPPORTED: log.trace( '\'%s\' has been marked as not supported. Removing from the ' 'list of supported cloud functions', funcname ) functions.pop(funcname, None) return functions def netapi(opts): ''' Return the network api functions ''' return LazyLoader( _module_dirs(opts, 'netapi'), opts, tag='netapi', ) def executors(opts, functions=None, context=None, proxy=None): ''' Returns the executor modules ''' executors = LazyLoader( _module_dirs(opts, 'executors', 'executor'), opts, tag='executor', pack={'__salt__': functions, '__context__': context or {}, '__proxy__': proxy or {}}, ) executors.pack['__executors__'] = executors return executors def cache(opts, serial): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'cache', 'cache'), opts, tag='cache', pack={'__opts__': opts, '__context__': {'serial': serial}}, ) def _generate_module(name): if name in sys.modules: return code = "'''Salt loaded {0} parent module'''".format(name.split('.')[-1]) # ModuleType can't accept a unicode type on PY2 module = types.ModuleType(str(name)) # future lint: disable=blacklisted-function exec(code, module.__dict__) sys.modules[name] = module def _mod_type(module_path): if module_path.startswith(SALT_BASE_PATH): return 'int' return 'ext' def _inject_into_mod(mod, name, value, force_lock=False): ''' Inject a variable into a module. This is used to inject "globals" like ``__salt__``, ``__pillar``, or ``grains``. Instead of injecting the value directly, a ``ThreadLocalProxy`` is created. If such a proxy is already present under the specified name, it is updated with the new value. This update only affects the current thread, so that the same name can refer to different values depending on the thread of execution. This is important for data that is not truly global. For example, pillar data might be dynamically overriden through function parameters and thus the actual values available in pillar might depend on the thread that is calling a module. mod: module object into which the value is going to be injected. name: name of the variable that is injected into the module. value: value that is injected into the variable. The value is not injected directly, but instead set as the new reference of the proxy that has been created for the variable. force_lock: whether the lock should be acquired before checking whether a proxy object for the specified name has already been injected into the module. If ``False`` (the default), this function checks for the module's variable without acquiring the lock and only acquires the lock if a new proxy has to be created and injected. ''' old_value = getattr(mod, name, None) # We use a double-checked locking scheme in order to avoid taking the lock # when a proxy object has already been injected. # In most programming languages, double-checked locking is considered # unsafe when used without explicit memory barriers because one might read # an uninitialized value. In CPython it is safe due to the global # interpreter lock (GIL). In Python implementations that do not have the # GIL, it could be unsafe, but at least Jython also guarantees that (for # Python objects) memory is not corrupted when writing and reading without # explicit synchronization # (http://www.jython.org/jythonbook/en/1.0/Concurrency.html). # Please note that in order to make this code safe in a runtime environment # that does not make this guarantees, it is not sufficient. The # ThreadLocalProxy must also be created with fallback_to_shared set to # False or a lock must be added to the ThreadLocalProxy. if force_lock: with _inject_into_mod.lock: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: setattr(mod, name, ThreadLocalProxy(value, True)) else: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: _inject_into_mod(mod, name, value, True) # Lock used when injecting globals. This is needed to avoid a race condition # when two threads try to load the same module concurrently. This must be # outside the loader because there might be more than one loader for the same # namespace. _inject_into_mod.lock = threading.RLock() # TODO: move somewhere else? class FilterDictWrapper(MutableMapping): ''' Create a dict which wraps another dict with a specific key suffix on get This is to replace "filter_load" ''' def __init__(self, d, suffix): self._dict = d self.suffix = suffix def __setitem__(self, key, val): self._dict[key] = val def __delitem__(self, key): del self._dict[key] def __getitem__(self, key): return self._dict[key + self.suffix] def __len__(self): return len(self._dict) def __iter__(self): for key in self._dict: if key.endswith(self.suffix): yield key.replace(self.suffix, '') class LazyLoader(salt.utils.lazy.LazyDict): ''' A pseduo-dictionary which has a set of keys which are the name of the module and function, delimited by a dot. When the value of the key is accessed, the function is then loaded from disk and into memory. .. note:: Iterating over keys will cause all modules to be loaded. :param list module_dirs: A list of directories on disk to search for modules :param dict opts: The salt options dictionary. :param str tag: The tag for the type of module to load :param func mod_type_check: A function which can be used to verify files :param dict pack: A dictionary of function to be packed into modules as they are loaded :param list whitelist: A list of modules to whitelist :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules. :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality. If not true, the module will not load. :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values are function references themselves which are loaded on-demand. # TODO: - move modules_max_memory into here - singletons (per tag) ''' mod_dict_class = salt.utils.odict.OrderedDict def __init__(self, module_dirs, opts=None, tag='module', loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, proxy=None, virtual_funcs=None, ): # pylint: disable=W0231 ''' In pack, if any of the values are None they will be replaced with an empty context-specific dict ''' self.inject_globals = {} self.pack = {} if pack is None else pack if opts is None: opts = {} threadsafety = not opts.get('multiprocessing') self.context_dict = salt.utils.context.ContextDict(threadsafe=threadsafety) self.opts = self.__prep_mod_opts(opts) self.module_dirs = module_dirs self.tag = tag self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME self.mod_type_check = mod_type_check or _mod_type if '__context__' not in self.pack: self.pack['__context__'] = None for k, v in six.iteritems(self.pack): if v is None: # if the value of a pack is None, lets make an empty dict value = self.context_dict.get(k, {}) if isinstance(value, ThreadLocalProxy): value = ThreadLocalProxy.unproxy(value) self.context_dict[k] = value self.pack[k] = salt.utils.context.NamespacedDictWrapper(self.context_dict, k) self.whitelist = whitelist self.virtual_enable = virtual_enable self.initial_load = True # names of modules that we don't have (errors, __virtual__, etc.) self.missing_modules = {} # mapping of name -> error self.loaded_modules = {} # mapping of module_name -> dict_of_functions self.loaded_files = set() # TODO: just remove them from file_mapping? self.static_modules = static_modules if static_modules else [] if virtual_funcs is None: virtual_funcs = [] self.virtual_funcs = virtual_funcs self.disabled = set( self.opts.get( 'disable_{0}{1}'.format( self.tag, '' if self.tag[-1] == 's' else 's' ), [] ) ) # A map of suffix to description for imp self.suffix_map = {} # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [''] for (suffix, mode, kind) in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) self._lock = threading.RLock() self._refresh_file_mapping() super(LazyLoader, self).__init__() # late init the lazy loader # create all of the import namespaces _generate_module('{0}.int'.format(self.loaded_base_name)) _generate_module('{0}.int.{1}'.format(self.loaded_base_name, tag)) _generate_module('{0}.ext'.format(self.loaded_base_name)) _generate_module('{0}.ext.{1}'.format(self.loaded_base_name, tag)) def __getitem__(self, item): ''' Override the __getitem__ in order to decorate the returned function if we need to last-minute inject globals ''' func = super(LazyLoader, self).__getitem__(item) if self.inject_globals: return global_injector_decorator(self.inject_globals)(func) else: return func def __getattr__(self, mod_name): ''' Allow for "direct" attribute access-- this allows jinja templates to access things like `salt.test.ping()` ''' if mod_name in ('__getstate__', '__setstate__'): return object.__getattribute__(self, mod_name) # if we have an attribute named that, lets return it. try: return object.__getattr__(self, mod_name) # pylint: disable=no-member except AttributeError: pass # otherwise we assume its jinja template access if mod_name not in self.loaded_modules and not self.loaded: for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and mod_name in self.loaded_modules: break if mod_name in self.loaded_modules: return self.loaded_modules[mod_name] else: raise AttributeError(mod_name) def missing_fun_string(self, function_name): ''' Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ''' mod_name = function_name.split('.')[0] if mod_name in self.loaded_modules: return '\'{0}\' is not available.'.format(function_name) else: try: reason = self.missing_modules[mod_name] except KeyError: return '\'{0}\' is not available.'.format(function_name) else: if reason is not None: return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason) else: return '\'{0}\' __virtual__ returned False'.format(mod_name) def _refresh_file_mapping(self): ''' refresh the mapping of the FS on disk ''' # map of suffix to description for imp if self.opts.get('cython_enable', True) is True: try: global pyximport pyximport = __import__('pyximport') # pylint: disable=import-error pyximport.install() # add to suffix_map so file_mapping will pick it up self.suffix_map['.pyx'] = tuple() except ImportError: log.info('Cython is enabled in the options but not present ' 'in the system path. Skipping Cython modules.') # Allow for zipimport of modules if self.opts.get('enable_zip_modules', True) is True: self.suffix_map['.zip'] = tuple() # allow for module dirs if USE_IMPORTLIB: self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY) else: self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY) # create mapping of filename (without suffix) to (path, suffix) # The files are added in order of priority, so order *must* be retained. self.file_mapping = salt.utils.odict.OrderedDict() opt_match = [] def _replace_pre_ext(obj): ''' Hack so we can get the optimization level that we replaced (if any) out of the re.sub call below. We use a list here because it is a persistent data structure that we will be able to access after re.sub is called. ''' opt_match.append(obj) return '' for mod_dir in self.module_dirs: try: # Make sure we have a sorted listdir in order to have # expectable override results files = sorted( x for x in os.listdir(mod_dir) if x != '__pycache__' ) except OSError: continue # Next mod_dir if six.PY3: try: pycache_files = [ os.path.join('__pycache__', x) for x in sorted(os.listdir(os.path.join(mod_dir, '__pycache__'))) ] except OSError: pass else: files.extend(pycache_files) for filename in files: try: dirname, basename = os.path.split(filename) if basename.startswith('_'): # skip private modules # log messages omitted for obviousness continue # Next filename f_noext, ext = os.path.splitext(basename) if six.PY3: f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext) try: opt_level = int( opt_match.pop().group(1).rsplit('-', 1)[-1] ) except (AttributeError, IndexError, ValueError): # No regex match or no optimization level matched opt_level = 0 try: opt_index = self.opts['optimization_order'].index(opt_level) except KeyError: log.trace( 'Disallowed optimization level %d for module ' 'name \'%s\', skipping. Add %d to the ' '\'optimization_order\' config option if you ' 'do not want to ignore this optimization ' 'level.', opt_level, f_noext, opt_level ) continue else: # Optimization level not reflected in filename on PY2 opt_index = 0 # make sure it is a suffix we support if ext not in self.suffix_map: continue # Next filename if f_noext in self.disabled: log.trace( 'Skipping %s, it is disabled by configuration', filename ) continue # Next filename fpath = os.path.join(mod_dir, filename) # if its a directory, lets allow us to load that if ext == '': # is there something __init__? subfiles = os.listdir(fpath) for suffix in self.suffix_order: if '' == suffix: continue # Next suffix (__init__ must have a suffix) init_file = '__init__{0}'.format(suffix) if init_file in subfiles: break else: continue # Next filename try: curr_ext = self.file_mapping[f_noext][1] curr_opt_index = self.file_mapping[f_noext][2] except KeyError: pass else: if '' in (curr_ext, ext) and curr_ext != ext: log.error( 'Module/package collision: \'%s\' and \'%s\'', fpath, self.file_mapping[f_noext][0] ) if six.PY3 and ext == '.pyc' and curr_ext == '.pyc': # Check the optimization level if opt_index >= curr_opt_index: # Module name match, but a higher-priority # optimization level was already matched, skipping. continue elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext): # Match found but a higher-priorty match already # exists, so skip this. continue if six.PY3 and not dirname and ext == '.pyc': # On Python 3, we should only load .pyc files from the # __pycache__ subdirectory (i.e. when dirname is not an # empty string). continue # Made it this far - add it self.file_mapping[f_noext] = (fpath, ext, opt_index) except OSError: continue for smod in self.static_modules: f_noext = smod.split('.')[-1] self.file_mapping[f_noext] = (smod, '.o', 0) def clear(self): ''' Clear the dict ''' with self._lock: super(LazyLoader, self).clear() # clear the lazy loader self.loaded_files = set() self.missing_modules = {} self.loaded_modules = {} # if we have been loaded before, lets clear the file mapping since # we obviously want a re-do if hasattr(self, 'opts'): self._refresh_file_mapping() self.initial_load = False def __prep_mod_opts(self, opts): ''' Strip out of the opts any logger instance ''' if '__grains__' not in self.pack: grains = opts.get('grains', {}) if isinstance(grains, ThreadLocalProxy): grains = ThreadLocalProxy.unproxy(grains) self.context_dict['grains'] = grains self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains') if '__pillar__' not in self.pack: pillar = opts.get('pillar', {}) if isinstance(pillar, ThreadLocalProxy): pillar = ThreadLocalProxy.unproxy(pillar) self.context_dict['pillar'] = pillar self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar') mod_opts = {} for key, val in list(opts.items()): if key == 'logger': continue mod_opts[key] = val return mod_opts def _iter_files(self, mod_name): ''' Iterate over all file_mapping files in order of closeness to mod_name ''' # do we have an exact match? if mod_name in self.file_mapping: yield mod_name # do we have a partial match? for k in self.file_mapping: if mod_name in k: yield k # anyone else? Bueller? for k in self.file_mapping: if mod_name not in k: yield k def _reload_submodules(self, mod): submodules = ( getattr(mod, sname) for sname in dir(mod) if isinstance(getattr(mod, sname), mod.__class__) ) # reload only custom "sub"modules for submodule in submodules: # it is a submodule if the name is in a namespace under mod if submodule.__name__.startswith(mod.__name__ + '.'): reload_module(submodule) self._reload_submodules(submodule) def _load_module(self, name): mod = None fpath, suffix = self.file_mapping[name][:2] self.loaded_files.add(name) fpath_dirname = os.path.dirname(fpath) try: sys.path.append(fpath_dirname) if suffix == '.pyx': mod = pyximport.load_module(name, fpath, tempfile.gettempdir()) elif suffix == '.o': top_mod = __import__(fpath, globals(), locals(), []) comps = fpath.split('.') if len(comps) < 2: mod = top_mod else: mod = top_mod for subname in comps[1:]: mod = getattr(mod, subname) elif suffix == '.zip': mod = zipimporter(fpath).load_module(name) else: desc = self.suffix_map[suffix] # if it is a directory, we don't open a file try: mod_namespace = '.'.join(( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name)) except TypeError: mod_namespace = '{0}.{1}.{2}.{3}'.format( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name) if suffix == '': if USE_IMPORTLIB: # pylint: disable=no-member # Package directory, look for __init__ loader_details = [ (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES), (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES), (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), ] file_finder = importlib.machinery.FileFinder( fpath_dirname, *loader_details ) spec = file_finder.find_spec(mod_namespace) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: mod = imp.load_module(mod_namespace, None, fpath, desc) # reload all submodules if necessary if not self.initial_load: self._reload_submodules(mod) else: if USE_IMPORTLIB: # pylint: disable=no-member loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath) spec = importlib.util.spec_from_file_location( mod_namespace, fpath, loader=loader ) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() #mod = importlib.util.module_from_spec(spec) #spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: with salt.utils.files.fopen(fpath, desc[1]) as fn_: mod = imp.load_module(mod_namespace, fn_, fpath, desc) except IOError: raise except ImportError as exc: if 'magic number' in six.text_type(exc): error_msg = 'Failed to import {0} {1}. Bad magic number. If migrating from Python2 to Python3, remove all .pyc files and try again.'.format(self.tag, name) log.warning(error_msg) self.missing_modules[name] = error_msg log.debug( 'Failed to import %s %s:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = exc return False except Exception as error: log.error( 'Failed to import %s %s, this is due most likely to a ' 'syntax error:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False except SystemExit as error: try: fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1] except Exception: pass else: tgt_fn = os.path.join('salt', 'utils', 'process.py') if fn_.endswith(tgt_fn) and '_handle_signals' in caller: # Race conditon, SIGTERM or SIGINT received while loader # was in process of loading a module. Call sys.exit to # ensure that the process is killed. sys.exit(salt.defaults.exitcodes.EX_OK) log.error( 'Failed to import %s %s as the module called exit()\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False finally: sys.path.remove(fpath_dirname) if hasattr(mod, '__opts__'): mod.__opts__.update(self.opts) else: mod.__opts__ = self.opts # pack whatever other globals we were asked to for p_name, p_value in six.iteritems(self.pack): _inject_into_mod(mod, p_name, p_value) module_name = mod.__name__.rsplit('.', 1)[-1] # Call a module's initialization method if it exists module_init = getattr(mod, '__init__', None) if inspect.isfunction(module_init): try: module_init(self.opts) except TypeError as e: log.error(e) except Exception: err_string = '__init__ failed' log.debug( 'Error loading %s.%s: %s', self.tag, module_name, err_string, exc_info=True ) self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False # if virtual modules are enabled, we need to look for the # __virtual__() function inside that module and run it. if self.virtual_enable: virtual_funcs_to_process = ['__virtual__'] + self.virtual_funcs for virtual_func in virtual_funcs_to_process: virtual_ret, module_name, virtual_err, virtual_aliases = \ self._process_virtual(mod, module_name, virtual_func) if virtual_err is not None: log.trace( 'Error loading %s.%s: %s', self.tag, module_name, virtual_err ) # if _process_virtual returned a non-True value then we are # supposed to not process this module if virtual_ret is not True and module_name not in self.missing_modules: # If a module has information about why it could not be loaded, record it self.missing_modules[module_name] = virtual_err self.missing_modules[name] = virtual_err return False else: virtual_aliases = () # If this is a proxy minion then MOST modules cannot work. Therefore, require that # any module that does work with salt-proxy-minion define __proxyenabled__ as a list # containing the names of the proxy types that the module supports. # # Render modules and state modules are OK though if 'proxy' in self.opts: if self.tag in ['grains', 'proxy']: if not hasattr(mod, '__proxyenabled__') or \ (self.opts['proxy']['proxytype'] not in mod.__proxyenabled__ and '*' not in mod.__proxyenabled__): err_string = 'not a proxy_minion enabled module' self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False if getattr(mod, '__load__', False) is not False: log.info( 'The functions from module \'%s\' are being loaded from the ' 'provided __load__ attribute', module_name ) # If we had another module by the same virtual name, we should put any # new functions under the existing dictionary. mod_names = [module_name] + list(virtual_aliases) mod_dict = dict(( (x, self.loaded_modules.get(x, self.mod_dict_class())) for x in mod_names )) for attr in getattr(mod, '__load__', dir(mod)): if attr.startswith('_') and attr != '__call__': # private functions are skipped, # except __call__ which is default entrance # for multi-function batch-like state syntax continue func = getattr(mod, attr) if not inspect.isfunction(func) and not isinstance(func, functools.partial): # Not a function!? Skip it!!! continue # Let's get the function name. # If the module has the __func_alias__ attribute, it must be a # dictionary mapping in the form of(key -> value): # <real-func-name> -> <desired-func-name> # # It default's of course to the found callable attribute name # if no alias is defined. funcname = getattr(mod, '__func_alias__', {}).get(attr, attr) for tgt_mod in mod_names: try: full_funcname = '.'.join((tgt_mod, funcname)) except TypeError: full_funcname = '{0}.{1}'.format(tgt_mod, funcname) # Save many references for lookups # Careful not to overwrite existing (higher priority) functions if full_funcname not in self._dict: self._dict[full_funcname] = func if funcname not in mod_dict[tgt_mod]: setattr(mod_dict[tgt_mod], funcname, func) mod_dict[tgt_mod][funcname] = func self._apply_outputter(func, mod) # enforce depends try: Depends.enforce_dependencies(self._dict, self.tag) except RuntimeError as exc: log.info( 'Depends.enforce_dependencies() failed for the following ' 'reason: %s', exc ) for tgt_mod in mod_names: self.loaded_modules[tgt_mod] = mod_dict[tgt_mod] return True def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise KeyError('The key \'{0}\' should contain a \'.\''.format(key)) mod_name, _ = key.split('.', 1) with self._lock: # It is possible that the key is in the dictionary after # acquiring the lock due to another thread loading it. if mod_name in self.missing_modules or key in self._dict: return True # if the modulename isn't in the whitelist, don't bother if self.whitelist and mod_name not in self.whitelist: log.error( 'Failed to load function %s because its module (%s) is ' 'not in the whitelist: %s', key, mod_name, self.whitelist ) raise KeyError(key) def _inner_load(mod_name): for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and key in self._dict: return True return False # try to load the module ret = None reloaded = False # re-scan up to once, IOErrors or a failed load cause re-scans of the # filesystem while True: try: ret = _inner_load(mod_name) if not reloaded and ret is not True: self._refresh_file_mapping() reloaded = True continue break except IOError: if not reloaded: self._refresh_file_mapping() reloaded = True continue return ret def _load_all(self): ''' Load all of them ''' with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True def reload_modules(self): with self._lock: self.loaded_files = set() self._load_all() def _apply_outputter(self, func, mod): ''' Apply the __outputter__ variable to the functions ''' if hasattr(mod, '__outputter__'): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__] def _process_virtual(self, mod, module_name, virtual_func='__virtual__'): ''' Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1] ''' # The __virtual__ function will return either a True or False value. # If it returns a True value it can also set a module level attribute # named __virtualname__ with the name that the module should be # referred to as. # # This allows us to have things like the pkg module working on all # platforms under the name 'pkg'. It also allows for modules like # augeas_cfg to be referred to as 'augeas', which would otherwise have # namespace collisions. And finally it allows modules to return False # if they are not intended to run on the given platform or are missing # dependencies. virtual_aliases = getattr(mod, '__virtual_aliases__', tuple()) try: error_reason = None if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__): try: start = time.time() virtual = getattr(mod, virtual_func)() if isinstance(virtual, tuple): error_reason = virtual[1] virtual = virtual[0] if self.opts.get('virtual_timer', False): end = time.time() - start msg = 'Virtual function took {0} seconds for {1}'.format( end, module_name) log.warning(msg) except Exception as exc: error_reason = ( 'Exception raised when processing __virtual__ function' ' for {0}. Module will not be loaded: {1}'.format( mod.__name__, exc)) log.error(error_reason, exc_info_on_loglevel=logging.DEBUG) virtual = None # Get the module's virtual name virtualname = getattr(mod, '__virtualname__', virtual) if not virtual: # if __virtual__() evaluates to False then the module # wasn't meant for this platform or it's not supposed to # load for some other reason. # Some modules might accidentally return None and are # improperly loaded if virtual is None: log.warning( '%s.__virtual__() is wrongly returning `None`. ' 'It should either return `True`, `False` or a new ' 'name. If you\'re the developer of the module ' '\'%s\', please fix this.', mod.__name__, module_name ) return (False, module_name, error_reason, virtual_aliases) # At this point, __virtual__ did not return a # boolean value, let's check for deprecated usage # or module renames if virtual is not True and module_name != virtual: # The module is renaming itself. Updating the module name # with the new name log.trace('Loaded %s as virtual %s', module_name, virtual) if virtualname != virtual: # The __virtualname__ attribute does not match what's # being returned by the __virtual__() function. This # should be considered an error. log.error( 'The module \'%s\' is showing some bad usage. Its ' '__virtualname__ attribute is set to \'%s\' yet the ' '__virtual__() function is returning \'%s\'. These ' 'values should match!', mod.__name__, virtualname, virtual ) module_name = virtualname # If the __virtual__ function returns True and __virtualname__ # is set then use it elif virtual is True and virtualname != module_name: if virtualname is not True: module_name = virtualname except KeyError: # Key errors come out of the virtual function when passing # in incomplete grains sets, these can be safely ignored # and logged to debug, still, it includes the traceback to # help debugging. log.debug('KeyError when loading %s', module_name, exc_info=True) except Exception: # If the module throws an exception during __virtual__() # then log the information and continue to the next. log.error( 'Failed to read the virtual function for %s: %s', self.tag, module_name, exc_info=True ) return (False, module_name, error_reason, virtual_aliases) return (True, module_name, None, virtual_aliases) def global_injector_decorator(inject_globals): ''' Decorator used by the LazyLoader to inject globals into a function at execute time. globals Dictionary with global variables to inject ''' def inner_decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): with salt.utils.context.func_globals_inject(f, **inject_globals): return f(*args, **kwargs) return wrapper return inner_decorator
saltstack/salt
salt/loader.py
clouds
python
def clouds(opts): ''' Return the cloud functions ''' # Let's bring __active_provider_name__, defaulting to None, to all cloud # drivers. This will get temporarily updated/overridden with a context # manager when needed. functions = LazyLoader( _module_dirs(opts, 'clouds', 'cloud', base_path=os.path.join(SALT_BASE_PATH, 'cloud'), int_type='clouds'), opts, tag='clouds', pack={'__utils__': salt.loader.utils(opts), '__active_provider_name__': None}, ) for funcname in LIBCLOUD_FUNCS_NOT_SUPPORTED: log.trace( '\'%s\' has been marked as not supported. Removing from the ' 'list of supported cloud functions', funcname ) functions.pop(funcname, None) return functions
Return the cloud functions
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L1015-L1039
null
# -*- coding: utf-8 -*- ''' The Salt loader is the core to Salt's plugin system, the loader scans directories for python loadable code and organizes the code into the plugin interfaces used by Salt. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import sys import time import logging import inspect import tempfile import threading import functools import threading import traceback import types from zipimport import zipimporter # Import salt libs import salt.config import salt.defaults.events import salt.defaults.exitcodes import salt.syspaths import salt.utils.args import salt.utils.context import salt.utils.data import salt.utils.dictupdate import salt.utils.event import salt.utils.files import salt.utils.lazy import salt.utils.odict import salt.utils.platform import salt.utils.versions import salt.utils.stringutils from salt.exceptions import LoaderError from salt.template import check_render_pipe_str from salt.utils.decorators import Depends from salt.utils.thread_local_proxy import ThreadLocalProxy # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import reload_module if sys.version_info[:2] >= (3, 5): import importlib.machinery # pylint: disable=no-name-in-module,import-error import importlib.util # pylint: disable=no-name-in-module,import-error USE_IMPORTLIB = True else: import imp USE_IMPORTLIB = False try: from collections.abc import MutableMapping except ImportError: from collections import MutableMapping try: import pkg_resources HAS_PKG_RESOURCES = True except ImportError: HAS_PKG_RESOURCES = False log = logging.getLogger(__name__) SALT_BASE_PATH = os.path.abspath(salt.syspaths.INSTALL_DIR) LOADED_BASE_NAME = 'salt.loaded' if USE_IMPORTLIB: # pylint: disable=no-member MODULE_KIND_SOURCE = 1 MODULE_KIND_COMPILED = 2 MODULE_KIND_EXTENSION = 3 MODULE_KIND_PKG_DIRECTORY = 5 SUFFIXES = [] for suffix in importlib.machinery.EXTENSION_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_EXTENSION)) for suffix in importlib.machinery.SOURCE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_SOURCE)) for suffix in importlib.machinery.BYTECODE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_COMPILED)) MODULE_KIND_MAP = { MODULE_KIND_SOURCE: importlib.machinery.SourceFileLoader, MODULE_KIND_COMPILED: importlib.machinery.SourcelessFileLoader, MODULE_KIND_EXTENSION: importlib.machinery.ExtensionFileLoader } # pylint: enable=no-member else: SUFFIXES = imp.get_suffixes() PY3_PRE_EXT = \ re.compile(r'\.cpython-{0}{1}(\.opt-[1-9])?'.format(*sys.version_info[:2])) # Because on the cloud drivers we do `from salt.cloud.libcloudfuncs import *` # which simplifies code readability, it adds some unsupported functions into # the driver's module scope. # We list un-supported functions here. These will be removed from the loaded. # TODO: remove the need for this cross-module code. Maybe use NotImplemented LIBCLOUD_FUNCS_NOT_SUPPORTED = ( 'parallels.avail_sizes', 'parallels.avail_locations', 'proxmox.avail_sizes', ) # Will be set to pyximport module at runtime if cython is enabled in config. pyximport = None def static_loader( opts, ext_type, tag, pack=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, filter_name=None, ): funcs = LazyLoader( _module_dirs( opts, ext_type, tag, int_type, ext_dirs, ext_type_dirs, base_path, ), opts, tag=tag, pack=pack, ) ret = {} funcs._load_all() if filter_name: funcs = FilterDictWrapper(funcs, filter_name) for key in funcs: ret[key] = funcs[key] return ret def _format_entrypoint_target(ep): ''' Makes a string describing the target of an EntryPoint object. Base strongly on EntryPoint.__str__(). ''' s = ep.module_name if ep.attrs: s += ':' + '.'.join(ep.attrs) return s def _module_dirs( opts, ext_type, tag=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, ): if tag is None: tag = ext_type sys_types = os.path.join(base_path or SALT_BASE_PATH, int_type or ext_type) ext_types = os.path.join(opts['extension_modules'], ext_type) ext_type_types = [] if ext_dirs: if ext_type_dirs is None: ext_type_dirs = '{0}_dirs'.format(tag) if ext_type_dirs in opts: ext_type_types.extend(opts[ext_type_dirs]) if HAS_PKG_RESOURCES and ext_type_dirs: for entry_point in pkg_resources.iter_entry_points('salt.loader', ext_type_dirs): try: loaded_entry_point = entry_point.load() for path in loaded_entry_point(): ext_type_types.append(path) except Exception as exc: log.error("Error getting module directories from %s: %s", _format_entrypoint_target(entry_point), exc) log.debug("Full backtrace for module directories error", exc_info=True) cli_module_dirs = [] # The dirs can be any module dir, or a in-tree _{ext_type} dir for _dir in opts.get('module_dirs', []): # Prepend to the list to match cli argument ordering maybe_dir = os.path.join(_dir, ext_type) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) continue maybe_dir = os.path.join(_dir, '_{0}'.format(ext_type)) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) return cli_module_dirs + ext_type_types + [ext_types, sys_types] def minion_mods( opts, context=None, utils=None, whitelist=None, initial_load=False, loaded_base_name=None, notify=False, static_modules=None, proxy=None): ''' Load execution modules Returns a dictionary of execution modules appropriate for the current system by evaluating the __virtual__() function in each module. :param dict opts: The Salt options dictionary :param dict context: A Salt context that should be made present inside generated modules in __context__ :param dict utils: Utility functions which should be made available to Salt modules in __utils__. See `utils_dirs` in salt.config for additional information about configuration. :param list whitelist: A list of modules which should be whitelisted. :param bool initial_load: Deprecated flag! Unused. :param str loaded_base_name: A string marker for the loaded base name. :param bool notify: Flag indicating that an event should be fired upon completion of module loading. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) __opts__['grains'] = __grains__ __utils__ = salt.loader.utils(__opts__) __salt__ = salt.loader.minion_mods(__opts__, utils=__utils__) __salt__['test.ping']() ''' # TODO Publish documentation for module whitelisting if not whitelist: whitelist = opts.get('whitelist_modules', None) ret = LazyLoader( _module_dirs(opts, 'modules', 'module'), opts, tag='module', pack={'__context__': context, '__utils__': utils, '__proxy__': proxy}, whitelist=whitelist, loaded_base_name=loaded_base_name, static_modules=static_modules, ) ret.pack['__salt__'] = ret # Load any provider overrides from the configuration file providers option # Note: Providers can be pkg, service, user or group - not to be confused # with cloud providers. providers = opts.get('providers', False) if providers and isinstance(providers, dict): for mod in providers: # sometimes providers opts is not to diverge modules but # for other configuration try: funcs = raw_mod(opts, providers[mod], ret) except TypeError: break else: if funcs: for func in funcs: f_key = '{0}{1}'.format(mod, func[func.rindex('.'):]) ret[f_key] = funcs[func] if notify: evt = salt.utils.event.get_event('minion', opts=opts, listen=False) evt.fire_event({'complete': True}, tag=salt.defaults.events.MINION_MOD_COMPLETE) return ret def raw_mod(opts, name, functions, mod='modules'): ''' Returns a single module loaded raw and bypassing the __virtual__ function .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') testmod = salt.loader.raw_mod(__opts__, 'test', None) testmod['test.ping']() ''' loader = LazyLoader( _module_dirs(opts, mod, 'module'), opts, tag='rawmodule', virtual_enable=False, pack={'__salt__': functions}, ) # if we don't have the module, return an empty dict if name not in loader.file_mapping: return {} loader._load_module(name) # load a single module (the one passed in) return dict(loader._dict) # return a copy of *just* the funcs for `name` def metaproxy(opts): ''' Return functions used in the meta proxy ''' return LazyLoader( _module_dirs(opts, 'metaproxy'), opts, tag='metaproxy' ) def matchers(opts): ''' Return the matcher services plugins ''' return LazyLoader( _module_dirs(opts, 'matchers'), opts, tag='matchers' ) def engines(opts, functions, runners, utils, proxy=None): ''' Return the master services plugins ''' pack = {'__salt__': functions, '__runners__': runners, '__proxy__': proxy, '__utils__': utils} return LazyLoader( _module_dirs(opts, 'engines'), opts, tag='engines', pack=pack, ) def proxy(opts, functions=None, returners=None, whitelist=None, utils=None): ''' Returns the proxy module for this salt-proxy-minion ''' ret = LazyLoader( _module_dirs(opts, 'proxy'), opts, tag='proxy', pack={'__salt__': functions, '__ret__': returners, '__utils__': utils}, ) ret.pack['__proxy__'] = ret return ret def returners(opts, functions, whitelist=None, context=None, proxy=None): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'returners', 'returner'), opts, tag='returner', whitelist=whitelist, pack={'__salt__': functions, '__context__': context, '__proxy__': proxy or {}}, ) def utils(opts, whitelist=None, context=None, proxy=proxy): ''' Returns the utility modules ''' return LazyLoader( _module_dirs(opts, 'utils', ext_type_dirs='utils_dirs'), opts, tag='utils', whitelist=whitelist, pack={'__context__': context, '__proxy__': proxy or {}}, ) def pillars(opts, functions, context=None): ''' Returns the pillars modules ''' ret = LazyLoader(_module_dirs(opts, 'pillar'), opts, tag='pillar', pack={'__salt__': functions, '__context__': context, '__utils__': utils(opts)}) ret.pack['__ext_pillar__'] = ret return FilterDictWrapper(ret, '.ext_pillar') def tops(opts): ''' Returns the tops modules ''' if 'master_tops' not in opts: return {} whitelist = list(opts['master_tops'].keys()) ret = LazyLoader( _module_dirs(opts, 'tops', 'top'), opts, tag='top', whitelist=whitelist, ) return FilterDictWrapper(ret, '.top') def wheels(opts, whitelist=None, context=None): ''' Returns the wheels modules ''' if context is None: context = {} return LazyLoader( _module_dirs(opts, 'wheel'), opts, tag='wheel', whitelist=whitelist, pack={'__context__': context}, ) def outputters(opts): ''' Returns the outputters modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only outputters present in the keyspace ''' ret = LazyLoader( _module_dirs(opts, 'output', ext_type_dirs='outputter_dirs'), opts, tag='output', ) wrapped_ret = FilterDictWrapper(ret, '.output') # TODO: this name seems terrible... __salt__ should always be execution mods ret.pack['__salt__'] = wrapped_ret return wrapped_ret def serializers(opts): ''' Returns the serializers modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only serializers present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'serializers'), opts, tag='serializers', ) def eauth_tokens(opts): ''' Returns the tokens modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only token backends present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'tokens'), opts, tag='tokens', ) def auth(opts, whitelist=None): ''' Returns the auth modules :param dict opts: The Salt options dictionary :returns: LazyLoader ''' return LazyLoader( _module_dirs(opts, 'auth'), opts, tag='auth', whitelist=whitelist, pack={'__salt__': minion_mods(opts)}, ) def fileserver(opts, backends): ''' Returns the file server modules ''' return LazyLoader(_module_dirs(opts, 'fileserver'), opts, tag='fileserver', whitelist=backends, pack={'__utils__': utils(opts)}) def roster(opts, runner=None, utils=None, whitelist=None): ''' Returns the roster modules ''' return LazyLoader( _module_dirs(opts, 'roster'), opts, tag='roster', whitelist=whitelist, pack={ '__runner__': runner, '__utils__': utils, }, ) def thorium(opts, functions, runners): ''' Load the thorium runtime modules ''' pack = {'__salt__': functions, '__runner__': runners, '__context__': {}} ret = LazyLoader(_module_dirs(opts, 'thorium'), opts, tag='thorium', pack=pack) ret.pack['__thorium__'] = ret return ret def states(opts, functions, utils, serializers, whitelist=None, proxy=None, context=None): ''' Returns the state modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') statemods = salt.loader.states(__opts__, None, None) ''' if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'states'), opts, tag='states', pack={'__salt__': functions, '__proxy__': proxy or {}}, whitelist=whitelist, ) ret.pack['__states__'] = ret ret.pack['__utils__'] = utils ret.pack['__serializers__'] = serializers ret.pack['__context__'] = context return ret def beacons(opts, functions, context=None, proxy=None): ''' Load the beacon modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. ''' return LazyLoader( _module_dirs(opts, 'beacons'), opts, tag='beacons', pack={'__context__': context, '__salt__': functions, '__proxy__': proxy or {}}, virtual_funcs=[], ) def log_handlers(opts): ''' Returns the custom logging handler modules :param dict opts: The Salt options dictionary ''' ret = LazyLoader( _module_dirs( opts, 'log_handlers', int_type='handlers', base_path=os.path.join(SALT_BASE_PATH, 'log'), ), opts, tag='log_handlers', ) return FilterDictWrapper(ret, '.setup_handlers') def ssh_wrapper(opts, functions=None, context=None): ''' Returns the custom logging handler modules ''' return LazyLoader( _module_dirs( opts, 'wrapper', base_path=os.path.join(SALT_BASE_PATH, os.path.join('client', 'ssh')), ), opts, tag='wrapper', pack={ '__salt__': functions, '__grains__': opts.get('grains', {}), '__pillar__': opts.get('pillar', {}), '__context__': context, }, ) def render(opts, functions, states=None, proxy=None, context=None): ''' Returns the render modules ''' if context is None: context = {} pack = {'__salt__': functions, '__grains__': opts.get('grains', {}), '__context__': context} if states: pack['__states__'] = states pack['__proxy__'] = proxy or {} ret = LazyLoader( _module_dirs( opts, 'renderers', 'render', ext_type_dirs='render_dirs', ), opts, tag='render', pack=pack, ) rend = FilterDictWrapper(ret, '.render') if not check_render_pipe_str(opts['renderer'], rend, opts['renderer_blacklist'], opts['renderer_whitelist']): err = ('The renderer {0} is unavailable, this error is often because ' 'the needed software is unavailable'.format(opts['renderer'])) log.critical(err) raise LoaderError(err) return rend def grain_funcs(opts, proxy=None): ''' Returns the grain functions .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') grainfuncs = salt.loader.grain_funcs(__opts__) ''' ret = LazyLoader( _module_dirs( opts, 'grains', 'grain', ext_type_dirs='grains_dirs', ), opts, tag='grains', ) ret.pack['__utils__'] = utils(opts, proxy=proxy) return ret def _load_cached_grains(opts, cfn): ''' Returns the grains cached in cfn, or None if the cache is too old or is corrupted. ''' if not os.path.isfile(cfn): log.debug('Grains cache file does not exist.') return None grains_cache_age = int(time.time() - os.path.getmtime(cfn)) if grains_cache_age > opts.get('grains_cache_expiration', 300): log.debug( 'Grains cache last modified %s seconds ago and cache ' 'expiration is set to %s. Grains cache expired. ' 'Refreshing.', grains_cache_age, opts.get('grains_cache_expiration', 300) ) return None if opts.get('refresh_grains_cache', False): log.debug('refresh_grains_cache requested, Refreshing.') return None log.debug('Retrieving grains from cache') try: serial = salt.payload.Serial(opts) with salt.utils.files.fopen(cfn, 'rb') as fp_: cached_grains = salt.utils.data.decode(serial.load(fp_), preserve_tuples=True) if not cached_grains: log.debug('Cached grains are empty, cache might be corrupted. Refreshing.') return None return cached_grains except (IOError, OSError): return None def grains(opts, force_refresh=False, proxy=None): ''' Return the functions for the dynamic grains and the values for the static grains. Since grains are computed early in the startup process, grains functions do not have __salt__ or __proxy__ available. At proxy-minion startup, this function is called with the proxymodule LazyLoader object so grains functions can communicate with their controlled device. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) print __grains__['id'] ''' # Need to re-import salt.config, somehow it got lost when a minion is starting import salt.config # if we have no grains, lets try loading from disk (TODO: move to decorator?) cfn = os.path.join( opts['cachedir'], 'grains.cache.p' ) if not force_refresh and opts.get('grains_cache', False): cached_grains = _load_cached_grains(opts, cfn) if cached_grains: return cached_grains else: log.debug('Grains refresh requested. Refreshing grains.') if opts.get('skip_grains', False): return {} grains_deep_merge = opts.get('grains_deep_merge', False) is True if 'conf_file' in opts: pre_opts = {} pre_opts.update(salt.config.load_config( opts['conf_file'], 'SALT_MINION_CONFIG', salt.config.DEFAULT_MINION_OPTS['conf_file'] )) default_include = pre_opts.get( 'default_include', opts['default_include'] ) include = pre_opts.get('include', []) pre_opts.update(salt.config.include_config( default_include, opts['conf_file'], verbose=False )) pre_opts.update(salt.config.include_config( include, opts['conf_file'], verbose=True )) if 'grains' in pre_opts: opts['grains'] = pre_opts['grains'] else: opts['grains'] = {} else: opts['grains'] = {} grains_data = {} blist = opts.get('grains_blacklist', []) funcs = grain_funcs(opts, proxy=proxy) if force_refresh: # if we refresh, lets reload grain modules funcs.clear() # Run core grains for key in funcs: if not key.startswith('core.'): continue log.trace('Loading %s grain', key) ret = funcs[key]() if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) # Run the rest of the grains for key in funcs: if key.startswith('core.') or key == '_errors': continue try: # Grains are loaded too early to take advantage of the injected # __proxy__ variable. Pass an instance of that LazyLoader # here instead to grains functions if the grains functions take # one parameter. Then the grains can have access to the # proxymodule for retrieving information from the connected # device. log.trace('Loading %s grain', key) parameters = salt.utils.args.get_function_argspec(funcs[key]).args kwargs = {} if 'proxy' in parameters: kwargs['proxy'] = proxy if 'grains' in parameters: kwargs['grains'] = grains_data ret = funcs[key](**kwargs) except Exception: if salt.utils.platform.is_proxy(): log.info('The following CRITICAL message may not be an error; the proxy may not be completely established yet.') log.critical( 'Failed to load grains defined in grain file %s in ' 'function %s, error:\n', key, funcs[key], exc_info=True ) continue if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) if opts.get('proxy_merge_grains_in_module', True) and proxy: try: proxytype = proxy.opts['proxy']['proxytype'] if proxytype + '.grains' in proxy: if proxytype + '.initialized' in proxy and proxy[proxytype + '.initialized'](): try: proxytype = proxy.opts['proxy']['proxytype'] ret = proxy[proxytype + '.grains']() if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) except Exception: log.critical('Failed to run proxy\'s grains function!', exc_info=True ) except KeyError: pass grains_data.update(opts['grains']) # Write cache if enabled if opts.get('grains_cache', False): with salt.utils.files.set_umask(0o077): try: if salt.utils.platform.is_windows(): # Late import import salt.modules.cmdmod # Make sure cache file isn't read-only salt.modules.cmdmod._run_quiet('attrib -R "{0}"'.format(cfn)) with salt.utils.files.fopen(cfn, 'w+b') as fp_: try: serial = salt.payload.Serial(opts) serial.dump(grains_data, fp_) except TypeError as e: log.error('Failed to serialize grains cache: %s', e) raise # re-throw for cleanup except Exception as e: log.error('Unable to write to grains cache file %s: %s', cfn, e) # Based on the original exception, the file may or may not have been # created. If it was, we will remove it now, as the exception means # the serialized data is not to be trusted, no matter what the # exception is. if os.path.isfile(cfn): os.unlink(cfn) if grains_deep_merge: salt.utils.dictupdate.update(grains_data, opts['grains']) else: grains_data.update(opts['grains']) return salt.utils.data.decode(grains_data, preserve_tuples=True) # TODO: get rid of? Does anyone use this? You should use raw() instead def call(fun, **kwargs): ''' Directly call a function inside a loader directory ''' args = kwargs.get('args', []) dirs = kwargs.get('dirs', []) funcs = LazyLoader( [os.path.join(SALT_BASE_PATH, 'modules')] + dirs, None, tag='modules', virtual_enable=False, ) return funcs[fun](*args) def runner(opts, utils=None, context=None, whitelist=None): ''' Directly call a function inside a loader directory ''' if utils is None: utils = {} if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'runners', 'runner', ext_type_dirs='runner_dirs'), opts, tag='runners', pack={'__utils__': utils, '__context__': context}, whitelist=whitelist, ) # TODO: change from __salt__ to something else, we overload __salt__ too much ret.pack['__salt__'] = ret return ret def queues(opts): ''' Directly call a function inside a loader directory ''' return LazyLoader( _module_dirs(opts, 'queues', 'queue', ext_type_dirs='queue_dirs'), opts, tag='queues', ) def sdb(opts, functions=None, whitelist=None, utils=None): ''' Make a very small database call ''' if utils is None: utils = {} return LazyLoader( _module_dirs(opts, 'sdb'), opts, tag='sdb', pack={ '__sdb__': functions, '__opts__': opts, '__utils__': utils, '__salt__': minion_mods(opts, utils), }, whitelist=whitelist, ) def pkgdb(opts): ''' Return modules for SPM's package database .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgdb', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgdb' ) def pkgfiles(opts): ''' Return modules for SPM's file handling .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgfiles', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgfiles' ) def netapi(opts): ''' Return the network api functions ''' return LazyLoader( _module_dirs(opts, 'netapi'), opts, tag='netapi', ) def executors(opts, functions=None, context=None, proxy=None): ''' Returns the executor modules ''' executors = LazyLoader( _module_dirs(opts, 'executors', 'executor'), opts, tag='executor', pack={'__salt__': functions, '__context__': context or {}, '__proxy__': proxy or {}}, ) executors.pack['__executors__'] = executors return executors def cache(opts, serial): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'cache', 'cache'), opts, tag='cache', pack={'__opts__': opts, '__context__': {'serial': serial}}, ) def _generate_module(name): if name in sys.modules: return code = "'''Salt loaded {0} parent module'''".format(name.split('.')[-1]) # ModuleType can't accept a unicode type on PY2 module = types.ModuleType(str(name)) # future lint: disable=blacklisted-function exec(code, module.__dict__) sys.modules[name] = module def _mod_type(module_path): if module_path.startswith(SALT_BASE_PATH): return 'int' return 'ext' def _inject_into_mod(mod, name, value, force_lock=False): ''' Inject a variable into a module. This is used to inject "globals" like ``__salt__``, ``__pillar``, or ``grains``. Instead of injecting the value directly, a ``ThreadLocalProxy`` is created. If such a proxy is already present under the specified name, it is updated with the new value. This update only affects the current thread, so that the same name can refer to different values depending on the thread of execution. This is important for data that is not truly global. For example, pillar data might be dynamically overriden through function parameters and thus the actual values available in pillar might depend on the thread that is calling a module. mod: module object into which the value is going to be injected. name: name of the variable that is injected into the module. value: value that is injected into the variable. The value is not injected directly, but instead set as the new reference of the proxy that has been created for the variable. force_lock: whether the lock should be acquired before checking whether a proxy object for the specified name has already been injected into the module. If ``False`` (the default), this function checks for the module's variable without acquiring the lock and only acquires the lock if a new proxy has to be created and injected. ''' old_value = getattr(mod, name, None) # We use a double-checked locking scheme in order to avoid taking the lock # when a proxy object has already been injected. # In most programming languages, double-checked locking is considered # unsafe when used without explicit memory barriers because one might read # an uninitialized value. In CPython it is safe due to the global # interpreter lock (GIL). In Python implementations that do not have the # GIL, it could be unsafe, but at least Jython also guarantees that (for # Python objects) memory is not corrupted when writing and reading without # explicit synchronization # (http://www.jython.org/jythonbook/en/1.0/Concurrency.html). # Please note that in order to make this code safe in a runtime environment # that does not make this guarantees, it is not sufficient. The # ThreadLocalProxy must also be created with fallback_to_shared set to # False or a lock must be added to the ThreadLocalProxy. if force_lock: with _inject_into_mod.lock: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: setattr(mod, name, ThreadLocalProxy(value, True)) else: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: _inject_into_mod(mod, name, value, True) # Lock used when injecting globals. This is needed to avoid a race condition # when two threads try to load the same module concurrently. This must be # outside the loader because there might be more than one loader for the same # namespace. _inject_into_mod.lock = threading.RLock() # TODO: move somewhere else? class FilterDictWrapper(MutableMapping): ''' Create a dict which wraps another dict with a specific key suffix on get This is to replace "filter_load" ''' def __init__(self, d, suffix): self._dict = d self.suffix = suffix def __setitem__(self, key, val): self._dict[key] = val def __delitem__(self, key): del self._dict[key] def __getitem__(self, key): return self._dict[key + self.suffix] def __len__(self): return len(self._dict) def __iter__(self): for key in self._dict: if key.endswith(self.suffix): yield key.replace(self.suffix, '') class LazyLoader(salt.utils.lazy.LazyDict): ''' A pseduo-dictionary which has a set of keys which are the name of the module and function, delimited by a dot. When the value of the key is accessed, the function is then loaded from disk and into memory. .. note:: Iterating over keys will cause all modules to be loaded. :param list module_dirs: A list of directories on disk to search for modules :param dict opts: The salt options dictionary. :param str tag: The tag for the type of module to load :param func mod_type_check: A function which can be used to verify files :param dict pack: A dictionary of function to be packed into modules as they are loaded :param list whitelist: A list of modules to whitelist :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules. :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality. If not true, the module will not load. :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values are function references themselves which are loaded on-demand. # TODO: - move modules_max_memory into here - singletons (per tag) ''' mod_dict_class = salt.utils.odict.OrderedDict def __init__(self, module_dirs, opts=None, tag='module', loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, proxy=None, virtual_funcs=None, ): # pylint: disable=W0231 ''' In pack, if any of the values are None they will be replaced with an empty context-specific dict ''' self.inject_globals = {} self.pack = {} if pack is None else pack if opts is None: opts = {} threadsafety = not opts.get('multiprocessing') self.context_dict = salt.utils.context.ContextDict(threadsafe=threadsafety) self.opts = self.__prep_mod_opts(opts) self.module_dirs = module_dirs self.tag = tag self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME self.mod_type_check = mod_type_check or _mod_type if '__context__' not in self.pack: self.pack['__context__'] = None for k, v in six.iteritems(self.pack): if v is None: # if the value of a pack is None, lets make an empty dict value = self.context_dict.get(k, {}) if isinstance(value, ThreadLocalProxy): value = ThreadLocalProxy.unproxy(value) self.context_dict[k] = value self.pack[k] = salt.utils.context.NamespacedDictWrapper(self.context_dict, k) self.whitelist = whitelist self.virtual_enable = virtual_enable self.initial_load = True # names of modules that we don't have (errors, __virtual__, etc.) self.missing_modules = {} # mapping of name -> error self.loaded_modules = {} # mapping of module_name -> dict_of_functions self.loaded_files = set() # TODO: just remove them from file_mapping? self.static_modules = static_modules if static_modules else [] if virtual_funcs is None: virtual_funcs = [] self.virtual_funcs = virtual_funcs self.disabled = set( self.opts.get( 'disable_{0}{1}'.format( self.tag, '' if self.tag[-1] == 's' else 's' ), [] ) ) # A map of suffix to description for imp self.suffix_map = {} # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [''] for (suffix, mode, kind) in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) self._lock = threading.RLock() self._refresh_file_mapping() super(LazyLoader, self).__init__() # late init the lazy loader # create all of the import namespaces _generate_module('{0}.int'.format(self.loaded_base_name)) _generate_module('{0}.int.{1}'.format(self.loaded_base_name, tag)) _generate_module('{0}.ext'.format(self.loaded_base_name)) _generate_module('{0}.ext.{1}'.format(self.loaded_base_name, tag)) def __getitem__(self, item): ''' Override the __getitem__ in order to decorate the returned function if we need to last-minute inject globals ''' func = super(LazyLoader, self).__getitem__(item) if self.inject_globals: return global_injector_decorator(self.inject_globals)(func) else: return func def __getattr__(self, mod_name): ''' Allow for "direct" attribute access-- this allows jinja templates to access things like `salt.test.ping()` ''' if mod_name in ('__getstate__', '__setstate__'): return object.__getattribute__(self, mod_name) # if we have an attribute named that, lets return it. try: return object.__getattr__(self, mod_name) # pylint: disable=no-member except AttributeError: pass # otherwise we assume its jinja template access if mod_name not in self.loaded_modules and not self.loaded: for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and mod_name in self.loaded_modules: break if mod_name in self.loaded_modules: return self.loaded_modules[mod_name] else: raise AttributeError(mod_name) def missing_fun_string(self, function_name): ''' Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ''' mod_name = function_name.split('.')[0] if mod_name in self.loaded_modules: return '\'{0}\' is not available.'.format(function_name) else: try: reason = self.missing_modules[mod_name] except KeyError: return '\'{0}\' is not available.'.format(function_name) else: if reason is not None: return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason) else: return '\'{0}\' __virtual__ returned False'.format(mod_name) def _refresh_file_mapping(self): ''' refresh the mapping of the FS on disk ''' # map of suffix to description for imp if self.opts.get('cython_enable', True) is True: try: global pyximport pyximport = __import__('pyximport') # pylint: disable=import-error pyximport.install() # add to suffix_map so file_mapping will pick it up self.suffix_map['.pyx'] = tuple() except ImportError: log.info('Cython is enabled in the options but not present ' 'in the system path. Skipping Cython modules.') # Allow for zipimport of modules if self.opts.get('enable_zip_modules', True) is True: self.suffix_map['.zip'] = tuple() # allow for module dirs if USE_IMPORTLIB: self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY) else: self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY) # create mapping of filename (without suffix) to (path, suffix) # The files are added in order of priority, so order *must* be retained. self.file_mapping = salt.utils.odict.OrderedDict() opt_match = [] def _replace_pre_ext(obj): ''' Hack so we can get the optimization level that we replaced (if any) out of the re.sub call below. We use a list here because it is a persistent data structure that we will be able to access after re.sub is called. ''' opt_match.append(obj) return '' for mod_dir in self.module_dirs: try: # Make sure we have a sorted listdir in order to have # expectable override results files = sorted( x for x in os.listdir(mod_dir) if x != '__pycache__' ) except OSError: continue # Next mod_dir if six.PY3: try: pycache_files = [ os.path.join('__pycache__', x) for x in sorted(os.listdir(os.path.join(mod_dir, '__pycache__'))) ] except OSError: pass else: files.extend(pycache_files) for filename in files: try: dirname, basename = os.path.split(filename) if basename.startswith('_'): # skip private modules # log messages omitted for obviousness continue # Next filename f_noext, ext = os.path.splitext(basename) if six.PY3: f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext) try: opt_level = int( opt_match.pop().group(1).rsplit('-', 1)[-1] ) except (AttributeError, IndexError, ValueError): # No regex match or no optimization level matched opt_level = 0 try: opt_index = self.opts['optimization_order'].index(opt_level) except KeyError: log.trace( 'Disallowed optimization level %d for module ' 'name \'%s\', skipping. Add %d to the ' '\'optimization_order\' config option if you ' 'do not want to ignore this optimization ' 'level.', opt_level, f_noext, opt_level ) continue else: # Optimization level not reflected in filename on PY2 opt_index = 0 # make sure it is a suffix we support if ext not in self.suffix_map: continue # Next filename if f_noext in self.disabled: log.trace( 'Skipping %s, it is disabled by configuration', filename ) continue # Next filename fpath = os.path.join(mod_dir, filename) # if its a directory, lets allow us to load that if ext == '': # is there something __init__? subfiles = os.listdir(fpath) for suffix in self.suffix_order: if '' == suffix: continue # Next suffix (__init__ must have a suffix) init_file = '__init__{0}'.format(suffix) if init_file in subfiles: break else: continue # Next filename try: curr_ext = self.file_mapping[f_noext][1] curr_opt_index = self.file_mapping[f_noext][2] except KeyError: pass else: if '' in (curr_ext, ext) and curr_ext != ext: log.error( 'Module/package collision: \'%s\' and \'%s\'', fpath, self.file_mapping[f_noext][0] ) if six.PY3 and ext == '.pyc' and curr_ext == '.pyc': # Check the optimization level if opt_index >= curr_opt_index: # Module name match, but a higher-priority # optimization level was already matched, skipping. continue elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext): # Match found but a higher-priorty match already # exists, so skip this. continue if six.PY3 and not dirname and ext == '.pyc': # On Python 3, we should only load .pyc files from the # __pycache__ subdirectory (i.e. when dirname is not an # empty string). continue # Made it this far - add it self.file_mapping[f_noext] = (fpath, ext, opt_index) except OSError: continue for smod in self.static_modules: f_noext = smod.split('.')[-1] self.file_mapping[f_noext] = (smod, '.o', 0) def clear(self): ''' Clear the dict ''' with self._lock: super(LazyLoader, self).clear() # clear the lazy loader self.loaded_files = set() self.missing_modules = {} self.loaded_modules = {} # if we have been loaded before, lets clear the file mapping since # we obviously want a re-do if hasattr(self, 'opts'): self._refresh_file_mapping() self.initial_load = False def __prep_mod_opts(self, opts): ''' Strip out of the opts any logger instance ''' if '__grains__' not in self.pack: grains = opts.get('grains', {}) if isinstance(grains, ThreadLocalProxy): grains = ThreadLocalProxy.unproxy(grains) self.context_dict['grains'] = grains self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains') if '__pillar__' not in self.pack: pillar = opts.get('pillar', {}) if isinstance(pillar, ThreadLocalProxy): pillar = ThreadLocalProxy.unproxy(pillar) self.context_dict['pillar'] = pillar self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar') mod_opts = {} for key, val in list(opts.items()): if key == 'logger': continue mod_opts[key] = val return mod_opts def _iter_files(self, mod_name): ''' Iterate over all file_mapping files in order of closeness to mod_name ''' # do we have an exact match? if mod_name in self.file_mapping: yield mod_name # do we have a partial match? for k in self.file_mapping: if mod_name in k: yield k # anyone else? Bueller? for k in self.file_mapping: if mod_name not in k: yield k def _reload_submodules(self, mod): submodules = ( getattr(mod, sname) for sname in dir(mod) if isinstance(getattr(mod, sname), mod.__class__) ) # reload only custom "sub"modules for submodule in submodules: # it is a submodule if the name is in a namespace under mod if submodule.__name__.startswith(mod.__name__ + '.'): reload_module(submodule) self._reload_submodules(submodule) def _load_module(self, name): mod = None fpath, suffix = self.file_mapping[name][:2] self.loaded_files.add(name) fpath_dirname = os.path.dirname(fpath) try: sys.path.append(fpath_dirname) if suffix == '.pyx': mod = pyximport.load_module(name, fpath, tempfile.gettempdir()) elif suffix == '.o': top_mod = __import__(fpath, globals(), locals(), []) comps = fpath.split('.') if len(comps) < 2: mod = top_mod else: mod = top_mod for subname in comps[1:]: mod = getattr(mod, subname) elif suffix == '.zip': mod = zipimporter(fpath).load_module(name) else: desc = self.suffix_map[suffix] # if it is a directory, we don't open a file try: mod_namespace = '.'.join(( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name)) except TypeError: mod_namespace = '{0}.{1}.{2}.{3}'.format( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name) if suffix == '': if USE_IMPORTLIB: # pylint: disable=no-member # Package directory, look for __init__ loader_details = [ (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES), (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES), (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), ] file_finder = importlib.machinery.FileFinder( fpath_dirname, *loader_details ) spec = file_finder.find_spec(mod_namespace) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: mod = imp.load_module(mod_namespace, None, fpath, desc) # reload all submodules if necessary if not self.initial_load: self._reload_submodules(mod) else: if USE_IMPORTLIB: # pylint: disable=no-member loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath) spec = importlib.util.spec_from_file_location( mod_namespace, fpath, loader=loader ) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() #mod = importlib.util.module_from_spec(spec) #spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: with salt.utils.files.fopen(fpath, desc[1]) as fn_: mod = imp.load_module(mod_namespace, fn_, fpath, desc) except IOError: raise except ImportError as exc: if 'magic number' in six.text_type(exc): error_msg = 'Failed to import {0} {1}. Bad magic number. If migrating from Python2 to Python3, remove all .pyc files and try again.'.format(self.tag, name) log.warning(error_msg) self.missing_modules[name] = error_msg log.debug( 'Failed to import %s %s:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = exc return False except Exception as error: log.error( 'Failed to import %s %s, this is due most likely to a ' 'syntax error:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False except SystemExit as error: try: fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1] except Exception: pass else: tgt_fn = os.path.join('salt', 'utils', 'process.py') if fn_.endswith(tgt_fn) and '_handle_signals' in caller: # Race conditon, SIGTERM or SIGINT received while loader # was in process of loading a module. Call sys.exit to # ensure that the process is killed. sys.exit(salt.defaults.exitcodes.EX_OK) log.error( 'Failed to import %s %s as the module called exit()\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False finally: sys.path.remove(fpath_dirname) if hasattr(mod, '__opts__'): mod.__opts__.update(self.opts) else: mod.__opts__ = self.opts # pack whatever other globals we were asked to for p_name, p_value in six.iteritems(self.pack): _inject_into_mod(mod, p_name, p_value) module_name = mod.__name__.rsplit('.', 1)[-1] # Call a module's initialization method if it exists module_init = getattr(mod, '__init__', None) if inspect.isfunction(module_init): try: module_init(self.opts) except TypeError as e: log.error(e) except Exception: err_string = '__init__ failed' log.debug( 'Error loading %s.%s: %s', self.tag, module_name, err_string, exc_info=True ) self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False # if virtual modules are enabled, we need to look for the # __virtual__() function inside that module and run it. if self.virtual_enable: virtual_funcs_to_process = ['__virtual__'] + self.virtual_funcs for virtual_func in virtual_funcs_to_process: virtual_ret, module_name, virtual_err, virtual_aliases = \ self._process_virtual(mod, module_name, virtual_func) if virtual_err is not None: log.trace( 'Error loading %s.%s: %s', self.tag, module_name, virtual_err ) # if _process_virtual returned a non-True value then we are # supposed to not process this module if virtual_ret is not True and module_name not in self.missing_modules: # If a module has information about why it could not be loaded, record it self.missing_modules[module_name] = virtual_err self.missing_modules[name] = virtual_err return False else: virtual_aliases = () # If this is a proxy minion then MOST modules cannot work. Therefore, require that # any module that does work with salt-proxy-minion define __proxyenabled__ as a list # containing the names of the proxy types that the module supports. # # Render modules and state modules are OK though if 'proxy' in self.opts: if self.tag in ['grains', 'proxy']: if not hasattr(mod, '__proxyenabled__') or \ (self.opts['proxy']['proxytype'] not in mod.__proxyenabled__ and '*' not in mod.__proxyenabled__): err_string = 'not a proxy_minion enabled module' self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False if getattr(mod, '__load__', False) is not False: log.info( 'The functions from module \'%s\' are being loaded from the ' 'provided __load__ attribute', module_name ) # If we had another module by the same virtual name, we should put any # new functions under the existing dictionary. mod_names = [module_name] + list(virtual_aliases) mod_dict = dict(( (x, self.loaded_modules.get(x, self.mod_dict_class())) for x in mod_names )) for attr in getattr(mod, '__load__', dir(mod)): if attr.startswith('_') and attr != '__call__': # private functions are skipped, # except __call__ which is default entrance # for multi-function batch-like state syntax continue func = getattr(mod, attr) if not inspect.isfunction(func) and not isinstance(func, functools.partial): # Not a function!? Skip it!!! continue # Let's get the function name. # If the module has the __func_alias__ attribute, it must be a # dictionary mapping in the form of(key -> value): # <real-func-name> -> <desired-func-name> # # It default's of course to the found callable attribute name # if no alias is defined. funcname = getattr(mod, '__func_alias__', {}).get(attr, attr) for tgt_mod in mod_names: try: full_funcname = '.'.join((tgt_mod, funcname)) except TypeError: full_funcname = '{0}.{1}'.format(tgt_mod, funcname) # Save many references for lookups # Careful not to overwrite existing (higher priority) functions if full_funcname not in self._dict: self._dict[full_funcname] = func if funcname not in mod_dict[tgt_mod]: setattr(mod_dict[tgt_mod], funcname, func) mod_dict[tgt_mod][funcname] = func self._apply_outputter(func, mod) # enforce depends try: Depends.enforce_dependencies(self._dict, self.tag) except RuntimeError as exc: log.info( 'Depends.enforce_dependencies() failed for the following ' 'reason: %s', exc ) for tgt_mod in mod_names: self.loaded_modules[tgt_mod] = mod_dict[tgt_mod] return True def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise KeyError('The key \'{0}\' should contain a \'.\''.format(key)) mod_name, _ = key.split('.', 1) with self._lock: # It is possible that the key is in the dictionary after # acquiring the lock due to another thread loading it. if mod_name in self.missing_modules or key in self._dict: return True # if the modulename isn't in the whitelist, don't bother if self.whitelist and mod_name not in self.whitelist: log.error( 'Failed to load function %s because its module (%s) is ' 'not in the whitelist: %s', key, mod_name, self.whitelist ) raise KeyError(key) def _inner_load(mod_name): for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and key in self._dict: return True return False # try to load the module ret = None reloaded = False # re-scan up to once, IOErrors or a failed load cause re-scans of the # filesystem while True: try: ret = _inner_load(mod_name) if not reloaded and ret is not True: self._refresh_file_mapping() reloaded = True continue break except IOError: if not reloaded: self._refresh_file_mapping() reloaded = True continue return ret def _load_all(self): ''' Load all of them ''' with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True def reload_modules(self): with self._lock: self.loaded_files = set() self._load_all() def _apply_outputter(self, func, mod): ''' Apply the __outputter__ variable to the functions ''' if hasattr(mod, '__outputter__'): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__] def _process_virtual(self, mod, module_name, virtual_func='__virtual__'): ''' Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1] ''' # The __virtual__ function will return either a True or False value. # If it returns a True value it can also set a module level attribute # named __virtualname__ with the name that the module should be # referred to as. # # This allows us to have things like the pkg module working on all # platforms under the name 'pkg'. It also allows for modules like # augeas_cfg to be referred to as 'augeas', which would otherwise have # namespace collisions. And finally it allows modules to return False # if they are not intended to run on the given platform or are missing # dependencies. virtual_aliases = getattr(mod, '__virtual_aliases__', tuple()) try: error_reason = None if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__): try: start = time.time() virtual = getattr(mod, virtual_func)() if isinstance(virtual, tuple): error_reason = virtual[1] virtual = virtual[0] if self.opts.get('virtual_timer', False): end = time.time() - start msg = 'Virtual function took {0} seconds for {1}'.format( end, module_name) log.warning(msg) except Exception as exc: error_reason = ( 'Exception raised when processing __virtual__ function' ' for {0}. Module will not be loaded: {1}'.format( mod.__name__, exc)) log.error(error_reason, exc_info_on_loglevel=logging.DEBUG) virtual = None # Get the module's virtual name virtualname = getattr(mod, '__virtualname__', virtual) if not virtual: # if __virtual__() evaluates to False then the module # wasn't meant for this platform or it's not supposed to # load for some other reason. # Some modules might accidentally return None and are # improperly loaded if virtual is None: log.warning( '%s.__virtual__() is wrongly returning `None`. ' 'It should either return `True`, `False` or a new ' 'name. If you\'re the developer of the module ' '\'%s\', please fix this.', mod.__name__, module_name ) return (False, module_name, error_reason, virtual_aliases) # At this point, __virtual__ did not return a # boolean value, let's check for deprecated usage # or module renames if virtual is not True and module_name != virtual: # The module is renaming itself. Updating the module name # with the new name log.trace('Loaded %s as virtual %s', module_name, virtual) if virtualname != virtual: # The __virtualname__ attribute does not match what's # being returned by the __virtual__() function. This # should be considered an error. log.error( 'The module \'%s\' is showing some bad usage. Its ' '__virtualname__ attribute is set to \'%s\' yet the ' '__virtual__() function is returning \'%s\'. These ' 'values should match!', mod.__name__, virtualname, virtual ) module_name = virtualname # If the __virtual__ function returns True and __virtualname__ # is set then use it elif virtual is True and virtualname != module_name: if virtualname is not True: module_name = virtualname except KeyError: # Key errors come out of the virtual function when passing # in incomplete grains sets, these can be safely ignored # and logged to debug, still, it includes the traceback to # help debugging. log.debug('KeyError when loading %s', module_name, exc_info=True) except Exception: # If the module throws an exception during __virtual__() # then log the information and continue to the next. log.error( 'Failed to read the virtual function for %s: %s', self.tag, module_name, exc_info=True ) return (False, module_name, error_reason, virtual_aliases) return (True, module_name, None, virtual_aliases) def global_injector_decorator(inject_globals): ''' Decorator used by the LazyLoader to inject globals into a function at execute time. globals Dictionary with global variables to inject ''' def inner_decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): with salt.utils.context.func_globals_inject(f, **inject_globals): return f(*args, **kwargs) return wrapper return inner_decorator
saltstack/salt
salt/loader.py
executors
python
def executors(opts, functions=None, context=None, proxy=None): ''' Returns the executor modules ''' executors = LazyLoader( _module_dirs(opts, 'executors', 'executor'), opts, tag='executor', pack={'__salt__': functions, '__context__': context or {}, '__proxy__': proxy or {}}, ) executors.pack['__executors__'] = executors return executors
Returns the executor modules
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L1053-L1064
null
# -*- coding: utf-8 -*- ''' The Salt loader is the core to Salt's plugin system, the loader scans directories for python loadable code and organizes the code into the plugin interfaces used by Salt. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import sys import time import logging import inspect import tempfile import threading import functools import threading import traceback import types from zipimport import zipimporter # Import salt libs import salt.config import salt.defaults.events import salt.defaults.exitcodes import salt.syspaths import salt.utils.args import salt.utils.context import salt.utils.data import salt.utils.dictupdate import salt.utils.event import salt.utils.files import salt.utils.lazy import salt.utils.odict import salt.utils.platform import salt.utils.versions import salt.utils.stringutils from salt.exceptions import LoaderError from salt.template import check_render_pipe_str from salt.utils.decorators import Depends from salt.utils.thread_local_proxy import ThreadLocalProxy # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import reload_module if sys.version_info[:2] >= (3, 5): import importlib.machinery # pylint: disable=no-name-in-module,import-error import importlib.util # pylint: disable=no-name-in-module,import-error USE_IMPORTLIB = True else: import imp USE_IMPORTLIB = False try: from collections.abc import MutableMapping except ImportError: from collections import MutableMapping try: import pkg_resources HAS_PKG_RESOURCES = True except ImportError: HAS_PKG_RESOURCES = False log = logging.getLogger(__name__) SALT_BASE_PATH = os.path.abspath(salt.syspaths.INSTALL_DIR) LOADED_BASE_NAME = 'salt.loaded' if USE_IMPORTLIB: # pylint: disable=no-member MODULE_KIND_SOURCE = 1 MODULE_KIND_COMPILED = 2 MODULE_KIND_EXTENSION = 3 MODULE_KIND_PKG_DIRECTORY = 5 SUFFIXES = [] for suffix in importlib.machinery.EXTENSION_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_EXTENSION)) for suffix in importlib.machinery.SOURCE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_SOURCE)) for suffix in importlib.machinery.BYTECODE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_COMPILED)) MODULE_KIND_MAP = { MODULE_KIND_SOURCE: importlib.machinery.SourceFileLoader, MODULE_KIND_COMPILED: importlib.machinery.SourcelessFileLoader, MODULE_KIND_EXTENSION: importlib.machinery.ExtensionFileLoader } # pylint: enable=no-member else: SUFFIXES = imp.get_suffixes() PY3_PRE_EXT = \ re.compile(r'\.cpython-{0}{1}(\.opt-[1-9])?'.format(*sys.version_info[:2])) # Because on the cloud drivers we do `from salt.cloud.libcloudfuncs import *` # which simplifies code readability, it adds some unsupported functions into # the driver's module scope. # We list un-supported functions here. These will be removed from the loaded. # TODO: remove the need for this cross-module code. Maybe use NotImplemented LIBCLOUD_FUNCS_NOT_SUPPORTED = ( 'parallels.avail_sizes', 'parallels.avail_locations', 'proxmox.avail_sizes', ) # Will be set to pyximport module at runtime if cython is enabled in config. pyximport = None def static_loader( opts, ext_type, tag, pack=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, filter_name=None, ): funcs = LazyLoader( _module_dirs( opts, ext_type, tag, int_type, ext_dirs, ext_type_dirs, base_path, ), opts, tag=tag, pack=pack, ) ret = {} funcs._load_all() if filter_name: funcs = FilterDictWrapper(funcs, filter_name) for key in funcs: ret[key] = funcs[key] return ret def _format_entrypoint_target(ep): ''' Makes a string describing the target of an EntryPoint object. Base strongly on EntryPoint.__str__(). ''' s = ep.module_name if ep.attrs: s += ':' + '.'.join(ep.attrs) return s def _module_dirs( opts, ext_type, tag=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, ): if tag is None: tag = ext_type sys_types = os.path.join(base_path or SALT_BASE_PATH, int_type or ext_type) ext_types = os.path.join(opts['extension_modules'], ext_type) ext_type_types = [] if ext_dirs: if ext_type_dirs is None: ext_type_dirs = '{0}_dirs'.format(tag) if ext_type_dirs in opts: ext_type_types.extend(opts[ext_type_dirs]) if HAS_PKG_RESOURCES and ext_type_dirs: for entry_point in pkg_resources.iter_entry_points('salt.loader', ext_type_dirs): try: loaded_entry_point = entry_point.load() for path in loaded_entry_point(): ext_type_types.append(path) except Exception as exc: log.error("Error getting module directories from %s: %s", _format_entrypoint_target(entry_point), exc) log.debug("Full backtrace for module directories error", exc_info=True) cli_module_dirs = [] # The dirs can be any module dir, or a in-tree _{ext_type} dir for _dir in opts.get('module_dirs', []): # Prepend to the list to match cli argument ordering maybe_dir = os.path.join(_dir, ext_type) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) continue maybe_dir = os.path.join(_dir, '_{0}'.format(ext_type)) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) return cli_module_dirs + ext_type_types + [ext_types, sys_types] def minion_mods( opts, context=None, utils=None, whitelist=None, initial_load=False, loaded_base_name=None, notify=False, static_modules=None, proxy=None): ''' Load execution modules Returns a dictionary of execution modules appropriate for the current system by evaluating the __virtual__() function in each module. :param dict opts: The Salt options dictionary :param dict context: A Salt context that should be made present inside generated modules in __context__ :param dict utils: Utility functions which should be made available to Salt modules in __utils__. See `utils_dirs` in salt.config for additional information about configuration. :param list whitelist: A list of modules which should be whitelisted. :param bool initial_load: Deprecated flag! Unused. :param str loaded_base_name: A string marker for the loaded base name. :param bool notify: Flag indicating that an event should be fired upon completion of module loading. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) __opts__['grains'] = __grains__ __utils__ = salt.loader.utils(__opts__) __salt__ = salt.loader.minion_mods(__opts__, utils=__utils__) __salt__['test.ping']() ''' # TODO Publish documentation for module whitelisting if not whitelist: whitelist = opts.get('whitelist_modules', None) ret = LazyLoader( _module_dirs(opts, 'modules', 'module'), opts, tag='module', pack={'__context__': context, '__utils__': utils, '__proxy__': proxy}, whitelist=whitelist, loaded_base_name=loaded_base_name, static_modules=static_modules, ) ret.pack['__salt__'] = ret # Load any provider overrides from the configuration file providers option # Note: Providers can be pkg, service, user or group - not to be confused # with cloud providers. providers = opts.get('providers', False) if providers and isinstance(providers, dict): for mod in providers: # sometimes providers opts is not to diverge modules but # for other configuration try: funcs = raw_mod(opts, providers[mod], ret) except TypeError: break else: if funcs: for func in funcs: f_key = '{0}{1}'.format(mod, func[func.rindex('.'):]) ret[f_key] = funcs[func] if notify: evt = salt.utils.event.get_event('minion', opts=opts, listen=False) evt.fire_event({'complete': True}, tag=salt.defaults.events.MINION_MOD_COMPLETE) return ret def raw_mod(opts, name, functions, mod='modules'): ''' Returns a single module loaded raw and bypassing the __virtual__ function .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') testmod = salt.loader.raw_mod(__opts__, 'test', None) testmod['test.ping']() ''' loader = LazyLoader( _module_dirs(opts, mod, 'module'), opts, tag='rawmodule', virtual_enable=False, pack={'__salt__': functions}, ) # if we don't have the module, return an empty dict if name not in loader.file_mapping: return {} loader._load_module(name) # load a single module (the one passed in) return dict(loader._dict) # return a copy of *just* the funcs for `name` def metaproxy(opts): ''' Return functions used in the meta proxy ''' return LazyLoader( _module_dirs(opts, 'metaproxy'), opts, tag='metaproxy' ) def matchers(opts): ''' Return the matcher services plugins ''' return LazyLoader( _module_dirs(opts, 'matchers'), opts, tag='matchers' ) def engines(opts, functions, runners, utils, proxy=None): ''' Return the master services plugins ''' pack = {'__salt__': functions, '__runners__': runners, '__proxy__': proxy, '__utils__': utils} return LazyLoader( _module_dirs(opts, 'engines'), opts, tag='engines', pack=pack, ) def proxy(opts, functions=None, returners=None, whitelist=None, utils=None): ''' Returns the proxy module for this salt-proxy-minion ''' ret = LazyLoader( _module_dirs(opts, 'proxy'), opts, tag='proxy', pack={'__salt__': functions, '__ret__': returners, '__utils__': utils}, ) ret.pack['__proxy__'] = ret return ret def returners(opts, functions, whitelist=None, context=None, proxy=None): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'returners', 'returner'), opts, tag='returner', whitelist=whitelist, pack={'__salt__': functions, '__context__': context, '__proxy__': proxy or {}}, ) def utils(opts, whitelist=None, context=None, proxy=proxy): ''' Returns the utility modules ''' return LazyLoader( _module_dirs(opts, 'utils', ext_type_dirs='utils_dirs'), opts, tag='utils', whitelist=whitelist, pack={'__context__': context, '__proxy__': proxy or {}}, ) def pillars(opts, functions, context=None): ''' Returns the pillars modules ''' ret = LazyLoader(_module_dirs(opts, 'pillar'), opts, tag='pillar', pack={'__salt__': functions, '__context__': context, '__utils__': utils(opts)}) ret.pack['__ext_pillar__'] = ret return FilterDictWrapper(ret, '.ext_pillar') def tops(opts): ''' Returns the tops modules ''' if 'master_tops' not in opts: return {} whitelist = list(opts['master_tops'].keys()) ret = LazyLoader( _module_dirs(opts, 'tops', 'top'), opts, tag='top', whitelist=whitelist, ) return FilterDictWrapper(ret, '.top') def wheels(opts, whitelist=None, context=None): ''' Returns the wheels modules ''' if context is None: context = {} return LazyLoader( _module_dirs(opts, 'wheel'), opts, tag='wheel', whitelist=whitelist, pack={'__context__': context}, ) def outputters(opts): ''' Returns the outputters modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only outputters present in the keyspace ''' ret = LazyLoader( _module_dirs(opts, 'output', ext_type_dirs='outputter_dirs'), opts, tag='output', ) wrapped_ret = FilterDictWrapper(ret, '.output') # TODO: this name seems terrible... __salt__ should always be execution mods ret.pack['__salt__'] = wrapped_ret return wrapped_ret def serializers(opts): ''' Returns the serializers modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only serializers present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'serializers'), opts, tag='serializers', ) def eauth_tokens(opts): ''' Returns the tokens modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only token backends present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'tokens'), opts, tag='tokens', ) def auth(opts, whitelist=None): ''' Returns the auth modules :param dict opts: The Salt options dictionary :returns: LazyLoader ''' return LazyLoader( _module_dirs(opts, 'auth'), opts, tag='auth', whitelist=whitelist, pack={'__salt__': minion_mods(opts)}, ) def fileserver(opts, backends): ''' Returns the file server modules ''' return LazyLoader(_module_dirs(opts, 'fileserver'), opts, tag='fileserver', whitelist=backends, pack={'__utils__': utils(opts)}) def roster(opts, runner=None, utils=None, whitelist=None): ''' Returns the roster modules ''' return LazyLoader( _module_dirs(opts, 'roster'), opts, tag='roster', whitelist=whitelist, pack={ '__runner__': runner, '__utils__': utils, }, ) def thorium(opts, functions, runners): ''' Load the thorium runtime modules ''' pack = {'__salt__': functions, '__runner__': runners, '__context__': {}} ret = LazyLoader(_module_dirs(opts, 'thorium'), opts, tag='thorium', pack=pack) ret.pack['__thorium__'] = ret return ret def states(opts, functions, utils, serializers, whitelist=None, proxy=None, context=None): ''' Returns the state modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') statemods = salt.loader.states(__opts__, None, None) ''' if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'states'), opts, tag='states', pack={'__salt__': functions, '__proxy__': proxy or {}}, whitelist=whitelist, ) ret.pack['__states__'] = ret ret.pack['__utils__'] = utils ret.pack['__serializers__'] = serializers ret.pack['__context__'] = context return ret def beacons(opts, functions, context=None, proxy=None): ''' Load the beacon modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. ''' return LazyLoader( _module_dirs(opts, 'beacons'), opts, tag='beacons', pack={'__context__': context, '__salt__': functions, '__proxy__': proxy or {}}, virtual_funcs=[], ) def log_handlers(opts): ''' Returns the custom logging handler modules :param dict opts: The Salt options dictionary ''' ret = LazyLoader( _module_dirs( opts, 'log_handlers', int_type='handlers', base_path=os.path.join(SALT_BASE_PATH, 'log'), ), opts, tag='log_handlers', ) return FilterDictWrapper(ret, '.setup_handlers') def ssh_wrapper(opts, functions=None, context=None): ''' Returns the custom logging handler modules ''' return LazyLoader( _module_dirs( opts, 'wrapper', base_path=os.path.join(SALT_BASE_PATH, os.path.join('client', 'ssh')), ), opts, tag='wrapper', pack={ '__salt__': functions, '__grains__': opts.get('grains', {}), '__pillar__': opts.get('pillar', {}), '__context__': context, }, ) def render(opts, functions, states=None, proxy=None, context=None): ''' Returns the render modules ''' if context is None: context = {} pack = {'__salt__': functions, '__grains__': opts.get('grains', {}), '__context__': context} if states: pack['__states__'] = states pack['__proxy__'] = proxy or {} ret = LazyLoader( _module_dirs( opts, 'renderers', 'render', ext_type_dirs='render_dirs', ), opts, tag='render', pack=pack, ) rend = FilterDictWrapper(ret, '.render') if not check_render_pipe_str(opts['renderer'], rend, opts['renderer_blacklist'], opts['renderer_whitelist']): err = ('The renderer {0} is unavailable, this error is often because ' 'the needed software is unavailable'.format(opts['renderer'])) log.critical(err) raise LoaderError(err) return rend def grain_funcs(opts, proxy=None): ''' Returns the grain functions .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') grainfuncs = salt.loader.grain_funcs(__opts__) ''' ret = LazyLoader( _module_dirs( opts, 'grains', 'grain', ext_type_dirs='grains_dirs', ), opts, tag='grains', ) ret.pack['__utils__'] = utils(opts, proxy=proxy) return ret def _load_cached_grains(opts, cfn): ''' Returns the grains cached in cfn, or None if the cache is too old or is corrupted. ''' if not os.path.isfile(cfn): log.debug('Grains cache file does not exist.') return None grains_cache_age = int(time.time() - os.path.getmtime(cfn)) if grains_cache_age > opts.get('grains_cache_expiration', 300): log.debug( 'Grains cache last modified %s seconds ago and cache ' 'expiration is set to %s. Grains cache expired. ' 'Refreshing.', grains_cache_age, opts.get('grains_cache_expiration', 300) ) return None if opts.get('refresh_grains_cache', False): log.debug('refresh_grains_cache requested, Refreshing.') return None log.debug('Retrieving grains from cache') try: serial = salt.payload.Serial(opts) with salt.utils.files.fopen(cfn, 'rb') as fp_: cached_grains = salt.utils.data.decode(serial.load(fp_), preserve_tuples=True) if not cached_grains: log.debug('Cached grains are empty, cache might be corrupted. Refreshing.') return None return cached_grains except (IOError, OSError): return None def grains(opts, force_refresh=False, proxy=None): ''' Return the functions for the dynamic grains and the values for the static grains. Since grains are computed early in the startup process, grains functions do not have __salt__ or __proxy__ available. At proxy-minion startup, this function is called with the proxymodule LazyLoader object so grains functions can communicate with their controlled device. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) print __grains__['id'] ''' # Need to re-import salt.config, somehow it got lost when a minion is starting import salt.config # if we have no grains, lets try loading from disk (TODO: move to decorator?) cfn = os.path.join( opts['cachedir'], 'grains.cache.p' ) if not force_refresh and opts.get('grains_cache', False): cached_grains = _load_cached_grains(opts, cfn) if cached_grains: return cached_grains else: log.debug('Grains refresh requested. Refreshing grains.') if opts.get('skip_grains', False): return {} grains_deep_merge = opts.get('grains_deep_merge', False) is True if 'conf_file' in opts: pre_opts = {} pre_opts.update(salt.config.load_config( opts['conf_file'], 'SALT_MINION_CONFIG', salt.config.DEFAULT_MINION_OPTS['conf_file'] )) default_include = pre_opts.get( 'default_include', opts['default_include'] ) include = pre_opts.get('include', []) pre_opts.update(salt.config.include_config( default_include, opts['conf_file'], verbose=False )) pre_opts.update(salt.config.include_config( include, opts['conf_file'], verbose=True )) if 'grains' in pre_opts: opts['grains'] = pre_opts['grains'] else: opts['grains'] = {} else: opts['grains'] = {} grains_data = {} blist = opts.get('grains_blacklist', []) funcs = grain_funcs(opts, proxy=proxy) if force_refresh: # if we refresh, lets reload grain modules funcs.clear() # Run core grains for key in funcs: if not key.startswith('core.'): continue log.trace('Loading %s grain', key) ret = funcs[key]() if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) # Run the rest of the grains for key in funcs: if key.startswith('core.') or key == '_errors': continue try: # Grains are loaded too early to take advantage of the injected # __proxy__ variable. Pass an instance of that LazyLoader # here instead to grains functions if the grains functions take # one parameter. Then the grains can have access to the # proxymodule for retrieving information from the connected # device. log.trace('Loading %s grain', key) parameters = salt.utils.args.get_function_argspec(funcs[key]).args kwargs = {} if 'proxy' in parameters: kwargs['proxy'] = proxy if 'grains' in parameters: kwargs['grains'] = grains_data ret = funcs[key](**kwargs) except Exception: if salt.utils.platform.is_proxy(): log.info('The following CRITICAL message may not be an error; the proxy may not be completely established yet.') log.critical( 'Failed to load grains defined in grain file %s in ' 'function %s, error:\n', key, funcs[key], exc_info=True ) continue if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) if opts.get('proxy_merge_grains_in_module', True) and proxy: try: proxytype = proxy.opts['proxy']['proxytype'] if proxytype + '.grains' in proxy: if proxytype + '.initialized' in proxy and proxy[proxytype + '.initialized'](): try: proxytype = proxy.opts['proxy']['proxytype'] ret = proxy[proxytype + '.grains']() if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) except Exception: log.critical('Failed to run proxy\'s grains function!', exc_info=True ) except KeyError: pass grains_data.update(opts['grains']) # Write cache if enabled if opts.get('grains_cache', False): with salt.utils.files.set_umask(0o077): try: if salt.utils.platform.is_windows(): # Late import import salt.modules.cmdmod # Make sure cache file isn't read-only salt.modules.cmdmod._run_quiet('attrib -R "{0}"'.format(cfn)) with salt.utils.files.fopen(cfn, 'w+b') as fp_: try: serial = salt.payload.Serial(opts) serial.dump(grains_data, fp_) except TypeError as e: log.error('Failed to serialize grains cache: %s', e) raise # re-throw for cleanup except Exception as e: log.error('Unable to write to grains cache file %s: %s', cfn, e) # Based on the original exception, the file may or may not have been # created. If it was, we will remove it now, as the exception means # the serialized data is not to be trusted, no matter what the # exception is. if os.path.isfile(cfn): os.unlink(cfn) if grains_deep_merge: salt.utils.dictupdate.update(grains_data, opts['grains']) else: grains_data.update(opts['grains']) return salt.utils.data.decode(grains_data, preserve_tuples=True) # TODO: get rid of? Does anyone use this? You should use raw() instead def call(fun, **kwargs): ''' Directly call a function inside a loader directory ''' args = kwargs.get('args', []) dirs = kwargs.get('dirs', []) funcs = LazyLoader( [os.path.join(SALT_BASE_PATH, 'modules')] + dirs, None, tag='modules', virtual_enable=False, ) return funcs[fun](*args) def runner(opts, utils=None, context=None, whitelist=None): ''' Directly call a function inside a loader directory ''' if utils is None: utils = {} if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'runners', 'runner', ext_type_dirs='runner_dirs'), opts, tag='runners', pack={'__utils__': utils, '__context__': context}, whitelist=whitelist, ) # TODO: change from __salt__ to something else, we overload __salt__ too much ret.pack['__salt__'] = ret return ret def queues(opts): ''' Directly call a function inside a loader directory ''' return LazyLoader( _module_dirs(opts, 'queues', 'queue', ext_type_dirs='queue_dirs'), opts, tag='queues', ) def sdb(opts, functions=None, whitelist=None, utils=None): ''' Make a very small database call ''' if utils is None: utils = {} return LazyLoader( _module_dirs(opts, 'sdb'), opts, tag='sdb', pack={ '__sdb__': functions, '__opts__': opts, '__utils__': utils, '__salt__': minion_mods(opts, utils), }, whitelist=whitelist, ) def pkgdb(opts): ''' Return modules for SPM's package database .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgdb', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgdb' ) def pkgfiles(opts): ''' Return modules for SPM's file handling .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgfiles', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgfiles' ) def clouds(opts): ''' Return the cloud functions ''' # Let's bring __active_provider_name__, defaulting to None, to all cloud # drivers. This will get temporarily updated/overridden with a context # manager when needed. functions = LazyLoader( _module_dirs(opts, 'clouds', 'cloud', base_path=os.path.join(SALT_BASE_PATH, 'cloud'), int_type='clouds'), opts, tag='clouds', pack={'__utils__': salt.loader.utils(opts), '__active_provider_name__': None}, ) for funcname in LIBCLOUD_FUNCS_NOT_SUPPORTED: log.trace( '\'%s\' has been marked as not supported. Removing from the ' 'list of supported cloud functions', funcname ) functions.pop(funcname, None) return functions def netapi(opts): ''' Return the network api functions ''' return LazyLoader( _module_dirs(opts, 'netapi'), opts, tag='netapi', ) def cache(opts, serial): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'cache', 'cache'), opts, tag='cache', pack={'__opts__': opts, '__context__': {'serial': serial}}, ) def _generate_module(name): if name in sys.modules: return code = "'''Salt loaded {0} parent module'''".format(name.split('.')[-1]) # ModuleType can't accept a unicode type on PY2 module = types.ModuleType(str(name)) # future lint: disable=blacklisted-function exec(code, module.__dict__) sys.modules[name] = module def _mod_type(module_path): if module_path.startswith(SALT_BASE_PATH): return 'int' return 'ext' def _inject_into_mod(mod, name, value, force_lock=False): ''' Inject a variable into a module. This is used to inject "globals" like ``__salt__``, ``__pillar``, or ``grains``. Instead of injecting the value directly, a ``ThreadLocalProxy`` is created. If such a proxy is already present under the specified name, it is updated with the new value. This update only affects the current thread, so that the same name can refer to different values depending on the thread of execution. This is important for data that is not truly global. For example, pillar data might be dynamically overriden through function parameters and thus the actual values available in pillar might depend on the thread that is calling a module. mod: module object into which the value is going to be injected. name: name of the variable that is injected into the module. value: value that is injected into the variable. The value is not injected directly, but instead set as the new reference of the proxy that has been created for the variable. force_lock: whether the lock should be acquired before checking whether a proxy object for the specified name has already been injected into the module. If ``False`` (the default), this function checks for the module's variable without acquiring the lock and only acquires the lock if a new proxy has to be created and injected. ''' old_value = getattr(mod, name, None) # We use a double-checked locking scheme in order to avoid taking the lock # when a proxy object has already been injected. # In most programming languages, double-checked locking is considered # unsafe when used without explicit memory barriers because one might read # an uninitialized value. In CPython it is safe due to the global # interpreter lock (GIL). In Python implementations that do not have the # GIL, it could be unsafe, but at least Jython also guarantees that (for # Python objects) memory is not corrupted when writing and reading without # explicit synchronization # (http://www.jython.org/jythonbook/en/1.0/Concurrency.html). # Please note that in order to make this code safe in a runtime environment # that does not make this guarantees, it is not sufficient. The # ThreadLocalProxy must also be created with fallback_to_shared set to # False or a lock must be added to the ThreadLocalProxy. if force_lock: with _inject_into_mod.lock: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: setattr(mod, name, ThreadLocalProxy(value, True)) else: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: _inject_into_mod(mod, name, value, True) # Lock used when injecting globals. This is needed to avoid a race condition # when two threads try to load the same module concurrently. This must be # outside the loader because there might be more than one loader for the same # namespace. _inject_into_mod.lock = threading.RLock() # TODO: move somewhere else? class FilterDictWrapper(MutableMapping): ''' Create a dict which wraps another dict with a specific key suffix on get This is to replace "filter_load" ''' def __init__(self, d, suffix): self._dict = d self.suffix = suffix def __setitem__(self, key, val): self._dict[key] = val def __delitem__(self, key): del self._dict[key] def __getitem__(self, key): return self._dict[key + self.suffix] def __len__(self): return len(self._dict) def __iter__(self): for key in self._dict: if key.endswith(self.suffix): yield key.replace(self.suffix, '') class LazyLoader(salt.utils.lazy.LazyDict): ''' A pseduo-dictionary which has a set of keys which are the name of the module and function, delimited by a dot. When the value of the key is accessed, the function is then loaded from disk and into memory. .. note:: Iterating over keys will cause all modules to be loaded. :param list module_dirs: A list of directories on disk to search for modules :param dict opts: The salt options dictionary. :param str tag: The tag for the type of module to load :param func mod_type_check: A function which can be used to verify files :param dict pack: A dictionary of function to be packed into modules as they are loaded :param list whitelist: A list of modules to whitelist :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules. :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality. If not true, the module will not load. :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values are function references themselves which are loaded on-demand. # TODO: - move modules_max_memory into here - singletons (per tag) ''' mod_dict_class = salt.utils.odict.OrderedDict def __init__(self, module_dirs, opts=None, tag='module', loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, proxy=None, virtual_funcs=None, ): # pylint: disable=W0231 ''' In pack, if any of the values are None they will be replaced with an empty context-specific dict ''' self.inject_globals = {} self.pack = {} if pack is None else pack if opts is None: opts = {} threadsafety = not opts.get('multiprocessing') self.context_dict = salt.utils.context.ContextDict(threadsafe=threadsafety) self.opts = self.__prep_mod_opts(opts) self.module_dirs = module_dirs self.tag = tag self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME self.mod_type_check = mod_type_check or _mod_type if '__context__' not in self.pack: self.pack['__context__'] = None for k, v in six.iteritems(self.pack): if v is None: # if the value of a pack is None, lets make an empty dict value = self.context_dict.get(k, {}) if isinstance(value, ThreadLocalProxy): value = ThreadLocalProxy.unproxy(value) self.context_dict[k] = value self.pack[k] = salt.utils.context.NamespacedDictWrapper(self.context_dict, k) self.whitelist = whitelist self.virtual_enable = virtual_enable self.initial_load = True # names of modules that we don't have (errors, __virtual__, etc.) self.missing_modules = {} # mapping of name -> error self.loaded_modules = {} # mapping of module_name -> dict_of_functions self.loaded_files = set() # TODO: just remove them from file_mapping? self.static_modules = static_modules if static_modules else [] if virtual_funcs is None: virtual_funcs = [] self.virtual_funcs = virtual_funcs self.disabled = set( self.opts.get( 'disable_{0}{1}'.format( self.tag, '' if self.tag[-1] == 's' else 's' ), [] ) ) # A map of suffix to description for imp self.suffix_map = {} # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [''] for (suffix, mode, kind) in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) self._lock = threading.RLock() self._refresh_file_mapping() super(LazyLoader, self).__init__() # late init the lazy loader # create all of the import namespaces _generate_module('{0}.int'.format(self.loaded_base_name)) _generate_module('{0}.int.{1}'.format(self.loaded_base_name, tag)) _generate_module('{0}.ext'.format(self.loaded_base_name)) _generate_module('{0}.ext.{1}'.format(self.loaded_base_name, tag)) def __getitem__(self, item): ''' Override the __getitem__ in order to decorate the returned function if we need to last-minute inject globals ''' func = super(LazyLoader, self).__getitem__(item) if self.inject_globals: return global_injector_decorator(self.inject_globals)(func) else: return func def __getattr__(self, mod_name): ''' Allow for "direct" attribute access-- this allows jinja templates to access things like `salt.test.ping()` ''' if mod_name in ('__getstate__', '__setstate__'): return object.__getattribute__(self, mod_name) # if we have an attribute named that, lets return it. try: return object.__getattr__(self, mod_name) # pylint: disable=no-member except AttributeError: pass # otherwise we assume its jinja template access if mod_name not in self.loaded_modules and not self.loaded: for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and mod_name in self.loaded_modules: break if mod_name in self.loaded_modules: return self.loaded_modules[mod_name] else: raise AttributeError(mod_name) def missing_fun_string(self, function_name): ''' Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ''' mod_name = function_name.split('.')[0] if mod_name in self.loaded_modules: return '\'{0}\' is not available.'.format(function_name) else: try: reason = self.missing_modules[mod_name] except KeyError: return '\'{0}\' is not available.'.format(function_name) else: if reason is not None: return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason) else: return '\'{0}\' __virtual__ returned False'.format(mod_name) def _refresh_file_mapping(self): ''' refresh the mapping of the FS on disk ''' # map of suffix to description for imp if self.opts.get('cython_enable', True) is True: try: global pyximport pyximport = __import__('pyximport') # pylint: disable=import-error pyximport.install() # add to suffix_map so file_mapping will pick it up self.suffix_map['.pyx'] = tuple() except ImportError: log.info('Cython is enabled in the options but not present ' 'in the system path. Skipping Cython modules.') # Allow for zipimport of modules if self.opts.get('enable_zip_modules', True) is True: self.suffix_map['.zip'] = tuple() # allow for module dirs if USE_IMPORTLIB: self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY) else: self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY) # create mapping of filename (without suffix) to (path, suffix) # The files are added in order of priority, so order *must* be retained. self.file_mapping = salt.utils.odict.OrderedDict() opt_match = [] def _replace_pre_ext(obj): ''' Hack so we can get the optimization level that we replaced (if any) out of the re.sub call below. We use a list here because it is a persistent data structure that we will be able to access after re.sub is called. ''' opt_match.append(obj) return '' for mod_dir in self.module_dirs: try: # Make sure we have a sorted listdir in order to have # expectable override results files = sorted( x for x in os.listdir(mod_dir) if x != '__pycache__' ) except OSError: continue # Next mod_dir if six.PY3: try: pycache_files = [ os.path.join('__pycache__', x) for x in sorted(os.listdir(os.path.join(mod_dir, '__pycache__'))) ] except OSError: pass else: files.extend(pycache_files) for filename in files: try: dirname, basename = os.path.split(filename) if basename.startswith('_'): # skip private modules # log messages omitted for obviousness continue # Next filename f_noext, ext = os.path.splitext(basename) if six.PY3: f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext) try: opt_level = int( opt_match.pop().group(1).rsplit('-', 1)[-1] ) except (AttributeError, IndexError, ValueError): # No regex match or no optimization level matched opt_level = 0 try: opt_index = self.opts['optimization_order'].index(opt_level) except KeyError: log.trace( 'Disallowed optimization level %d for module ' 'name \'%s\', skipping. Add %d to the ' '\'optimization_order\' config option if you ' 'do not want to ignore this optimization ' 'level.', opt_level, f_noext, opt_level ) continue else: # Optimization level not reflected in filename on PY2 opt_index = 0 # make sure it is a suffix we support if ext not in self.suffix_map: continue # Next filename if f_noext in self.disabled: log.trace( 'Skipping %s, it is disabled by configuration', filename ) continue # Next filename fpath = os.path.join(mod_dir, filename) # if its a directory, lets allow us to load that if ext == '': # is there something __init__? subfiles = os.listdir(fpath) for suffix in self.suffix_order: if '' == suffix: continue # Next suffix (__init__ must have a suffix) init_file = '__init__{0}'.format(suffix) if init_file in subfiles: break else: continue # Next filename try: curr_ext = self.file_mapping[f_noext][1] curr_opt_index = self.file_mapping[f_noext][2] except KeyError: pass else: if '' in (curr_ext, ext) and curr_ext != ext: log.error( 'Module/package collision: \'%s\' and \'%s\'', fpath, self.file_mapping[f_noext][0] ) if six.PY3 and ext == '.pyc' and curr_ext == '.pyc': # Check the optimization level if opt_index >= curr_opt_index: # Module name match, but a higher-priority # optimization level was already matched, skipping. continue elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext): # Match found but a higher-priorty match already # exists, so skip this. continue if six.PY3 and not dirname and ext == '.pyc': # On Python 3, we should only load .pyc files from the # __pycache__ subdirectory (i.e. when dirname is not an # empty string). continue # Made it this far - add it self.file_mapping[f_noext] = (fpath, ext, opt_index) except OSError: continue for smod in self.static_modules: f_noext = smod.split('.')[-1] self.file_mapping[f_noext] = (smod, '.o', 0) def clear(self): ''' Clear the dict ''' with self._lock: super(LazyLoader, self).clear() # clear the lazy loader self.loaded_files = set() self.missing_modules = {} self.loaded_modules = {} # if we have been loaded before, lets clear the file mapping since # we obviously want a re-do if hasattr(self, 'opts'): self._refresh_file_mapping() self.initial_load = False def __prep_mod_opts(self, opts): ''' Strip out of the opts any logger instance ''' if '__grains__' not in self.pack: grains = opts.get('grains', {}) if isinstance(grains, ThreadLocalProxy): grains = ThreadLocalProxy.unproxy(grains) self.context_dict['grains'] = grains self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains') if '__pillar__' not in self.pack: pillar = opts.get('pillar', {}) if isinstance(pillar, ThreadLocalProxy): pillar = ThreadLocalProxy.unproxy(pillar) self.context_dict['pillar'] = pillar self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar') mod_opts = {} for key, val in list(opts.items()): if key == 'logger': continue mod_opts[key] = val return mod_opts def _iter_files(self, mod_name): ''' Iterate over all file_mapping files in order of closeness to mod_name ''' # do we have an exact match? if mod_name in self.file_mapping: yield mod_name # do we have a partial match? for k in self.file_mapping: if mod_name in k: yield k # anyone else? Bueller? for k in self.file_mapping: if mod_name not in k: yield k def _reload_submodules(self, mod): submodules = ( getattr(mod, sname) for sname in dir(mod) if isinstance(getattr(mod, sname), mod.__class__) ) # reload only custom "sub"modules for submodule in submodules: # it is a submodule if the name is in a namespace under mod if submodule.__name__.startswith(mod.__name__ + '.'): reload_module(submodule) self._reload_submodules(submodule) def _load_module(self, name): mod = None fpath, suffix = self.file_mapping[name][:2] self.loaded_files.add(name) fpath_dirname = os.path.dirname(fpath) try: sys.path.append(fpath_dirname) if suffix == '.pyx': mod = pyximport.load_module(name, fpath, tempfile.gettempdir()) elif suffix == '.o': top_mod = __import__(fpath, globals(), locals(), []) comps = fpath.split('.') if len(comps) < 2: mod = top_mod else: mod = top_mod for subname in comps[1:]: mod = getattr(mod, subname) elif suffix == '.zip': mod = zipimporter(fpath).load_module(name) else: desc = self.suffix_map[suffix] # if it is a directory, we don't open a file try: mod_namespace = '.'.join(( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name)) except TypeError: mod_namespace = '{0}.{1}.{2}.{3}'.format( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name) if suffix == '': if USE_IMPORTLIB: # pylint: disable=no-member # Package directory, look for __init__ loader_details = [ (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES), (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES), (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), ] file_finder = importlib.machinery.FileFinder( fpath_dirname, *loader_details ) spec = file_finder.find_spec(mod_namespace) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: mod = imp.load_module(mod_namespace, None, fpath, desc) # reload all submodules if necessary if not self.initial_load: self._reload_submodules(mod) else: if USE_IMPORTLIB: # pylint: disable=no-member loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath) spec = importlib.util.spec_from_file_location( mod_namespace, fpath, loader=loader ) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() #mod = importlib.util.module_from_spec(spec) #spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: with salt.utils.files.fopen(fpath, desc[1]) as fn_: mod = imp.load_module(mod_namespace, fn_, fpath, desc) except IOError: raise except ImportError as exc: if 'magic number' in six.text_type(exc): error_msg = 'Failed to import {0} {1}. Bad magic number. If migrating from Python2 to Python3, remove all .pyc files and try again.'.format(self.tag, name) log.warning(error_msg) self.missing_modules[name] = error_msg log.debug( 'Failed to import %s %s:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = exc return False except Exception as error: log.error( 'Failed to import %s %s, this is due most likely to a ' 'syntax error:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False except SystemExit as error: try: fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1] except Exception: pass else: tgt_fn = os.path.join('salt', 'utils', 'process.py') if fn_.endswith(tgt_fn) and '_handle_signals' in caller: # Race conditon, SIGTERM or SIGINT received while loader # was in process of loading a module. Call sys.exit to # ensure that the process is killed. sys.exit(salt.defaults.exitcodes.EX_OK) log.error( 'Failed to import %s %s as the module called exit()\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False finally: sys.path.remove(fpath_dirname) if hasattr(mod, '__opts__'): mod.__opts__.update(self.opts) else: mod.__opts__ = self.opts # pack whatever other globals we were asked to for p_name, p_value in six.iteritems(self.pack): _inject_into_mod(mod, p_name, p_value) module_name = mod.__name__.rsplit('.', 1)[-1] # Call a module's initialization method if it exists module_init = getattr(mod, '__init__', None) if inspect.isfunction(module_init): try: module_init(self.opts) except TypeError as e: log.error(e) except Exception: err_string = '__init__ failed' log.debug( 'Error loading %s.%s: %s', self.tag, module_name, err_string, exc_info=True ) self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False # if virtual modules are enabled, we need to look for the # __virtual__() function inside that module and run it. if self.virtual_enable: virtual_funcs_to_process = ['__virtual__'] + self.virtual_funcs for virtual_func in virtual_funcs_to_process: virtual_ret, module_name, virtual_err, virtual_aliases = \ self._process_virtual(mod, module_name, virtual_func) if virtual_err is not None: log.trace( 'Error loading %s.%s: %s', self.tag, module_name, virtual_err ) # if _process_virtual returned a non-True value then we are # supposed to not process this module if virtual_ret is not True and module_name not in self.missing_modules: # If a module has information about why it could not be loaded, record it self.missing_modules[module_name] = virtual_err self.missing_modules[name] = virtual_err return False else: virtual_aliases = () # If this is a proxy minion then MOST modules cannot work. Therefore, require that # any module that does work with salt-proxy-minion define __proxyenabled__ as a list # containing the names of the proxy types that the module supports. # # Render modules and state modules are OK though if 'proxy' in self.opts: if self.tag in ['grains', 'proxy']: if not hasattr(mod, '__proxyenabled__') or \ (self.opts['proxy']['proxytype'] not in mod.__proxyenabled__ and '*' not in mod.__proxyenabled__): err_string = 'not a proxy_minion enabled module' self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False if getattr(mod, '__load__', False) is not False: log.info( 'The functions from module \'%s\' are being loaded from the ' 'provided __load__ attribute', module_name ) # If we had another module by the same virtual name, we should put any # new functions under the existing dictionary. mod_names = [module_name] + list(virtual_aliases) mod_dict = dict(( (x, self.loaded_modules.get(x, self.mod_dict_class())) for x in mod_names )) for attr in getattr(mod, '__load__', dir(mod)): if attr.startswith('_') and attr != '__call__': # private functions are skipped, # except __call__ which is default entrance # for multi-function batch-like state syntax continue func = getattr(mod, attr) if not inspect.isfunction(func) and not isinstance(func, functools.partial): # Not a function!? Skip it!!! continue # Let's get the function name. # If the module has the __func_alias__ attribute, it must be a # dictionary mapping in the form of(key -> value): # <real-func-name> -> <desired-func-name> # # It default's of course to the found callable attribute name # if no alias is defined. funcname = getattr(mod, '__func_alias__', {}).get(attr, attr) for tgt_mod in mod_names: try: full_funcname = '.'.join((tgt_mod, funcname)) except TypeError: full_funcname = '{0}.{1}'.format(tgt_mod, funcname) # Save many references for lookups # Careful not to overwrite existing (higher priority) functions if full_funcname not in self._dict: self._dict[full_funcname] = func if funcname not in mod_dict[tgt_mod]: setattr(mod_dict[tgt_mod], funcname, func) mod_dict[tgt_mod][funcname] = func self._apply_outputter(func, mod) # enforce depends try: Depends.enforce_dependencies(self._dict, self.tag) except RuntimeError as exc: log.info( 'Depends.enforce_dependencies() failed for the following ' 'reason: %s', exc ) for tgt_mod in mod_names: self.loaded_modules[tgt_mod] = mod_dict[tgt_mod] return True def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise KeyError('The key \'{0}\' should contain a \'.\''.format(key)) mod_name, _ = key.split('.', 1) with self._lock: # It is possible that the key is in the dictionary after # acquiring the lock due to another thread loading it. if mod_name in self.missing_modules or key in self._dict: return True # if the modulename isn't in the whitelist, don't bother if self.whitelist and mod_name not in self.whitelist: log.error( 'Failed to load function %s because its module (%s) is ' 'not in the whitelist: %s', key, mod_name, self.whitelist ) raise KeyError(key) def _inner_load(mod_name): for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and key in self._dict: return True return False # try to load the module ret = None reloaded = False # re-scan up to once, IOErrors or a failed load cause re-scans of the # filesystem while True: try: ret = _inner_load(mod_name) if not reloaded and ret is not True: self._refresh_file_mapping() reloaded = True continue break except IOError: if not reloaded: self._refresh_file_mapping() reloaded = True continue return ret def _load_all(self): ''' Load all of them ''' with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True def reload_modules(self): with self._lock: self.loaded_files = set() self._load_all() def _apply_outputter(self, func, mod): ''' Apply the __outputter__ variable to the functions ''' if hasattr(mod, '__outputter__'): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__] def _process_virtual(self, mod, module_name, virtual_func='__virtual__'): ''' Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1] ''' # The __virtual__ function will return either a True or False value. # If it returns a True value it can also set a module level attribute # named __virtualname__ with the name that the module should be # referred to as. # # This allows us to have things like the pkg module working on all # platforms under the name 'pkg'. It also allows for modules like # augeas_cfg to be referred to as 'augeas', which would otherwise have # namespace collisions. And finally it allows modules to return False # if they are not intended to run on the given platform or are missing # dependencies. virtual_aliases = getattr(mod, '__virtual_aliases__', tuple()) try: error_reason = None if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__): try: start = time.time() virtual = getattr(mod, virtual_func)() if isinstance(virtual, tuple): error_reason = virtual[1] virtual = virtual[0] if self.opts.get('virtual_timer', False): end = time.time() - start msg = 'Virtual function took {0} seconds for {1}'.format( end, module_name) log.warning(msg) except Exception as exc: error_reason = ( 'Exception raised when processing __virtual__ function' ' for {0}. Module will not be loaded: {1}'.format( mod.__name__, exc)) log.error(error_reason, exc_info_on_loglevel=logging.DEBUG) virtual = None # Get the module's virtual name virtualname = getattr(mod, '__virtualname__', virtual) if not virtual: # if __virtual__() evaluates to False then the module # wasn't meant for this platform or it's not supposed to # load for some other reason. # Some modules might accidentally return None and are # improperly loaded if virtual is None: log.warning( '%s.__virtual__() is wrongly returning `None`. ' 'It should either return `True`, `False` or a new ' 'name. If you\'re the developer of the module ' '\'%s\', please fix this.', mod.__name__, module_name ) return (False, module_name, error_reason, virtual_aliases) # At this point, __virtual__ did not return a # boolean value, let's check for deprecated usage # or module renames if virtual is not True and module_name != virtual: # The module is renaming itself. Updating the module name # with the new name log.trace('Loaded %s as virtual %s', module_name, virtual) if virtualname != virtual: # The __virtualname__ attribute does not match what's # being returned by the __virtual__() function. This # should be considered an error. log.error( 'The module \'%s\' is showing some bad usage. Its ' '__virtualname__ attribute is set to \'%s\' yet the ' '__virtual__() function is returning \'%s\'. These ' 'values should match!', mod.__name__, virtualname, virtual ) module_name = virtualname # If the __virtual__ function returns True and __virtualname__ # is set then use it elif virtual is True and virtualname != module_name: if virtualname is not True: module_name = virtualname except KeyError: # Key errors come out of the virtual function when passing # in incomplete grains sets, these can be safely ignored # and logged to debug, still, it includes the traceback to # help debugging. log.debug('KeyError when loading %s', module_name, exc_info=True) except Exception: # If the module throws an exception during __virtual__() # then log the information and continue to the next. log.error( 'Failed to read the virtual function for %s: %s', self.tag, module_name, exc_info=True ) return (False, module_name, error_reason, virtual_aliases) return (True, module_name, None, virtual_aliases) def global_injector_decorator(inject_globals): ''' Decorator used by the LazyLoader to inject globals into a function at execute time. globals Dictionary with global variables to inject ''' def inner_decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): with salt.utils.context.func_globals_inject(f, **inject_globals): return f(*args, **kwargs) return wrapper return inner_decorator
saltstack/salt
salt/loader.py
cache
python
def cache(opts, serial): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'cache', 'cache'), opts, tag='cache', pack={'__opts__': opts, '__context__': {'serial': serial}}, )
Returns the returner modules
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L1067-L1076
null
# -*- coding: utf-8 -*- ''' The Salt loader is the core to Salt's plugin system, the loader scans directories for python loadable code and organizes the code into the plugin interfaces used by Salt. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import sys import time import logging import inspect import tempfile import threading import functools import threading import traceback import types from zipimport import zipimporter # Import salt libs import salt.config import salt.defaults.events import salt.defaults.exitcodes import salt.syspaths import salt.utils.args import salt.utils.context import salt.utils.data import salt.utils.dictupdate import salt.utils.event import salt.utils.files import salt.utils.lazy import salt.utils.odict import salt.utils.platform import salt.utils.versions import salt.utils.stringutils from salt.exceptions import LoaderError from salt.template import check_render_pipe_str from salt.utils.decorators import Depends from salt.utils.thread_local_proxy import ThreadLocalProxy # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import reload_module if sys.version_info[:2] >= (3, 5): import importlib.machinery # pylint: disable=no-name-in-module,import-error import importlib.util # pylint: disable=no-name-in-module,import-error USE_IMPORTLIB = True else: import imp USE_IMPORTLIB = False try: from collections.abc import MutableMapping except ImportError: from collections import MutableMapping try: import pkg_resources HAS_PKG_RESOURCES = True except ImportError: HAS_PKG_RESOURCES = False log = logging.getLogger(__name__) SALT_BASE_PATH = os.path.abspath(salt.syspaths.INSTALL_DIR) LOADED_BASE_NAME = 'salt.loaded' if USE_IMPORTLIB: # pylint: disable=no-member MODULE_KIND_SOURCE = 1 MODULE_KIND_COMPILED = 2 MODULE_KIND_EXTENSION = 3 MODULE_KIND_PKG_DIRECTORY = 5 SUFFIXES = [] for suffix in importlib.machinery.EXTENSION_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_EXTENSION)) for suffix in importlib.machinery.SOURCE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_SOURCE)) for suffix in importlib.machinery.BYTECODE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_COMPILED)) MODULE_KIND_MAP = { MODULE_KIND_SOURCE: importlib.machinery.SourceFileLoader, MODULE_KIND_COMPILED: importlib.machinery.SourcelessFileLoader, MODULE_KIND_EXTENSION: importlib.machinery.ExtensionFileLoader } # pylint: enable=no-member else: SUFFIXES = imp.get_suffixes() PY3_PRE_EXT = \ re.compile(r'\.cpython-{0}{1}(\.opt-[1-9])?'.format(*sys.version_info[:2])) # Because on the cloud drivers we do `from salt.cloud.libcloudfuncs import *` # which simplifies code readability, it adds some unsupported functions into # the driver's module scope. # We list un-supported functions here. These will be removed from the loaded. # TODO: remove the need for this cross-module code. Maybe use NotImplemented LIBCLOUD_FUNCS_NOT_SUPPORTED = ( 'parallels.avail_sizes', 'parallels.avail_locations', 'proxmox.avail_sizes', ) # Will be set to pyximport module at runtime if cython is enabled in config. pyximport = None def static_loader( opts, ext_type, tag, pack=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, filter_name=None, ): funcs = LazyLoader( _module_dirs( opts, ext_type, tag, int_type, ext_dirs, ext_type_dirs, base_path, ), opts, tag=tag, pack=pack, ) ret = {} funcs._load_all() if filter_name: funcs = FilterDictWrapper(funcs, filter_name) for key in funcs: ret[key] = funcs[key] return ret def _format_entrypoint_target(ep): ''' Makes a string describing the target of an EntryPoint object. Base strongly on EntryPoint.__str__(). ''' s = ep.module_name if ep.attrs: s += ':' + '.'.join(ep.attrs) return s def _module_dirs( opts, ext_type, tag=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, ): if tag is None: tag = ext_type sys_types = os.path.join(base_path or SALT_BASE_PATH, int_type or ext_type) ext_types = os.path.join(opts['extension_modules'], ext_type) ext_type_types = [] if ext_dirs: if ext_type_dirs is None: ext_type_dirs = '{0}_dirs'.format(tag) if ext_type_dirs in opts: ext_type_types.extend(opts[ext_type_dirs]) if HAS_PKG_RESOURCES and ext_type_dirs: for entry_point in pkg_resources.iter_entry_points('salt.loader', ext_type_dirs): try: loaded_entry_point = entry_point.load() for path in loaded_entry_point(): ext_type_types.append(path) except Exception as exc: log.error("Error getting module directories from %s: %s", _format_entrypoint_target(entry_point), exc) log.debug("Full backtrace for module directories error", exc_info=True) cli_module_dirs = [] # The dirs can be any module dir, or a in-tree _{ext_type} dir for _dir in opts.get('module_dirs', []): # Prepend to the list to match cli argument ordering maybe_dir = os.path.join(_dir, ext_type) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) continue maybe_dir = os.path.join(_dir, '_{0}'.format(ext_type)) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) return cli_module_dirs + ext_type_types + [ext_types, sys_types] def minion_mods( opts, context=None, utils=None, whitelist=None, initial_load=False, loaded_base_name=None, notify=False, static_modules=None, proxy=None): ''' Load execution modules Returns a dictionary of execution modules appropriate for the current system by evaluating the __virtual__() function in each module. :param dict opts: The Salt options dictionary :param dict context: A Salt context that should be made present inside generated modules in __context__ :param dict utils: Utility functions which should be made available to Salt modules in __utils__. See `utils_dirs` in salt.config for additional information about configuration. :param list whitelist: A list of modules which should be whitelisted. :param bool initial_load: Deprecated flag! Unused. :param str loaded_base_name: A string marker for the loaded base name. :param bool notify: Flag indicating that an event should be fired upon completion of module loading. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) __opts__['grains'] = __grains__ __utils__ = salt.loader.utils(__opts__) __salt__ = salt.loader.minion_mods(__opts__, utils=__utils__) __salt__['test.ping']() ''' # TODO Publish documentation for module whitelisting if not whitelist: whitelist = opts.get('whitelist_modules', None) ret = LazyLoader( _module_dirs(opts, 'modules', 'module'), opts, tag='module', pack={'__context__': context, '__utils__': utils, '__proxy__': proxy}, whitelist=whitelist, loaded_base_name=loaded_base_name, static_modules=static_modules, ) ret.pack['__salt__'] = ret # Load any provider overrides from the configuration file providers option # Note: Providers can be pkg, service, user or group - not to be confused # with cloud providers. providers = opts.get('providers', False) if providers and isinstance(providers, dict): for mod in providers: # sometimes providers opts is not to diverge modules but # for other configuration try: funcs = raw_mod(opts, providers[mod], ret) except TypeError: break else: if funcs: for func in funcs: f_key = '{0}{1}'.format(mod, func[func.rindex('.'):]) ret[f_key] = funcs[func] if notify: evt = salt.utils.event.get_event('minion', opts=opts, listen=False) evt.fire_event({'complete': True}, tag=salt.defaults.events.MINION_MOD_COMPLETE) return ret def raw_mod(opts, name, functions, mod='modules'): ''' Returns a single module loaded raw and bypassing the __virtual__ function .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') testmod = salt.loader.raw_mod(__opts__, 'test', None) testmod['test.ping']() ''' loader = LazyLoader( _module_dirs(opts, mod, 'module'), opts, tag='rawmodule', virtual_enable=False, pack={'__salt__': functions}, ) # if we don't have the module, return an empty dict if name not in loader.file_mapping: return {} loader._load_module(name) # load a single module (the one passed in) return dict(loader._dict) # return a copy of *just* the funcs for `name` def metaproxy(opts): ''' Return functions used in the meta proxy ''' return LazyLoader( _module_dirs(opts, 'metaproxy'), opts, tag='metaproxy' ) def matchers(opts): ''' Return the matcher services plugins ''' return LazyLoader( _module_dirs(opts, 'matchers'), opts, tag='matchers' ) def engines(opts, functions, runners, utils, proxy=None): ''' Return the master services plugins ''' pack = {'__salt__': functions, '__runners__': runners, '__proxy__': proxy, '__utils__': utils} return LazyLoader( _module_dirs(opts, 'engines'), opts, tag='engines', pack=pack, ) def proxy(opts, functions=None, returners=None, whitelist=None, utils=None): ''' Returns the proxy module for this salt-proxy-minion ''' ret = LazyLoader( _module_dirs(opts, 'proxy'), opts, tag='proxy', pack={'__salt__': functions, '__ret__': returners, '__utils__': utils}, ) ret.pack['__proxy__'] = ret return ret def returners(opts, functions, whitelist=None, context=None, proxy=None): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'returners', 'returner'), opts, tag='returner', whitelist=whitelist, pack={'__salt__': functions, '__context__': context, '__proxy__': proxy or {}}, ) def utils(opts, whitelist=None, context=None, proxy=proxy): ''' Returns the utility modules ''' return LazyLoader( _module_dirs(opts, 'utils', ext_type_dirs='utils_dirs'), opts, tag='utils', whitelist=whitelist, pack={'__context__': context, '__proxy__': proxy or {}}, ) def pillars(opts, functions, context=None): ''' Returns the pillars modules ''' ret = LazyLoader(_module_dirs(opts, 'pillar'), opts, tag='pillar', pack={'__salt__': functions, '__context__': context, '__utils__': utils(opts)}) ret.pack['__ext_pillar__'] = ret return FilterDictWrapper(ret, '.ext_pillar') def tops(opts): ''' Returns the tops modules ''' if 'master_tops' not in opts: return {} whitelist = list(opts['master_tops'].keys()) ret = LazyLoader( _module_dirs(opts, 'tops', 'top'), opts, tag='top', whitelist=whitelist, ) return FilterDictWrapper(ret, '.top') def wheels(opts, whitelist=None, context=None): ''' Returns the wheels modules ''' if context is None: context = {} return LazyLoader( _module_dirs(opts, 'wheel'), opts, tag='wheel', whitelist=whitelist, pack={'__context__': context}, ) def outputters(opts): ''' Returns the outputters modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only outputters present in the keyspace ''' ret = LazyLoader( _module_dirs(opts, 'output', ext_type_dirs='outputter_dirs'), opts, tag='output', ) wrapped_ret = FilterDictWrapper(ret, '.output') # TODO: this name seems terrible... __salt__ should always be execution mods ret.pack['__salt__'] = wrapped_ret return wrapped_ret def serializers(opts): ''' Returns the serializers modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only serializers present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'serializers'), opts, tag='serializers', ) def eauth_tokens(opts): ''' Returns the tokens modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only token backends present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'tokens'), opts, tag='tokens', ) def auth(opts, whitelist=None): ''' Returns the auth modules :param dict opts: The Salt options dictionary :returns: LazyLoader ''' return LazyLoader( _module_dirs(opts, 'auth'), opts, tag='auth', whitelist=whitelist, pack={'__salt__': minion_mods(opts)}, ) def fileserver(opts, backends): ''' Returns the file server modules ''' return LazyLoader(_module_dirs(opts, 'fileserver'), opts, tag='fileserver', whitelist=backends, pack={'__utils__': utils(opts)}) def roster(opts, runner=None, utils=None, whitelist=None): ''' Returns the roster modules ''' return LazyLoader( _module_dirs(opts, 'roster'), opts, tag='roster', whitelist=whitelist, pack={ '__runner__': runner, '__utils__': utils, }, ) def thorium(opts, functions, runners): ''' Load the thorium runtime modules ''' pack = {'__salt__': functions, '__runner__': runners, '__context__': {}} ret = LazyLoader(_module_dirs(opts, 'thorium'), opts, tag='thorium', pack=pack) ret.pack['__thorium__'] = ret return ret def states(opts, functions, utils, serializers, whitelist=None, proxy=None, context=None): ''' Returns the state modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') statemods = salt.loader.states(__opts__, None, None) ''' if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'states'), opts, tag='states', pack={'__salt__': functions, '__proxy__': proxy or {}}, whitelist=whitelist, ) ret.pack['__states__'] = ret ret.pack['__utils__'] = utils ret.pack['__serializers__'] = serializers ret.pack['__context__'] = context return ret def beacons(opts, functions, context=None, proxy=None): ''' Load the beacon modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. ''' return LazyLoader( _module_dirs(opts, 'beacons'), opts, tag='beacons', pack={'__context__': context, '__salt__': functions, '__proxy__': proxy or {}}, virtual_funcs=[], ) def log_handlers(opts): ''' Returns the custom logging handler modules :param dict opts: The Salt options dictionary ''' ret = LazyLoader( _module_dirs( opts, 'log_handlers', int_type='handlers', base_path=os.path.join(SALT_BASE_PATH, 'log'), ), opts, tag='log_handlers', ) return FilterDictWrapper(ret, '.setup_handlers') def ssh_wrapper(opts, functions=None, context=None): ''' Returns the custom logging handler modules ''' return LazyLoader( _module_dirs( opts, 'wrapper', base_path=os.path.join(SALT_BASE_PATH, os.path.join('client', 'ssh')), ), opts, tag='wrapper', pack={ '__salt__': functions, '__grains__': opts.get('grains', {}), '__pillar__': opts.get('pillar', {}), '__context__': context, }, ) def render(opts, functions, states=None, proxy=None, context=None): ''' Returns the render modules ''' if context is None: context = {} pack = {'__salt__': functions, '__grains__': opts.get('grains', {}), '__context__': context} if states: pack['__states__'] = states pack['__proxy__'] = proxy or {} ret = LazyLoader( _module_dirs( opts, 'renderers', 'render', ext_type_dirs='render_dirs', ), opts, tag='render', pack=pack, ) rend = FilterDictWrapper(ret, '.render') if not check_render_pipe_str(opts['renderer'], rend, opts['renderer_blacklist'], opts['renderer_whitelist']): err = ('The renderer {0} is unavailable, this error is often because ' 'the needed software is unavailable'.format(opts['renderer'])) log.critical(err) raise LoaderError(err) return rend def grain_funcs(opts, proxy=None): ''' Returns the grain functions .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') grainfuncs = salt.loader.grain_funcs(__opts__) ''' ret = LazyLoader( _module_dirs( opts, 'grains', 'grain', ext_type_dirs='grains_dirs', ), opts, tag='grains', ) ret.pack['__utils__'] = utils(opts, proxy=proxy) return ret def _load_cached_grains(opts, cfn): ''' Returns the grains cached in cfn, or None if the cache is too old or is corrupted. ''' if not os.path.isfile(cfn): log.debug('Grains cache file does not exist.') return None grains_cache_age = int(time.time() - os.path.getmtime(cfn)) if grains_cache_age > opts.get('grains_cache_expiration', 300): log.debug( 'Grains cache last modified %s seconds ago and cache ' 'expiration is set to %s. Grains cache expired. ' 'Refreshing.', grains_cache_age, opts.get('grains_cache_expiration', 300) ) return None if opts.get('refresh_grains_cache', False): log.debug('refresh_grains_cache requested, Refreshing.') return None log.debug('Retrieving grains from cache') try: serial = salt.payload.Serial(opts) with salt.utils.files.fopen(cfn, 'rb') as fp_: cached_grains = salt.utils.data.decode(serial.load(fp_), preserve_tuples=True) if not cached_grains: log.debug('Cached grains are empty, cache might be corrupted. Refreshing.') return None return cached_grains except (IOError, OSError): return None def grains(opts, force_refresh=False, proxy=None): ''' Return the functions for the dynamic grains and the values for the static grains. Since grains are computed early in the startup process, grains functions do not have __salt__ or __proxy__ available. At proxy-minion startup, this function is called with the proxymodule LazyLoader object so grains functions can communicate with their controlled device. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) print __grains__['id'] ''' # Need to re-import salt.config, somehow it got lost when a minion is starting import salt.config # if we have no grains, lets try loading from disk (TODO: move to decorator?) cfn = os.path.join( opts['cachedir'], 'grains.cache.p' ) if not force_refresh and opts.get('grains_cache', False): cached_grains = _load_cached_grains(opts, cfn) if cached_grains: return cached_grains else: log.debug('Grains refresh requested. Refreshing grains.') if opts.get('skip_grains', False): return {} grains_deep_merge = opts.get('grains_deep_merge', False) is True if 'conf_file' in opts: pre_opts = {} pre_opts.update(salt.config.load_config( opts['conf_file'], 'SALT_MINION_CONFIG', salt.config.DEFAULT_MINION_OPTS['conf_file'] )) default_include = pre_opts.get( 'default_include', opts['default_include'] ) include = pre_opts.get('include', []) pre_opts.update(salt.config.include_config( default_include, opts['conf_file'], verbose=False )) pre_opts.update(salt.config.include_config( include, opts['conf_file'], verbose=True )) if 'grains' in pre_opts: opts['grains'] = pre_opts['grains'] else: opts['grains'] = {} else: opts['grains'] = {} grains_data = {} blist = opts.get('grains_blacklist', []) funcs = grain_funcs(opts, proxy=proxy) if force_refresh: # if we refresh, lets reload grain modules funcs.clear() # Run core grains for key in funcs: if not key.startswith('core.'): continue log.trace('Loading %s grain', key) ret = funcs[key]() if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) # Run the rest of the grains for key in funcs: if key.startswith('core.') or key == '_errors': continue try: # Grains are loaded too early to take advantage of the injected # __proxy__ variable. Pass an instance of that LazyLoader # here instead to grains functions if the grains functions take # one parameter. Then the grains can have access to the # proxymodule for retrieving information from the connected # device. log.trace('Loading %s grain', key) parameters = salt.utils.args.get_function_argspec(funcs[key]).args kwargs = {} if 'proxy' in parameters: kwargs['proxy'] = proxy if 'grains' in parameters: kwargs['grains'] = grains_data ret = funcs[key](**kwargs) except Exception: if salt.utils.platform.is_proxy(): log.info('The following CRITICAL message may not be an error; the proxy may not be completely established yet.') log.critical( 'Failed to load grains defined in grain file %s in ' 'function %s, error:\n', key, funcs[key], exc_info=True ) continue if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) if opts.get('proxy_merge_grains_in_module', True) and proxy: try: proxytype = proxy.opts['proxy']['proxytype'] if proxytype + '.grains' in proxy: if proxytype + '.initialized' in proxy and proxy[proxytype + '.initialized'](): try: proxytype = proxy.opts['proxy']['proxytype'] ret = proxy[proxytype + '.grains']() if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) except Exception: log.critical('Failed to run proxy\'s grains function!', exc_info=True ) except KeyError: pass grains_data.update(opts['grains']) # Write cache if enabled if opts.get('grains_cache', False): with salt.utils.files.set_umask(0o077): try: if salt.utils.platform.is_windows(): # Late import import salt.modules.cmdmod # Make sure cache file isn't read-only salt.modules.cmdmod._run_quiet('attrib -R "{0}"'.format(cfn)) with salt.utils.files.fopen(cfn, 'w+b') as fp_: try: serial = salt.payload.Serial(opts) serial.dump(grains_data, fp_) except TypeError as e: log.error('Failed to serialize grains cache: %s', e) raise # re-throw for cleanup except Exception as e: log.error('Unable to write to grains cache file %s: %s', cfn, e) # Based on the original exception, the file may or may not have been # created. If it was, we will remove it now, as the exception means # the serialized data is not to be trusted, no matter what the # exception is. if os.path.isfile(cfn): os.unlink(cfn) if grains_deep_merge: salt.utils.dictupdate.update(grains_data, opts['grains']) else: grains_data.update(opts['grains']) return salt.utils.data.decode(grains_data, preserve_tuples=True) # TODO: get rid of? Does anyone use this? You should use raw() instead def call(fun, **kwargs): ''' Directly call a function inside a loader directory ''' args = kwargs.get('args', []) dirs = kwargs.get('dirs', []) funcs = LazyLoader( [os.path.join(SALT_BASE_PATH, 'modules')] + dirs, None, tag='modules', virtual_enable=False, ) return funcs[fun](*args) def runner(opts, utils=None, context=None, whitelist=None): ''' Directly call a function inside a loader directory ''' if utils is None: utils = {} if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'runners', 'runner', ext_type_dirs='runner_dirs'), opts, tag='runners', pack={'__utils__': utils, '__context__': context}, whitelist=whitelist, ) # TODO: change from __salt__ to something else, we overload __salt__ too much ret.pack['__salt__'] = ret return ret def queues(opts): ''' Directly call a function inside a loader directory ''' return LazyLoader( _module_dirs(opts, 'queues', 'queue', ext_type_dirs='queue_dirs'), opts, tag='queues', ) def sdb(opts, functions=None, whitelist=None, utils=None): ''' Make a very small database call ''' if utils is None: utils = {} return LazyLoader( _module_dirs(opts, 'sdb'), opts, tag='sdb', pack={ '__sdb__': functions, '__opts__': opts, '__utils__': utils, '__salt__': minion_mods(opts, utils), }, whitelist=whitelist, ) def pkgdb(opts): ''' Return modules for SPM's package database .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgdb', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgdb' ) def pkgfiles(opts): ''' Return modules for SPM's file handling .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgfiles', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgfiles' ) def clouds(opts): ''' Return the cloud functions ''' # Let's bring __active_provider_name__, defaulting to None, to all cloud # drivers. This will get temporarily updated/overridden with a context # manager when needed. functions = LazyLoader( _module_dirs(opts, 'clouds', 'cloud', base_path=os.path.join(SALT_BASE_PATH, 'cloud'), int_type='clouds'), opts, tag='clouds', pack={'__utils__': salt.loader.utils(opts), '__active_provider_name__': None}, ) for funcname in LIBCLOUD_FUNCS_NOT_SUPPORTED: log.trace( '\'%s\' has been marked as not supported. Removing from the ' 'list of supported cloud functions', funcname ) functions.pop(funcname, None) return functions def netapi(opts): ''' Return the network api functions ''' return LazyLoader( _module_dirs(opts, 'netapi'), opts, tag='netapi', ) def executors(opts, functions=None, context=None, proxy=None): ''' Returns the executor modules ''' executors = LazyLoader( _module_dirs(opts, 'executors', 'executor'), opts, tag='executor', pack={'__salt__': functions, '__context__': context or {}, '__proxy__': proxy or {}}, ) executors.pack['__executors__'] = executors return executors def _generate_module(name): if name in sys.modules: return code = "'''Salt loaded {0} parent module'''".format(name.split('.')[-1]) # ModuleType can't accept a unicode type on PY2 module = types.ModuleType(str(name)) # future lint: disable=blacklisted-function exec(code, module.__dict__) sys.modules[name] = module def _mod_type(module_path): if module_path.startswith(SALT_BASE_PATH): return 'int' return 'ext' def _inject_into_mod(mod, name, value, force_lock=False): ''' Inject a variable into a module. This is used to inject "globals" like ``__salt__``, ``__pillar``, or ``grains``. Instead of injecting the value directly, a ``ThreadLocalProxy`` is created. If such a proxy is already present under the specified name, it is updated with the new value. This update only affects the current thread, so that the same name can refer to different values depending on the thread of execution. This is important for data that is not truly global. For example, pillar data might be dynamically overriden through function parameters and thus the actual values available in pillar might depend on the thread that is calling a module. mod: module object into which the value is going to be injected. name: name of the variable that is injected into the module. value: value that is injected into the variable. The value is not injected directly, but instead set as the new reference of the proxy that has been created for the variable. force_lock: whether the lock should be acquired before checking whether a proxy object for the specified name has already been injected into the module. If ``False`` (the default), this function checks for the module's variable without acquiring the lock and only acquires the lock if a new proxy has to be created and injected. ''' old_value = getattr(mod, name, None) # We use a double-checked locking scheme in order to avoid taking the lock # when a proxy object has already been injected. # In most programming languages, double-checked locking is considered # unsafe when used without explicit memory barriers because one might read # an uninitialized value. In CPython it is safe due to the global # interpreter lock (GIL). In Python implementations that do not have the # GIL, it could be unsafe, but at least Jython also guarantees that (for # Python objects) memory is not corrupted when writing and reading without # explicit synchronization # (http://www.jython.org/jythonbook/en/1.0/Concurrency.html). # Please note that in order to make this code safe in a runtime environment # that does not make this guarantees, it is not sufficient. The # ThreadLocalProxy must also be created with fallback_to_shared set to # False or a lock must be added to the ThreadLocalProxy. if force_lock: with _inject_into_mod.lock: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: setattr(mod, name, ThreadLocalProxy(value, True)) else: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: _inject_into_mod(mod, name, value, True) # Lock used when injecting globals. This is needed to avoid a race condition # when two threads try to load the same module concurrently. This must be # outside the loader because there might be more than one loader for the same # namespace. _inject_into_mod.lock = threading.RLock() # TODO: move somewhere else? class FilterDictWrapper(MutableMapping): ''' Create a dict which wraps another dict with a specific key suffix on get This is to replace "filter_load" ''' def __init__(self, d, suffix): self._dict = d self.suffix = suffix def __setitem__(self, key, val): self._dict[key] = val def __delitem__(self, key): del self._dict[key] def __getitem__(self, key): return self._dict[key + self.suffix] def __len__(self): return len(self._dict) def __iter__(self): for key in self._dict: if key.endswith(self.suffix): yield key.replace(self.suffix, '') class LazyLoader(salt.utils.lazy.LazyDict): ''' A pseduo-dictionary which has a set of keys which are the name of the module and function, delimited by a dot. When the value of the key is accessed, the function is then loaded from disk and into memory. .. note:: Iterating over keys will cause all modules to be loaded. :param list module_dirs: A list of directories on disk to search for modules :param dict opts: The salt options dictionary. :param str tag: The tag for the type of module to load :param func mod_type_check: A function which can be used to verify files :param dict pack: A dictionary of function to be packed into modules as they are loaded :param list whitelist: A list of modules to whitelist :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules. :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality. If not true, the module will not load. :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values are function references themselves which are loaded on-demand. # TODO: - move modules_max_memory into here - singletons (per tag) ''' mod_dict_class = salt.utils.odict.OrderedDict def __init__(self, module_dirs, opts=None, tag='module', loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, proxy=None, virtual_funcs=None, ): # pylint: disable=W0231 ''' In pack, if any of the values are None they will be replaced with an empty context-specific dict ''' self.inject_globals = {} self.pack = {} if pack is None else pack if opts is None: opts = {} threadsafety = not opts.get('multiprocessing') self.context_dict = salt.utils.context.ContextDict(threadsafe=threadsafety) self.opts = self.__prep_mod_opts(opts) self.module_dirs = module_dirs self.tag = tag self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME self.mod_type_check = mod_type_check or _mod_type if '__context__' not in self.pack: self.pack['__context__'] = None for k, v in six.iteritems(self.pack): if v is None: # if the value of a pack is None, lets make an empty dict value = self.context_dict.get(k, {}) if isinstance(value, ThreadLocalProxy): value = ThreadLocalProxy.unproxy(value) self.context_dict[k] = value self.pack[k] = salt.utils.context.NamespacedDictWrapper(self.context_dict, k) self.whitelist = whitelist self.virtual_enable = virtual_enable self.initial_load = True # names of modules that we don't have (errors, __virtual__, etc.) self.missing_modules = {} # mapping of name -> error self.loaded_modules = {} # mapping of module_name -> dict_of_functions self.loaded_files = set() # TODO: just remove them from file_mapping? self.static_modules = static_modules if static_modules else [] if virtual_funcs is None: virtual_funcs = [] self.virtual_funcs = virtual_funcs self.disabled = set( self.opts.get( 'disable_{0}{1}'.format( self.tag, '' if self.tag[-1] == 's' else 's' ), [] ) ) # A map of suffix to description for imp self.suffix_map = {} # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [''] for (suffix, mode, kind) in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) self._lock = threading.RLock() self._refresh_file_mapping() super(LazyLoader, self).__init__() # late init the lazy loader # create all of the import namespaces _generate_module('{0}.int'.format(self.loaded_base_name)) _generate_module('{0}.int.{1}'.format(self.loaded_base_name, tag)) _generate_module('{0}.ext'.format(self.loaded_base_name)) _generate_module('{0}.ext.{1}'.format(self.loaded_base_name, tag)) def __getitem__(self, item): ''' Override the __getitem__ in order to decorate the returned function if we need to last-minute inject globals ''' func = super(LazyLoader, self).__getitem__(item) if self.inject_globals: return global_injector_decorator(self.inject_globals)(func) else: return func def __getattr__(self, mod_name): ''' Allow for "direct" attribute access-- this allows jinja templates to access things like `salt.test.ping()` ''' if mod_name in ('__getstate__', '__setstate__'): return object.__getattribute__(self, mod_name) # if we have an attribute named that, lets return it. try: return object.__getattr__(self, mod_name) # pylint: disable=no-member except AttributeError: pass # otherwise we assume its jinja template access if mod_name not in self.loaded_modules and not self.loaded: for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and mod_name in self.loaded_modules: break if mod_name in self.loaded_modules: return self.loaded_modules[mod_name] else: raise AttributeError(mod_name) def missing_fun_string(self, function_name): ''' Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ''' mod_name = function_name.split('.')[0] if mod_name in self.loaded_modules: return '\'{0}\' is not available.'.format(function_name) else: try: reason = self.missing_modules[mod_name] except KeyError: return '\'{0}\' is not available.'.format(function_name) else: if reason is not None: return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason) else: return '\'{0}\' __virtual__ returned False'.format(mod_name) def _refresh_file_mapping(self): ''' refresh the mapping of the FS on disk ''' # map of suffix to description for imp if self.opts.get('cython_enable', True) is True: try: global pyximport pyximport = __import__('pyximport') # pylint: disable=import-error pyximport.install() # add to suffix_map so file_mapping will pick it up self.suffix_map['.pyx'] = tuple() except ImportError: log.info('Cython is enabled in the options but not present ' 'in the system path. Skipping Cython modules.') # Allow for zipimport of modules if self.opts.get('enable_zip_modules', True) is True: self.suffix_map['.zip'] = tuple() # allow for module dirs if USE_IMPORTLIB: self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY) else: self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY) # create mapping of filename (without suffix) to (path, suffix) # The files are added in order of priority, so order *must* be retained. self.file_mapping = salt.utils.odict.OrderedDict() opt_match = [] def _replace_pre_ext(obj): ''' Hack so we can get the optimization level that we replaced (if any) out of the re.sub call below. We use a list here because it is a persistent data structure that we will be able to access after re.sub is called. ''' opt_match.append(obj) return '' for mod_dir in self.module_dirs: try: # Make sure we have a sorted listdir in order to have # expectable override results files = sorted( x for x in os.listdir(mod_dir) if x != '__pycache__' ) except OSError: continue # Next mod_dir if six.PY3: try: pycache_files = [ os.path.join('__pycache__', x) for x in sorted(os.listdir(os.path.join(mod_dir, '__pycache__'))) ] except OSError: pass else: files.extend(pycache_files) for filename in files: try: dirname, basename = os.path.split(filename) if basename.startswith('_'): # skip private modules # log messages omitted for obviousness continue # Next filename f_noext, ext = os.path.splitext(basename) if six.PY3: f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext) try: opt_level = int( opt_match.pop().group(1).rsplit('-', 1)[-1] ) except (AttributeError, IndexError, ValueError): # No regex match or no optimization level matched opt_level = 0 try: opt_index = self.opts['optimization_order'].index(opt_level) except KeyError: log.trace( 'Disallowed optimization level %d for module ' 'name \'%s\', skipping. Add %d to the ' '\'optimization_order\' config option if you ' 'do not want to ignore this optimization ' 'level.', opt_level, f_noext, opt_level ) continue else: # Optimization level not reflected in filename on PY2 opt_index = 0 # make sure it is a suffix we support if ext not in self.suffix_map: continue # Next filename if f_noext in self.disabled: log.trace( 'Skipping %s, it is disabled by configuration', filename ) continue # Next filename fpath = os.path.join(mod_dir, filename) # if its a directory, lets allow us to load that if ext == '': # is there something __init__? subfiles = os.listdir(fpath) for suffix in self.suffix_order: if '' == suffix: continue # Next suffix (__init__ must have a suffix) init_file = '__init__{0}'.format(suffix) if init_file in subfiles: break else: continue # Next filename try: curr_ext = self.file_mapping[f_noext][1] curr_opt_index = self.file_mapping[f_noext][2] except KeyError: pass else: if '' in (curr_ext, ext) and curr_ext != ext: log.error( 'Module/package collision: \'%s\' and \'%s\'', fpath, self.file_mapping[f_noext][0] ) if six.PY3 and ext == '.pyc' and curr_ext == '.pyc': # Check the optimization level if opt_index >= curr_opt_index: # Module name match, but a higher-priority # optimization level was already matched, skipping. continue elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext): # Match found but a higher-priorty match already # exists, so skip this. continue if six.PY3 and not dirname and ext == '.pyc': # On Python 3, we should only load .pyc files from the # __pycache__ subdirectory (i.e. when dirname is not an # empty string). continue # Made it this far - add it self.file_mapping[f_noext] = (fpath, ext, opt_index) except OSError: continue for smod in self.static_modules: f_noext = smod.split('.')[-1] self.file_mapping[f_noext] = (smod, '.o', 0) def clear(self): ''' Clear the dict ''' with self._lock: super(LazyLoader, self).clear() # clear the lazy loader self.loaded_files = set() self.missing_modules = {} self.loaded_modules = {} # if we have been loaded before, lets clear the file mapping since # we obviously want a re-do if hasattr(self, 'opts'): self._refresh_file_mapping() self.initial_load = False def __prep_mod_opts(self, opts): ''' Strip out of the opts any logger instance ''' if '__grains__' not in self.pack: grains = opts.get('grains', {}) if isinstance(grains, ThreadLocalProxy): grains = ThreadLocalProxy.unproxy(grains) self.context_dict['grains'] = grains self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains') if '__pillar__' not in self.pack: pillar = opts.get('pillar', {}) if isinstance(pillar, ThreadLocalProxy): pillar = ThreadLocalProxy.unproxy(pillar) self.context_dict['pillar'] = pillar self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar') mod_opts = {} for key, val in list(opts.items()): if key == 'logger': continue mod_opts[key] = val return mod_opts def _iter_files(self, mod_name): ''' Iterate over all file_mapping files in order of closeness to mod_name ''' # do we have an exact match? if mod_name in self.file_mapping: yield mod_name # do we have a partial match? for k in self.file_mapping: if mod_name in k: yield k # anyone else? Bueller? for k in self.file_mapping: if mod_name not in k: yield k def _reload_submodules(self, mod): submodules = ( getattr(mod, sname) for sname in dir(mod) if isinstance(getattr(mod, sname), mod.__class__) ) # reload only custom "sub"modules for submodule in submodules: # it is a submodule if the name is in a namespace under mod if submodule.__name__.startswith(mod.__name__ + '.'): reload_module(submodule) self._reload_submodules(submodule) def _load_module(self, name): mod = None fpath, suffix = self.file_mapping[name][:2] self.loaded_files.add(name) fpath_dirname = os.path.dirname(fpath) try: sys.path.append(fpath_dirname) if suffix == '.pyx': mod = pyximport.load_module(name, fpath, tempfile.gettempdir()) elif suffix == '.o': top_mod = __import__(fpath, globals(), locals(), []) comps = fpath.split('.') if len(comps) < 2: mod = top_mod else: mod = top_mod for subname in comps[1:]: mod = getattr(mod, subname) elif suffix == '.zip': mod = zipimporter(fpath).load_module(name) else: desc = self.suffix_map[suffix] # if it is a directory, we don't open a file try: mod_namespace = '.'.join(( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name)) except TypeError: mod_namespace = '{0}.{1}.{2}.{3}'.format( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name) if suffix == '': if USE_IMPORTLIB: # pylint: disable=no-member # Package directory, look for __init__ loader_details = [ (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES), (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES), (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), ] file_finder = importlib.machinery.FileFinder( fpath_dirname, *loader_details ) spec = file_finder.find_spec(mod_namespace) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: mod = imp.load_module(mod_namespace, None, fpath, desc) # reload all submodules if necessary if not self.initial_load: self._reload_submodules(mod) else: if USE_IMPORTLIB: # pylint: disable=no-member loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath) spec = importlib.util.spec_from_file_location( mod_namespace, fpath, loader=loader ) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() #mod = importlib.util.module_from_spec(spec) #spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: with salt.utils.files.fopen(fpath, desc[1]) as fn_: mod = imp.load_module(mod_namespace, fn_, fpath, desc) except IOError: raise except ImportError as exc: if 'magic number' in six.text_type(exc): error_msg = 'Failed to import {0} {1}. Bad magic number. If migrating from Python2 to Python3, remove all .pyc files and try again.'.format(self.tag, name) log.warning(error_msg) self.missing_modules[name] = error_msg log.debug( 'Failed to import %s %s:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = exc return False except Exception as error: log.error( 'Failed to import %s %s, this is due most likely to a ' 'syntax error:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False except SystemExit as error: try: fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1] except Exception: pass else: tgt_fn = os.path.join('salt', 'utils', 'process.py') if fn_.endswith(tgt_fn) and '_handle_signals' in caller: # Race conditon, SIGTERM or SIGINT received while loader # was in process of loading a module. Call sys.exit to # ensure that the process is killed. sys.exit(salt.defaults.exitcodes.EX_OK) log.error( 'Failed to import %s %s as the module called exit()\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False finally: sys.path.remove(fpath_dirname) if hasattr(mod, '__opts__'): mod.__opts__.update(self.opts) else: mod.__opts__ = self.opts # pack whatever other globals we were asked to for p_name, p_value in six.iteritems(self.pack): _inject_into_mod(mod, p_name, p_value) module_name = mod.__name__.rsplit('.', 1)[-1] # Call a module's initialization method if it exists module_init = getattr(mod, '__init__', None) if inspect.isfunction(module_init): try: module_init(self.opts) except TypeError as e: log.error(e) except Exception: err_string = '__init__ failed' log.debug( 'Error loading %s.%s: %s', self.tag, module_name, err_string, exc_info=True ) self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False # if virtual modules are enabled, we need to look for the # __virtual__() function inside that module and run it. if self.virtual_enable: virtual_funcs_to_process = ['__virtual__'] + self.virtual_funcs for virtual_func in virtual_funcs_to_process: virtual_ret, module_name, virtual_err, virtual_aliases = \ self._process_virtual(mod, module_name, virtual_func) if virtual_err is not None: log.trace( 'Error loading %s.%s: %s', self.tag, module_name, virtual_err ) # if _process_virtual returned a non-True value then we are # supposed to not process this module if virtual_ret is not True and module_name not in self.missing_modules: # If a module has information about why it could not be loaded, record it self.missing_modules[module_name] = virtual_err self.missing_modules[name] = virtual_err return False else: virtual_aliases = () # If this is a proxy minion then MOST modules cannot work. Therefore, require that # any module that does work with salt-proxy-minion define __proxyenabled__ as a list # containing the names of the proxy types that the module supports. # # Render modules and state modules are OK though if 'proxy' in self.opts: if self.tag in ['grains', 'proxy']: if not hasattr(mod, '__proxyenabled__') or \ (self.opts['proxy']['proxytype'] not in mod.__proxyenabled__ and '*' not in mod.__proxyenabled__): err_string = 'not a proxy_minion enabled module' self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False if getattr(mod, '__load__', False) is not False: log.info( 'The functions from module \'%s\' are being loaded from the ' 'provided __load__ attribute', module_name ) # If we had another module by the same virtual name, we should put any # new functions under the existing dictionary. mod_names = [module_name] + list(virtual_aliases) mod_dict = dict(( (x, self.loaded_modules.get(x, self.mod_dict_class())) for x in mod_names )) for attr in getattr(mod, '__load__', dir(mod)): if attr.startswith('_') and attr != '__call__': # private functions are skipped, # except __call__ which is default entrance # for multi-function batch-like state syntax continue func = getattr(mod, attr) if not inspect.isfunction(func) and not isinstance(func, functools.partial): # Not a function!? Skip it!!! continue # Let's get the function name. # If the module has the __func_alias__ attribute, it must be a # dictionary mapping in the form of(key -> value): # <real-func-name> -> <desired-func-name> # # It default's of course to the found callable attribute name # if no alias is defined. funcname = getattr(mod, '__func_alias__', {}).get(attr, attr) for tgt_mod in mod_names: try: full_funcname = '.'.join((tgt_mod, funcname)) except TypeError: full_funcname = '{0}.{1}'.format(tgt_mod, funcname) # Save many references for lookups # Careful not to overwrite existing (higher priority) functions if full_funcname not in self._dict: self._dict[full_funcname] = func if funcname not in mod_dict[tgt_mod]: setattr(mod_dict[tgt_mod], funcname, func) mod_dict[tgt_mod][funcname] = func self._apply_outputter(func, mod) # enforce depends try: Depends.enforce_dependencies(self._dict, self.tag) except RuntimeError as exc: log.info( 'Depends.enforce_dependencies() failed for the following ' 'reason: %s', exc ) for tgt_mod in mod_names: self.loaded_modules[tgt_mod] = mod_dict[tgt_mod] return True def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise KeyError('The key \'{0}\' should contain a \'.\''.format(key)) mod_name, _ = key.split('.', 1) with self._lock: # It is possible that the key is in the dictionary after # acquiring the lock due to another thread loading it. if mod_name in self.missing_modules or key in self._dict: return True # if the modulename isn't in the whitelist, don't bother if self.whitelist and mod_name not in self.whitelist: log.error( 'Failed to load function %s because its module (%s) is ' 'not in the whitelist: %s', key, mod_name, self.whitelist ) raise KeyError(key) def _inner_load(mod_name): for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and key in self._dict: return True return False # try to load the module ret = None reloaded = False # re-scan up to once, IOErrors or a failed load cause re-scans of the # filesystem while True: try: ret = _inner_load(mod_name) if not reloaded and ret is not True: self._refresh_file_mapping() reloaded = True continue break except IOError: if not reloaded: self._refresh_file_mapping() reloaded = True continue return ret def _load_all(self): ''' Load all of them ''' with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True def reload_modules(self): with self._lock: self.loaded_files = set() self._load_all() def _apply_outputter(self, func, mod): ''' Apply the __outputter__ variable to the functions ''' if hasattr(mod, '__outputter__'): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__] def _process_virtual(self, mod, module_name, virtual_func='__virtual__'): ''' Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1] ''' # The __virtual__ function will return either a True or False value. # If it returns a True value it can also set a module level attribute # named __virtualname__ with the name that the module should be # referred to as. # # This allows us to have things like the pkg module working on all # platforms under the name 'pkg'. It also allows for modules like # augeas_cfg to be referred to as 'augeas', which would otherwise have # namespace collisions. And finally it allows modules to return False # if they are not intended to run on the given platform or are missing # dependencies. virtual_aliases = getattr(mod, '__virtual_aliases__', tuple()) try: error_reason = None if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__): try: start = time.time() virtual = getattr(mod, virtual_func)() if isinstance(virtual, tuple): error_reason = virtual[1] virtual = virtual[0] if self.opts.get('virtual_timer', False): end = time.time() - start msg = 'Virtual function took {0} seconds for {1}'.format( end, module_name) log.warning(msg) except Exception as exc: error_reason = ( 'Exception raised when processing __virtual__ function' ' for {0}. Module will not be loaded: {1}'.format( mod.__name__, exc)) log.error(error_reason, exc_info_on_loglevel=logging.DEBUG) virtual = None # Get the module's virtual name virtualname = getattr(mod, '__virtualname__', virtual) if not virtual: # if __virtual__() evaluates to False then the module # wasn't meant for this platform or it's not supposed to # load for some other reason. # Some modules might accidentally return None and are # improperly loaded if virtual is None: log.warning( '%s.__virtual__() is wrongly returning `None`. ' 'It should either return `True`, `False` or a new ' 'name. If you\'re the developer of the module ' '\'%s\', please fix this.', mod.__name__, module_name ) return (False, module_name, error_reason, virtual_aliases) # At this point, __virtual__ did not return a # boolean value, let's check for deprecated usage # or module renames if virtual is not True and module_name != virtual: # The module is renaming itself. Updating the module name # with the new name log.trace('Loaded %s as virtual %s', module_name, virtual) if virtualname != virtual: # The __virtualname__ attribute does not match what's # being returned by the __virtual__() function. This # should be considered an error. log.error( 'The module \'%s\' is showing some bad usage. Its ' '__virtualname__ attribute is set to \'%s\' yet the ' '__virtual__() function is returning \'%s\'. These ' 'values should match!', mod.__name__, virtualname, virtual ) module_name = virtualname # If the __virtual__ function returns True and __virtualname__ # is set then use it elif virtual is True and virtualname != module_name: if virtualname is not True: module_name = virtualname except KeyError: # Key errors come out of the virtual function when passing # in incomplete grains sets, these can be safely ignored # and logged to debug, still, it includes the traceback to # help debugging. log.debug('KeyError when loading %s', module_name, exc_info=True) except Exception: # If the module throws an exception during __virtual__() # then log the information and continue to the next. log.error( 'Failed to read the virtual function for %s: %s', self.tag, module_name, exc_info=True ) return (False, module_name, error_reason, virtual_aliases) return (True, module_name, None, virtual_aliases) def global_injector_decorator(inject_globals): ''' Decorator used by the LazyLoader to inject globals into a function at execute time. globals Dictionary with global variables to inject ''' def inner_decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): with salt.utils.context.func_globals_inject(f, **inject_globals): return f(*args, **kwargs) return wrapper return inner_decorator
saltstack/salt
salt/loader.py
_inject_into_mod
python
def _inject_into_mod(mod, name, value, force_lock=False): ''' Inject a variable into a module. This is used to inject "globals" like ``__salt__``, ``__pillar``, or ``grains``. Instead of injecting the value directly, a ``ThreadLocalProxy`` is created. If such a proxy is already present under the specified name, it is updated with the new value. This update only affects the current thread, so that the same name can refer to different values depending on the thread of execution. This is important for data that is not truly global. For example, pillar data might be dynamically overriden through function parameters and thus the actual values available in pillar might depend on the thread that is calling a module. mod: module object into which the value is going to be injected. name: name of the variable that is injected into the module. value: value that is injected into the variable. The value is not injected directly, but instead set as the new reference of the proxy that has been created for the variable. force_lock: whether the lock should be acquired before checking whether a proxy object for the specified name has already been injected into the module. If ``False`` (the default), this function checks for the module's variable without acquiring the lock and only acquires the lock if a new proxy has to be created and injected. ''' old_value = getattr(mod, name, None) # We use a double-checked locking scheme in order to avoid taking the lock # when a proxy object has already been injected. # In most programming languages, double-checked locking is considered # unsafe when used without explicit memory barriers because one might read # an uninitialized value. In CPython it is safe due to the global # interpreter lock (GIL). In Python implementations that do not have the # GIL, it could be unsafe, but at least Jython also guarantees that (for # Python objects) memory is not corrupted when writing and reading without # explicit synchronization # (http://www.jython.org/jythonbook/en/1.0/Concurrency.html). # Please note that in order to make this code safe in a runtime environment # that does not make this guarantees, it is not sufficient. The # ThreadLocalProxy must also be created with fallback_to_shared set to # False or a lock must be added to the ThreadLocalProxy. if force_lock: with _inject_into_mod.lock: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: setattr(mod, name, ThreadLocalProxy(value, True)) else: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: _inject_into_mod(mod, name, value, True)
Inject a variable into a module. This is used to inject "globals" like ``__salt__``, ``__pillar``, or ``grains``. Instead of injecting the value directly, a ``ThreadLocalProxy`` is created. If such a proxy is already present under the specified name, it is updated with the new value. This update only affects the current thread, so that the same name can refer to different values depending on the thread of execution. This is important for data that is not truly global. For example, pillar data might be dynamically overriden through function parameters and thus the actual values available in pillar might depend on the thread that is calling a module. mod: module object into which the value is going to be injected. name: name of the variable that is injected into the module. value: value that is injected into the variable. The value is not injected directly, but instead set as the new reference of the proxy that has been created for the variable. force_lock: whether the lock should be acquired before checking whether a proxy object for the specified name has already been injected into the module. If ``False`` (the default), this function checks for the module's variable without acquiring the lock and only acquires the lock if a new proxy has to be created and injected.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L1096-L1155
null
# -*- coding: utf-8 -*- ''' The Salt loader is the core to Salt's plugin system, the loader scans directories for python loadable code and organizes the code into the plugin interfaces used by Salt. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import sys import time import logging import inspect import tempfile import threading import functools import threading import traceback import types from zipimport import zipimporter # Import salt libs import salt.config import salt.defaults.events import salt.defaults.exitcodes import salt.syspaths import salt.utils.args import salt.utils.context import salt.utils.data import salt.utils.dictupdate import salt.utils.event import salt.utils.files import salt.utils.lazy import salt.utils.odict import salt.utils.platform import salt.utils.versions import salt.utils.stringutils from salt.exceptions import LoaderError from salt.template import check_render_pipe_str from salt.utils.decorators import Depends from salt.utils.thread_local_proxy import ThreadLocalProxy # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import reload_module if sys.version_info[:2] >= (3, 5): import importlib.machinery # pylint: disable=no-name-in-module,import-error import importlib.util # pylint: disable=no-name-in-module,import-error USE_IMPORTLIB = True else: import imp USE_IMPORTLIB = False try: from collections.abc import MutableMapping except ImportError: from collections import MutableMapping try: import pkg_resources HAS_PKG_RESOURCES = True except ImportError: HAS_PKG_RESOURCES = False log = logging.getLogger(__name__) SALT_BASE_PATH = os.path.abspath(salt.syspaths.INSTALL_DIR) LOADED_BASE_NAME = 'salt.loaded' if USE_IMPORTLIB: # pylint: disable=no-member MODULE_KIND_SOURCE = 1 MODULE_KIND_COMPILED = 2 MODULE_KIND_EXTENSION = 3 MODULE_KIND_PKG_DIRECTORY = 5 SUFFIXES = [] for suffix in importlib.machinery.EXTENSION_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_EXTENSION)) for suffix in importlib.machinery.SOURCE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_SOURCE)) for suffix in importlib.machinery.BYTECODE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_COMPILED)) MODULE_KIND_MAP = { MODULE_KIND_SOURCE: importlib.machinery.SourceFileLoader, MODULE_KIND_COMPILED: importlib.machinery.SourcelessFileLoader, MODULE_KIND_EXTENSION: importlib.machinery.ExtensionFileLoader } # pylint: enable=no-member else: SUFFIXES = imp.get_suffixes() PY3_PRE_EXT = \ re.compile(r'\.cpython-{0}{1}(\.opt-[1-9])?'.format(*sys.version_info[:2])) # Because on the cloud drivers we do `from salt.cloud.libcloudfuncs import *` # which simplifies code readability, it adds some unsupported functions into # the driver's module scope. # We list un-supported functions here. These will be removed from the loaded. # TODO: remove the need for this cross-module code. Maybe use NotImplemented LIBCLOUD_FUNCS_NOT_SUPPORTED = ( 'parallels.avail_sizes', 'parallels.avail_locations', 'proxmox.avail_sizes', ) # Will be set to pyximport module at runtime if cython is enabled in config. pyximport = None def static_loader( opts, ext_type, tag, pack=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, filter_name=None, ): funcs = LazyLoader( _module_dirs( opts, ext_type, tag, int_type, ext_dirs, ext_type_dirs, base_path, ), opts, tag=tag, pack=pack, ) ret = {} funcs._load_all() if filter_name: funcs = FilterDictWrapper(funcs, filter_name) for key in funcs: ret[key] = funcs[key] return ret def _format_entrypoint_target(ep): ''' Makes a string describing the target of an EntryPoint object. Base strongly on EntryPoint.__str__(). ''' s = ep.module_name if ep.attrs: s += ':' + '.'.join(ep.attrs) return s def _module_dirs( opts, ext_type, tag=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, ): if tag is None: tag = ext_type sys_types = os.path.join(base_path or SALT_BASE_PATH, int_type or ext_type) ext_types = os.path.join(opts['extension_modules'], ext_type) ext_type_types = [] if ext_dirs: if ext_type_dirs is None: ext_type_dirs = '{0}_dirs'.format(tag) if ext_type_dirs in opts: ext_type_types.extend(opts[ext_type_dirs]) if HAS_PKG_RESOURCES and ext_type_dirs: for entry_point in pkg_resources.iter_entry_points('salt.loader', ext_type_dirs): try: loaded_entry_point = entry_point.load() for path in loaded_entry_point(): ext_type_types.append(path) except Exception as exc: log.error("Error getting module directories from %s: %s", _format_entrypoint_target(entry_point), exc) log.debug("Full backtrace for module directories error", exc_info=True) cli_module_dirs = [] # The dirs can be any module dir, or a in-tree _{ext_type} dir for _dir in opts.get('module_dirs', []): # Prepend to the list to match cli argument ordering maybe_dir = os.path.join(_dir, ext_type) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) continue maybe_dir = os.path.join(_dir, '_{0}'.format(ext_type)) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) return cli_module_dirs + ext_type_types + [ext_types, sys_types] def minion_mods( opts, context=None, utils=None, whitelist=None, initial_load=False, loaded_base_name=None, notify=False, static_modules=None, proxy=None): ''' Load execution modules Returns a dictionary of execution modules appropriate for the current system by evaluating the __virtual__() function in each module. :param dict opts: The Salt options dictionary :param dict context: A Salt context that should be made present inside generated modules in __context__ :param dict utils: Utility functions which should be made available to Salt modules in __utils__. See `utils_dirs` in salt.config for additional information about configuration. :param list whitelist: A list of modules which should be whitelisted. :param bool initial_load: Deprecated flag! Unused. :param str loaded_base_name: A string marker for the loaded base name. :param bool notify: Flag indicating that an event should be fired upon completion of module loading. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) __opts__['grains'] = __grains__ __utils__ = salt.loader.utils(__opts__) __salt__ = salt.loader.minion_mods(__opts__, utils=__utils__) __salt__['test.ping']() ''' # TODO Publish documentation for module whitelisting if not whitelist: whitelist = opts.get('whitelist_modules', None) ret = LazyLoader( _module_dirs(opts, 'modules', 'module'), opts, tag='module', pack={'__context__': context, '__utils__': utils, '__proxy__': proxy}, whitelist=whitelist, loaded_base_name=loaded_base_name, static_modules=static_modules, ) ret.pack['__salt__'] = ret # Load any provider overrides from the configuration file providers option # Note: Providers can be pkg, service, user or group - not to be confused # with cloud providers. providers = opts.get('providers', False) if providers and isinstance(providers, dict): for mod in providers: # sometimes providers opts is not to diverge modules but # for other configuration try: funcs = raw_mod(opts, providers[mod], ret) except TypeError: break else: if funcs: for func in funcs: f_key = '{0}{1}'.format(mod, func[func.rindex('.'):]) ret[f_key] = funcs[func] if notify: evt = salt.utils.event.get_event('minion', opts=opts, listen=False) evt.fire_event({'complete': True}, tag=salt.defaults.events.MINION_MOD_COMPLETE) return ret def raw_mod(opts, name, functions, mod='modules'): ''' Returns a single module loaded raw and bypassing the __virtual__ function .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') testmod = salt.loader.raw_mod(__opts__, 'test', None) testmod['test.ping']() ''' loader = LazyLoader( _module_dirs(opts, mod, 'module'), opts, tag='rawmodule', virtual_enable=False, pack={'__salt__': functions}, ) # if we don't have the module, return an empty dict if name not in loader.file_mapping: return {} loader._load_module(name) # load a single module (the one passed in) return dict(loader._dict) # return a copy of *just* the funcs for `name` def metaproxy(opts): ''' Return functions used in the meta proxy ''' return LazyLoader( _module_dirs(opts, 'metaproxy'), opts, tag='metaproxy' ) def matchers(opts): ''' Return the matcher services plugins ''' return LazyLoader( _module_dirs(opts, 'matchers'), opts, tag='matchers' ) def engines(opts, functions, runners, utils, proxy=None): ''' Return the master services plugins ''' pack = {'__salt__': functions, '__runners__': runners, '__proxy__': proxy, '__utils__': utils} return LazyLoader( _module_dirs(opts, 'engines'), opts, tag='engines', pack=pack, ) def proxy(opts, functions=None, returners=None, whitelist=None, utils=None): ''' Returns the proxy module for this salt-proxy-minion ''' ret = LazyLoader( _module_dirs(opts, 'proxy'), opts, tag='proxy', pack={'__salt__': functions, '__ret__': returners, '__utils__': utils}, ) ret.pack['__proxy__'] = ret return ret def returners(opts, functions, whitelist=None, context=None, proxy=None): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'returners', 'returner'), opts, tag='returner', whitelist=whitelist, pack={'__salt__': functions, '__context__': context, '__proxy__': proxy or {}}, ) def utils(opts, whitelist=None, context=None, proxy=proxy): ''' Returns the utility modules ''' return LazyLoader( _module_dirs(opts, 'utils', ext_type_dirs='utils_dirs'), opts, tag='utils', whitelist=whitelist, pack={'__context__': context, '__proxy__': proxy or {}}, ) def pillars(opts, functions, context=None): ''' Returns the pillars modules ''' ret = LazyLoader(_module_dirs(opts, 'pillar'), opts, tag='pillar', pack={'__salt__': functions, '__context__': context, '__utils__': utils(opts)}) ret.pack['__ext_pillar__'] = ret return FilterDictWrapper(ret, '.ext_pillar') def tops(opts): ''' Returns the tops modules ''' if 'master_tops' not in opts: return {} whitelist = list(opts['master_tops'].keys()) ret = LazyLoader( _module_dirs(opts, 'tops', 'top'), opts, tag='top', whitelist=whitelist, ) return FilterDictWrapper(ret, '.top') def wheels(opts, whitelist=None, context=None): ''' Returns the wheels modules ''' if context is None: context = {} return LazyLoader( _module_dirs(opts, 'wheel'), opts, tag='wheel', whitelist=whitelist, pack={'__context__': context}, ) def outputters(opts): ''' Returns the outputters modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only outputters present in the keyspace ''' ret = LazyLoader( _module_dirs(opts, 'output', ext_type_dirs='outputter_dirs'), opts, tag='output', ) wrapped_ret = FilterDictWrapper(ret, '.output') # TODO: this name seems terrible... __salt__ should always be execution mods ret.pack['__salt__'] = wrapped_ret return wrapped_ret def serializers(opts): ''' Returns the serializers modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only serializers present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'serializers'), opts, tag='serializers', ) def eauth_tokens(opts): ''' Returns the tokens modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only token backends present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'tokens'), opts, tag='tokens', ) def auth(opts, whitelist=None): ''' Returns the auth modules :param dict opts: The Salt options dictionary :returns: LazyLoader ''' return LazyLoader( _module_dirs(opts, 'auth'), opts, tag='auth', whitelist=whitelist, pack={'__salt__': minion_mods(opts)}, ) def fileserver(opts, backends): ''' Returns the file server modules ''' return LazyLoader(_module_dirs(opts, 'fileserver'), opts, tag='fileserver', whitelist=backends, pack={'__utils__': utils(opts)}) def roster(opts, runner=None, utils=None, whitelist=None): ''' Returns the roster modules ''' return LazyLoader( _module_dirs(opts, 'roster'), opts, tag='roster', whitelist=whitelist, pack={ '__runner__': runner, '__utils__': utils, }, ) def thorium(opts, functions, runners): ''' Load the thorium runtime modules ''' pack = {'__salt__': functions, '__runner__': runners, '__context__': {}} ret = LazyLoader(_module_dirs(opts, 'thorium'), opts, tag='thorium', pack=pack) ret.pack['__thorium__'] = ret return ret def states(opts, functions, utils, serializers, whitelist=None, proxy=None, context=None): ''' Returns the state modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') statemods = salt.loader.states(__opts__, None, None) ''' if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'states'), opts, tag='states', pack={'__salt__': functions, '__proxy__': proxy or {}}, whitelist=whitelist, ) ret.pack['__states__'] = ret ret.pack['__utils__'] = utils ret.pack['__serializers__'] = serializers ret.pack['__context__'] = context return ret def beacons(opts, functions, context=None, proxy=None): ''' Load the beacon modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. ''' return LazyLoader( _module_dirs(opts, 'beacons'), opts, tag='beacons', pack={'__context__': context, '__salt__': functions, '__proxy__': proxy or {}}, virtual_funcs=[], ) def log_handlers(opts): ''' Returns the custom logging handler modules :param dict opts: The Salt options dictionary ''' ret = LazyLoader( _module_dirs( opts, 'log_handlers', int_type='handlers', base_path=os.path.join(SALT_BASE_PATH, 'log'), ), opts, tag='log_handlers', ) return FilterDictWrapper(ret, '.setup_handlers') def ssh_wrapper(opts, functions=None, context=None): ''' Returns the custom logging handler modules ''' return LazyLoader( _module_dirs( opts, 'wrapper', base_path=os.path.join(SALT_BASE_PATH, os.path.join('client', 'ssh')), ), opts, tag='wrapper', pack={ '__salt__': functions, '__grains__': opts.get('grains', {}), '__pillar__': opts.get('pillar', {}), '__context__': context, }, ) def render(opts, functions, states=None, proxy=None, context=None): ''' Returns the render modules ''' if context is None: context = {} pack = {'__salt__': functions, '__grains__': opts.get('grains', {}), '__context__': context} if states: pack['__states__'] = states pack['__proxy__'] = proxy or {} ret = LazyLoader( _module_dirs( opts, 'renderers', 'render', ext_type_dirs='render_dirs', ), opts, tag='render', pack=pack, ) rend = FilterDictWrapper(ret, '.render') if not check_render_pipe_str(opts['renderer'], rend, opts['renderer_blacklist'], opts['renderer_whitelist']): err = ('The renderer {0} is unavailable, this error is often because ' 'the needed software is unavailable'.format(opts['renderer'])) log.critical(err) raise LoaderError(err) return rend def grain_funcs(opts, proxy=None): ''' Returns the grain functions .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') grainfuncs = salt.loader.grain_funcs(__opts__) ''' ret = LazyLoader( _module_dirs( opts, 'grains', 'grain', ext_type_dirs='grains_dirs', ), opts, tag='grains', ) ret.pack['__utils__'] = utils(opts, proxy=proxy) return ret def _load_cached_grains(opts, cfn): ''' Returns the grains cached in cfn, or None if the cache is too old or is corrupted. ''' if not os.path.isfile(cfn): log.debug('Grains cache file does not exist.') return None grains_cache_age = int(time.time() - os.path.getmtime(cfn)) if grains_cache_age > opts.get('grains_cache_expiration', 300): log.debug( 'Grains cache last modified %s seconds ago and cache ' 'expiration is set to %s. Grains cache expired. ' 'Refreshing.', grains_cache_age, opts.get('grains_cache_expiration', 300) ) return None if opts.get('refresh_grains_cache', False): log.debug('refresh_grains_cache requested, Refreshing.') return None log.debug('Retrieving grains from cache') try: serial = salt.payload.Serial(opts) with salt.utils.files.fopen(cfn, 'rb') as fp_: cached_grains = salt.utils.data.decode(serial.load(fp_), preserve_tuples=True) if not cached_grains: log.debug('Cached grains are empty, cache might be corrupted. Refreshing.') return None return cached_grains except (IOError, OSError): return None def grains(opts, force_refresh=False, proxy=None): ''' Return the functions for the dynamic grains and the values for the static grains. Since grains are computed early in the startup process, grains functions do not have __salt__ or __proxy__ available. At proxy-minion startup, this function is called with the proxymodule LazyLoader object so grains functions can communicate with their controlled device. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) print __grains__['id'] ''' # Need to re-import salt.config, somehow it got lost when a minion is starting import salt.config # if we have no grains, lets try loading from disk (TODO: move to decorator?) cfn = os.path.join( opts['cachedir'], 'grains.cache.p' ) if not force_refresh and opts.get('grains_cache', False): cached_grains = _load_cached_grains(opts, cfn) if cached_grains: return cached_grains else: log.debug('Grains refresh requested. Refreshing grains.') if opts.get('skip_grains', False): return {} grains_deep_merge = opts.get('grains_deep_merge', False) is True if 'conf_file' in opts: pre_opts = {} pre_opts.update(salt.config.load_config( opts['conf_file'], 'SALT_MINION_CONFIG', salt.config.DEFAULT_MINION_OPTS['conf_file'] )) default_include = pre_opts.get( 'default_include', opts['default_include'] ) include = pre_opts.get('include', []) pre_opts.update(salt.config.include_config( default_include, opts['conf_file'], verbose=False )) pre_opts.update(salt.config.include_config( include, opts['conf_file'], verbose=True )) if 'grains' in pre_opts: opts['grains'] = pre_opts['grains'] else: opts['grains'] = {} else: opts['grains'] = {} grains_data = {} blist = opts.get('grains_blacklist', []) funcs = grain_funcs(opts, proxy=proxy) if force_refresh: # if we refresh, lets reload grain modules funcs.clear() # Run core grains for key in funcs: if not key.startswith('core.'): continue log.trace('Loading %s grain', key) ret = funcs[key]() if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) # Run the rest of the grains for key in funcs: if key.startswith('core.') or key == '_errors': continue try: # Grains are loaded too early to take advantage of the injected # __proxy__ variable. Pass an instance of that LazyLoader # here instead to grains functions if the grains functions take # one parameter. Then the grains can have access to the # proxymodule for retrieving information from the connected # device. log.trace('Loading %s grain', key) parameters = salt.utils.args.get_function_argspec(funcs[key]).args kwargs = {} if 'proxy' in parameters: kwargs['proxy'] = proxy if 'grains' in parameters: kwargs['grains'] = grains_data ret = funcs[key](**kwargs) except Exception: if salt.utils.platform.is_proxy(): log.info('The following CRITICAL message may not be an error; the proxy may not be completely established yet.') log.critical( 'Failed to load grains defined in grain file %s in ' 'function %s, error:\n', key, funcs[key], exc_info=True ) continue if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) if opts.get('proxy_merge_grains_in_module', True) and proxy: try: proxytype = proxy.opts['proxy']['proxytype'] if proxytype + '.grains' in proxy: if proxytype + '.initialized' in proxy and proxy[proxytype + '.initialized'](): try: proxytype = proxy.opts['proxy']['proxytype'] ret = proxy[proxytype + '.grains']() if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) except Exception: log.critical('Failed to run proxy\'s grains function!', exc_info=True ) except KeyError: pass grains_data.update(opts['grains']) # Write cache if enabled if opts.get('grains_cache', False): with salt.utils.files.set_umask(0o077): try: if salt.utils.platform.is_windows(): # Late import import salt.modules.cmdmod # Make sure cache file isn't read-only salt.modules.cmdmod._run_quiet('attrib -R "{0}"'.format(cfn)) with salt.utils.files.fopen(cfn, 'w+b') as fp_: try: serial = salt.payload.Serial(opts) serial.dump(grains_data, fp_) except TypeError as e: log.error('Failed to serialize grains cache: %s', e) raise # re-throw for cleanup except Exception as e: log.error('Unable to write to grains cache file %s: %s', cfn, e) # Based on the original exception, the file may or may not have been # created. If it was, we will remove it now, as the exception means # the serialized data is not to be trusted, no matter what the # exception is. if os.path.isfile(cfn): os.unlink(cfn) if grains_deep_merge: salt.utils.dictupdate.update(grains_data, opts['grains']) else: grains_data.update(opts['grains']) return salt.utils.data.decode(grains_data, preserve_tuples=True) # TODO: get rid of? Does anyone use this? You should use raw() instead def call(fun, **kwargs): ''' Directly call a function inside a loader directory ''' args = kwargs.get('args', []) dirs = kwargs.get('dirs', []) funcs = LazyLoader( [os.path.join(SALT_BASE_PATH, 'modules')] + dirs, None, tag='modules', virtual_enable=False, ) return funcs[fun](*args) def runner(opts, utils=None, context=None, whitelist=None): ''' Directly call a function inside a loader directory ''' if utils is None: utils = {} if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'runners', 'runner', ext_type_dirs='runner_dirs'), opts, tag='runners', pack={'__utils__': utils, '__context__': context}, whitelist=whitelist, ) # TODO: change from __salt__ to something else, we overload __salt__ too much ret.pack['__salt__'] = ret return ret def queues(opts): ''' Directly call a function inside a loader directory ''' return LazyLoader( _module_dirs(opts, 'queues', 'queue', ext_type_dirs='queue_dirs'), opts, tag='queues', ) def sdb(opts, functions=None, whitelist=None, utils=None): ''' Make a very small database call ''' if utils is None: utils = {} return LazyLoader( _module_dirs(opts, 'sdb'), opts, tag='sdb', pack={ '__sdb__': functions, '__opts__': opts, '__utils__': utils, '__salt__': minion_mods(opts, utils), }, whitelist=whitelist, ) def pkgdb(opts): ''' Return modules for SPM's package database .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgdb', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgdb' ) def pkgfiles(opts): ''' Return modules for SPM's file handling .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgfiles', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgfiles' ) def clouds(opts): ''' Return the cloud functions ''' # Let's bring __active_provider_name__, defaulting to None, to all cloud # drivers. This will get temporarily updated/overridden with a context # manager when needed. functions = LazyLoader( _module_dirs(opts, 'clouds', 'cloud', base_path=os.path.join(SALT_BASE_PATH, 'cloud'), int_type='clouds'), opts, tag='clouds', pack={'__utils__': salt.loader.utils(opts), '__active_provider_name__': None}, ) for funcname in LIBCLOUD_FUNCS_NOT_SUPPORTED: log.trace( '\'%s\' has been marked as not supported. Removing from the ' 'list of supported cloud functions', funcname ) functions.pop(funcname, None) return functions def netapi(opts): ''' Return the network api functions ''' return LazyLoader( _module_dirs(opts, 'netapi'), opts, tag='netapi', ) def executors(opts, functions=None, context=None, proxy=None): ''' Returns the executor modules ''' executors = LazyLoader( _module_dirs(opts, 'executors', 'executor'), opts, tag='executor', pack={'__salt__': functions, '__context__': context or {}, '__proxy__': proxy or {}}, ) executors.pack['__executors__'] = executors return executors def cache(opts, serial): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'cache', 'cache'), opts, tag='cache', pack={'__opts__': opts, '__context__': {'serial': serial}}, ) def _generate_module(name): if name in sys.modules: return code = "'''Salt loaded {0} parent module'''".format(name.split('.')[-1]) # ModuleType can't accept a unicode type on PY2 module = types.ModuleType(str(name)) # future lint: disable=blacklisted-function exec(code, module.__dict__) sys.modules[name] = module def _mod_type(module_path): if module_path.startswith(SALT_BASE_PATH): return 'int' return 'ext' # Lock used when injecting globals. This is needed to avoid a race condition # when two threads try to load the same module concurrently. This must be # outside the loader because there might be more than one loader for the same # namespace. _inject_into_mod.lock = threading.RLock() # TODO: move somewhere else? class FilterDictWrapper(MutableMapping): ''' Create a dict which wraps another dict with a specific key suffix on get This is to replace "filter_load" ''' def __init__(self, d, suffix): self._dict = d self.suffix = suffix def __setitem__(self, key, val): self._dict[key] = val def __delitem__(self, key): del self._dict[key] def __getitem__(self, key): return self._dict[key + self.suffix] def __len__(self): return len(self._dict) def __iter__(self): for key in self._dict: if key.endswith(self.suffix): yield key.replace(self.suffix, '') class LazyLoader(salt.utils.lazy.LazyDict): ''' A pseduo-dictionary which has a set of keys which are the name of the module and function, delimited by a dot. When the value of the key is accessed, the function is then loaded from disk and into memory. .. note:: Iterating over keys will cause all modules to be loaded. :param list module_dirs: A list of directories on disk to search for modules :param dict opts: The salt options dictionary. :param str tag: The tag for the type of module to load :param func mod_type_check: A function which can be used to verify files :param dict pack: A dictionary of function to be packed into modules as they are loaded :param list whitelist: A list of modules to whitelist :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules. :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality. If not true, the module will not load. :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values are function references themselves which are loaded on-demand. # TODO: - move modules_max_memory into here - singletons (per tag) ''' mod_dict_class = salt.utils.odict.OrderedDict def __init__(self, module_dirs, opts=None, tag='module', loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, proxy=None, virtual_funcs=None, ): # pylint: disable=W0231 ''' In pack, if any of the values are None they will be replaced with an empty context-specific dict ''' self.inject_globals = {} self.pack = {} if pack is None else pack if opts is None: opts = {} threadsafety = not opts.get('multiprocessing') self.context_dict = salt.utils.context.ContextDict(threadsafe=threadsafety) self.opts = self.__prep_mod_opts(opts) self.module_dirs = module_dirs self.tag = tag self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME self.mod_type_check = mod_type_check or _mod_type if '__context__' not in self.pack: self.pack['__context__'] = None for k, v in six.iteritems(self.pack): if v is None: # if the value of a pack is None, lets make an empty dict value = self.context_dict.get(k, {}) if isinstance(value, ThreadLocalProxy): value = ThreadLocalProxy.unproxy(value) self.context_dict[k] = value self.pack[k] = salt.utils.context.NamespacedDictWrapper(self.context_dict, k) self.whitelist = whitelist self.virtual_enable = virtual_enable self.initial_load = True # names of modules that we don't have (errors, __virtual__, etc.) self.missing_modules = {} # mapping of name -> error self.loaded_modules = {} # mapping of module_name -> dict_of_functions self.loaded_files = set() # TODO: just remove them from file_mapping? self.static_modules = static_modules if static_modules else [] if virtual_funcs is None: virtual_funcs = [] self.virtual_funcs = virtual_funcs self.disabled = set( self.opts.get( 'disable_{0}{1}'.format( self.tag, '' if self.tag[-1] == 's' else 's' ), [] ) ) # A map of suffix to description for imp self.suffix_map = {} # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [''] for (suffix, mode, kind) in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) self._lock = threading.RLock() self._refresh_file_mapping() super(LazyLoader, self).__init__() # late init the lazy loader # create all of the import namespaces _generate_module('{0}.int'.format(self.loaded_base_name)) _generate_module('{0}.int.{1}'.format(self.loaded_base_name, tag)) _generate_module('{0}.ext'.format(self.loaded_base_name)) _generate_module('{0}.ext.{1}'.format(self.loaded_base_name, tag)) def __getitem__(self, item): ''' Override the __getitem__ in order to decorate the returned function if we need to last-minute inject globals ''' func = super(LazyLoader, self).__getitem__(item) if self.inject_globals: return global_injector_decorator(self.inject_globals)(func) else: return func def __getattr__(self, mod_name): ''' Allow for "direct" attribute access-- this allows jinja templates to access things like `salt.test.ping()` ''' if mod_name in ('__getstate__', '__setstate__'): return object.__getattribute__(self, mod_name) # if we have an attribute named that, lets return it. try: return object.__getattr__(self, mod_name) # pylint: disable=no-member except AttributeError: pass # otherwise we assume its jinja template access if mod_name not in self.loaded_modules and not self.loaded: for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and mod_name in self.loaded_modules: break if mod_name in self.loaded_modules: return self.loaded_modules[mod_name] else: raise AttributeError(mod_name) def missing_fun_string(self, function_name): ''' Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ''' mod_name = function_name.split('.')[0] if mod_name in self.loaded_modules: return '\'{0}\' is not available.'.format(function_name) else: try: reason = self.missing_modules[mod_name] except KeyError: return '\'{0}\' is not available.'.format(function_name) else: if reason is not None: return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason) else: return '\'{0}\' __virtual__ returned False'.format(mod_name) def _refresh_file_mapping(self): ''' refresh the mapping of the FS on disk ''' # map of suffix to description for imp if self.opts.get('cython_enable', True) is True: try: global pyximport pyximport = __import__('pyximport') # pylint: disable=import-error pyximport.install() # add to suffix_map so file_mapping will pick it up self.suffix_map['.pyx'] = tuple() except ImportError: log.info('Cython is enabled in the options but not present ' 'in the system path. Skipping Cython modules.') # Allow for zipimport of modules if self.opts.get('enable_zip_modules', True) is True: self.suffix_map['.zip'] = tuple() # allow for module dirs if USE_IMPORTLIB: self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY) else: self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY) # create mapping of filename (without suffix) to (path, suffix) # The files are added in order of priority, so order *must* be retained. self.file_mapping = salt.utils.odict.OrderedDict() opt_match = [] def _replace_pre_ext(obj): ''' Hack so we can get the optimization level that we replaced (if any) out of the re.sub call below. We use a list here because it is a persistent data structure that we will be able to access after re.sub is called. ''' opt_match.append(obj) return '' for mod_dir in self.module_dirs: try: # Make sure we have a sorted listdir in order to have # expectable override results files = sorted( x for x in os.listdir(mod_dir) if x != '__pycache__' ) except OSError: continue # Next mod_dir if six.PY3: try: pycache_files = [ os.path.join('__pycache__', x) for x in sorted(os.listdir(os.path.join(mod_dir, '__pycache__'))) ] except OSError: pass else: files.extend(pycache_files) for filename in files: try: dirname, basename = os.path.split(filename) if basename.startswith('_'): # skip private modules # log messages omitted for obviousness continue # Next filename f_noext, ext = os.path.splitext(basename) if six.PY3: f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext) try: opt_level = int( opt_match.pop().group(1).rsplit('-', 1)[-1] ) except (AttributeError, IndexError, ValueError): # No regex match or no optimization level matched opt_level = 0 try: opt_index = self.opts['optimization_order'].index(opt_level) except KeyError: log.trace( 'Disallowed optimization level %d for module ' 'name \'%s\', skipping. Add %d to the ' '\'optimization_order\' config option if you ' 'do not want to ignore this optimization ' 'level.', opt_level, f_noext, opt_level ) continue else: # Optimization level not reflected in filename on PY2 opt_index = 0 # make sure it is a suffix we support if ext not in self.suffix_map: continue # Next filename if f_noext in self.disabled: log.trace( 'Skipping %s, it is disabled by configuration', filename ) continue # Next filename fpath = os.path.join(mod_dir, filename) # if its a directory, lets allow us to load that if ext == '': # is there something __init__? subfiles = os.listdir(fpath) for suffix in self.suffix_order: if '' == suffix: continue # Next suffix (__init__ must have a suffix) init_file = '__init__{0}'.format(suffix) if init_file in subfiles: break else: continue # Next filename try: curr_ext = self.file_mapping[f_noext][1] curr_opt_index = self.file_mapping[f_noext][2] except KeyError: pass else: if '' in (curr_ext, ext) and curr_ext != ext: log.error( 'Module/package collision: \'%s\' and \'%s\'', fpath, self.file_mapping[f_noext][0] ) if six.PY3 and ext == '.pyc' and curr_ext == '.pyc': # Check the optimization level if opt_index >= curr_opt_index: # Module name match, but a higher-priority # optimization level was already matched, skipping. continue elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext): # Match found but a higher-priorty match already # exists, so skip this. continue if six.PY3 and not dirname and ext == '.pyc': # On Python 3, we should only load .pyc files from the # __pycache__ subdirectory (i.e. when dirname is not an # empty string). continue # Made it this far - add it self.file_mapping[f_noext] = (fpath, ext, opt_index) except OSError: continue for smod in self.static_modules: f_noext = smod.split('.')[-1] self.file_mapping[f_noext] = (smod, '.o', 0) def clear(self): ''' Clear the dict ''' with self._lock: super(LazyLoader, self).clear() # clear the lazy loader self.loaded_files = set() self.missing_modules = {} self.loaded_modules = {} # if we have been loaded before, lets clear the file mapping since # we obviously want a re-do if hasattr(self, 'opts'): self._refresh_file_mapping() self.initial_load = False def __prep_mod_opts(self, opts): ''' Strip out of the opts any logger instance ''' if '__grains__' not in self.pack: grains = opts.get('grains', {}) if isinstance(grains, ThreadLocalProxy): grains = ThreadLocalProxy.unproxy(grains) self.context_dict['grains'] = grains self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains') if '__pillar__' not in self.pack: pillar = opts.get('pillar', {}) if isinstance(pillar, ThreadLocalProxy): pillar = ThreadLocalProxy.unproxy(pillar) self.context_dict['pillar'] = pillar self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar') mod_opts = {} for key, val in list(opts.items()): if key == 'logger': continue mod_opts[key] = val return mod_opts def _iter_files(self, mod_name): ''' Iterate over all file_mapping files in order of closeness to mod_name ''' # do we have an exact match? if mod_name in self.file_mapping: yield mod_name # do we have a partial match? for k in self.file_mapping: if mod_name in k: yield k # anyone else? Bueller? for k in self.file_mapping: if mod_name not in k: yield k def _reload_submodules(self, mod): submodules = ( getattr(mod, sname) for sname in dir(mod) if isinstance(getattr(mod, sname), mod.__class__) ) # reload only custom "sub"modules for submodule in submodules: # it is a submodule if the name is in a namespace under mod if submodule.__name__.startswith(mod.__name__ + '.'): reload_module(submodule) self._reload_submodules(submodule) def _load_module(self, name): mod = None fpath, suffix = self.file_mapping[name][:2] self.loaded_files.add(name) fpath_dirname = os.path.dirname(fpath) try: sys.path.append(fpath_dirname) if suffix == '.pyx': mod = pyximport.load_module(name, fpath, tempfile.gettempdir()) elif suffix == '.o': top_mod = __import__(fpath, globals(), locals(), []) comps = fpath.split('.') if len(comps) < 2: mod = top_mod else: mod = top_mod for subname in comps[1:]: mod = getattr(mod, subname) elif suffix == '.zip': mod = zipimporter(fpath).load_module(name) else: desc = self.suffix_map[suffix] # if it is a directory, we don't open a file try: mod_namespace = '.'.join(( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name)) except TypeError: mod_namespace = '{0}.{1}.{2}.{3}'.format( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name) if suffix == '': if USE_IMPORTLIB: # pylint: disable=no-member # Package directory, look for __init__ loader_details = [ (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES), (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES), (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), ] file_finder = importlib.machinery.FileFinder( fpath_dirname, *loader_details ) spec = file_finder.find_spec(mod_namespace) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: mod = imp.load_module(mod_namespace, None, fpath, desc) # reload all submodules if necessary if not self.initial_load: self._reload_submodules(mod) else: if USE_IMPORTLIB: # pylint: disable=no-member loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath) spec = importlib.util.spec_from_file_location( mod_namespace, fpath, loader=loader ) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() #mod = importlib.util.module_from_spec(spec) #spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: with salt.utils.files.fopen(fpath, desc[1]) as fn_: mod = imp.load_module(mod_namespace, fn_, fpath, desc) except IOError: raise except ImportError as exc: if 'magic number' in six.text_type(exc): error_msg = 'Failed to import {0} {1}. Bad magic number. If migrating from Python2 to Python3, remove all .pyc files and try again.'.format(self.tag, name) log.warning(error_msg) self.missing_modules[name] = error_msg log.debug( 'Failed to import %s %s:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = exc return False except Exception as error: log.error( 'Failed to import %s %s, this is due most likely to a ' 'syntax error:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False except SystemExit as error: try: fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1] except Exception: pass else: tgt_fn = os.path.join('salt', 'utils', 'process.py') if fn_.endswith(tgt_fn) and '_handle_signals' in caller: # Race conditon, SIGTERM or SIGINT received while loader # was in process of loading a module. Call sys.exit to # ensure that the process is killed. sys.exit(salt.defaults.exitcodes.EX_OK) log.error( 'Failed to import %s %s as the module called exit()\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False finally: sys.path.remove(fpath_dirname) if hasattr(mod, '__opts__'): mod.__opts__.update(self.opts) else: mod.__opts__ = self.opts # pack whatever other globals we were asked to for p_name, p_value in six.iteritems(self.pack): _inject_into_mod(mod, p_name, p_value) module_name = mod.__name__.rsplit('.', 1)[-1] # Call a module's initialization method if it exists module_init = getattr(mod, '__init__', None) if inspect.isfunction(module_init): try: module_init(self.opts) except TypeError as e: log.error(e) except Exception: err_string = '__init__ failed' log.debug( 'Error loading %s.%s: %s', self.tag, module_name, err_string, exc_info=True ) self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False # if virtual modules are enabled, we need to look for the # __virtual__() function inside that module and run it. if self.virtual_enable: virtual_funcs_to_process = ['__virtual__'] + self.virtual_funcs for virtual_func in virtual_funcs_to_process: virtual_ret, module_name, virtual_err, virtual_aliases = \ self._process_virtual(mod, module_name, virtual_func) if virtual_err is not None: log.trace( 'Error loading %s.%s: %s', self.tag, module_name, virtual_err ) # if _process_virtual returned a non-True value then we are # supposed to not process this module if virtual_ret is not True and module_name not in self.missing_modules: # If a module has information about why it could not be loaded, record it self.missing_modules[module_name] = virtual_err self.missing_modules[name] = virtual_err return False else: virtual_aliases = () # If this is a proxy minion then MOST modules cannot work. Therefore, require that # any module that does work with salt-proxy-minion define __proxyenabled__ as a list # containing the names of the proxy types that the module supports. # # Render modules and state modules are OK though if 'proxy' in self.opts: if self.tag in ['grains', 'proxy']: if not hasattr(mod, '__proxyenabled__') or \ (self.opts['proxy']['proxytype'] not in mod.__proxyenabled__ and '*' not in mod.__proxyenabled__): err_string = 'not a proxy_minion enabled module' self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False if getattr(mod, '__load__', False) is not False: log.info( 'The functions from module \'%s\' are being loaded from the ' 'provided __load__ attribute', module_name ) # If we had another module by the same virtual name, we should put any # new functions under the existing dictionary. mod_names = [module_name] + list(virtual_aliases) mod_dict = dict(( (x, self.loaded_modules.get(x, self.mod_dict_class())) for x in mod_names )) for attr in getattr(mod, '__load__', dir(mod)): if attr.startswith('_') and attr != '__call__': # private functions are skipped, # except __call__ which is default entrance # for multi-function batch-like state syntax continue func = getattr(mod, attr) if not inspect.isfunction(func) and not isinstance(func, functools.partial): # Not a function!? Skip it!!! continue # Let's get the function name. # If the module has the __func_alias__ attribute, it must be a # dictionary mapping in the form of(key -> value): # <real-func-name> -> <desired-func-name> # # It default's of course to the found callable attribute name # if no alias is defined. funcname = getattr(mod, '__func_alias__', {}).get(attr, attr) for tgt_mod in mod_names: try: full_funcname = '.'.join((tgt_mod, funcname)) except TypeError: full_funcname = '{0}.{1}'.format(tgt_mod, funcname) # Save many references for lookups # Careful not to overwrite existing (higher priority) functions if full_funcname not in self._dict: self._dict[full_funcname] = func if funcname not in mod_dict[tgt_mod]: setattr(mod_dict[tgt_mod], funcname, func) mod_dict[tgt_mod][funcname] = func self._apply_outputter(func, mod) # enforce depends try: Depends.enforce_dependencies(self._dict, self.tag) except RuntimeError as exc: log.info( 'Depends.enforce_dependencies() failed for the following ' 'reason: %s', exc ) for tgt_mod in mod_names: self.loaded_modules[tgt_mod] = mod_dict[tgt_mod] return True def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise KeyError('The key \'{0}\' should contain a \'.\''.format(key)) mod_name, _ = key.split('.', 1) with self._lock: # It is possible that the key is in the dictionary after # acquiring the lock due to another thread loading it. if mod_name in self.missing_modules or key in self._dict: return True # if the modulename isn't in the whitelist, don't bother if self.whitelist and mod_name not in self.whitelist: log.error( 'Failed to load function %s because its module (%s) is ' 'not in the whitelist: %s', key, mod_name, self.whitelist ) raise KeyError(key) def _inner_load(mod_name): for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and key in self._dict: return True return False # try to load the module ret = None reloaded = False # re-scan up to once, IOErrors or a failed load cause re-scans of the # filesystem while True: try: ret = _inner_load(mod_name) if not reloaded and ret is not True: self._refresh_file_mapping() reloaded = True continue break except IOError: if not reloaded: self._refresh_file_mapping() reloaded = True continue return ret def _load_all(self): ''' Load all of them ''' with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True def reload_modules(self): with self._lock: self.loaded_files = set() self._load_all() def _apply_outputter(self, func, mod): ''' Apply the __outputter__ variable to the functions ''' if hasattr(mod, '__outputter__'): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__] def _process_virtual(self, mod, module_name, virtual_func='__virtual__'): ''' Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1] ''' # The __virtual__ function will return either a True or False value. # If it returns a True value it can also set a module level attribute # named __virtualname__ with the name that the module should be # referred to as. # # This allows us to have things like the pkg module working on all # platforms under the name 'pkg'. It also allows for modules like # augeas_cfg to be referred to as 'augeas', which would otherwise have # namespace collisions. And finally it allows modules to return False # if they are not intended to run on the given platform or are missing # dependencies. virtual_aliases = getattr(mod, '__virtual_aliases__', tuple()) try: error_reason = None if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__): try: start = time.time() virtual = getattr(mod, virtual_func)() if isinstance(virtual, tuple): error_reason = virtual[1] virtual = virtual[0] if self.opts.get('virtual_timer', False): end = time.time() - start msg = 'Virtual function took {0} seconds for {1}'.format( end, module_name) log.warning(msg) except Exception as exc: error_reason = ( 'Exception raised when processing __virtual__ function' ' for {0}. Module will not be loaded: {1}'.format( mod.__name__, exc)) log.error(error_reason, exc_info_on_loglevel=logging.DEBUG) virtual = None # Get the module's virtual name virtualname = getattr(mod, '__virtualname__', virtual) if not virtual: # if __virtual__() evaluates to False then the module # wasn't meant for this platform or it's not supposed to # load for some other reason. # Some modules might accidentally return None and are # improperly loaded if virtual is None: log.warning( '%s.__virtual__() is wrongly returning `None`. ' 'It should either return `True`, `False` or a new ' 'name. If you\'re the developer of the module ' '\'%s\', please fix this.', mod.__name__, module_name ) return (False, module_name, error_reason, virtual_aliases) # At this point, __virtual__ did not return a # boolean value, let's check for deprecated usage # or module renames if virtual is not True and module_name != virtual: # The module is renaming itself. Updating the module name # with the new name log.trace('Loaded %s as virtual %s', module_name, virtual) if virtualname != virtual: # The __virtualname__ attribute does not match what's # being returned by the __virtual__() function. This # should be considered an error. log.error( 'The module \'%s\' is showing some bad usage. Its ' '__virtualname__ attribute is set to \'%s\' yet the ' '__virtual__() function is returning \'%s\'. These ' 'values should match!', mod.__name__, virtualname, virtual ) module_name = virtualname # If the __virtual__ function returns True and __virtualname__ # is set then use it elif virtual is True and virtualname != module_name: if virtualname is not True: module_name = virtualname except KeyError: # Key errors come out of the virtual function when passing # in incomplete grains sets, these can be safely ignored # and logged to debug, still, it includes the traceback to # help debugging. log.debug('KeyError when loading %s', module_name, exc_info=True) except Exception: # If the module throws an exception during __virtual__() # then log the information and continue to the next. log.error( 'Failed to read the virtual function for %s: %s', self.tag, module_name, exc_info=True ) return (False, module_name, error_reason, virtual_aliases) return (True, module_name, None, virtual_aliases) def global_injector_decorator(inject_globals): ''' Decorator used by the LazyLoader to inject globals into a function at execute time. globals Dictionary with global variables to inject ''' def inner_decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): with salt.utils.context.func_globals_inject(f, **inject_globals): return f(*args, **kwargs) return wrapper return inner_decorator
saltstack/salt
salt/loader.py
global_injector_decorator
python
def global_injector_decorator(inject_globals): ''' Decorator used by the LazyLoader to inject globals into a function at execute time. globals Dictionary with global variables to inject ''' def inner_decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): with salt.utils.context.func_globals_inject(f, **inject_globals): return f(*args, **kwargs) return wrapper return inner_decorator
Decorator used by the LazyLoader to inject globals into a function at execute time. globals Dictionary with global variables to inject
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L2044-L2058
null
# -*- coding: utf-8 -*- ''' The Salt loader is the core to Salt's plugin system, the loader scans directories for python loadable code and organizes the code into the plugin interfaces used by Salt. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import sys import time import logging import inspect import tempfile import threading import functools import threading import traceback import types from zipimport import zipimporter # Import salt libs import salt.config import salt.defaults.events import salt.defaults.exitcodes import salt.syspaths import salt.utils.args import salt.utils.context import salt.utils.data import salt.utils.dictupdate import salt.utils.event import salt.utils.files import salt.utils.lazy import salt.utils.odict import salt.utils.platform import salt.utils.versions import salt.utils.stringutils from salt.exceptions import LoaderError from salt.template import check_render_pipe_str from salt.utils.decorators import Depends from salt.utils.thread_local_proxy import ThreadLocalProxy # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import reload_module if sys.version_info[:2] >= (3, 5): import importlib.machinery # pylint: disable=no-name-in-module,import-error import importlib.util # pylint: disable=no-name-in-module,import-error USE_IMPORTLIB = True else: import imp USE_IMPORTLIB = False try: from collections.abc import MutableMapping except ImportError: from collections import MutableMapping try: import pkg_resources HAS_PKG_RESOURCES = True except ImportError: HAS_PKG_RESOURCES = False log = logging.getLogger(__name__) SALT_BASE_PATH = os.path.abspath(salt.syspaths.INSTALL_DIR) LOADED_BASE_NAME = 'salt.loaded' if USE_IMPORTLIB: # pylint: disable=no-member MODULE_KIND_SOURCE = 1 MODULE_KIND_COMPILED = 2 MODULE_KIND_EXTENSION = 3 MODULE_KIND_PKG_DIRECTORY = 5 SUFFIXES = [] for suffix in importlib.machinery.EXTENSION_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_EXTENSION)) for suffix in importlib.machinery.SOURCE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_SOURCE)) for suffix in importlib.machinery.BYTECODE_SUFFIXES: SUFFIXES.append((suffix, 'rb', MODULE_KIND_COMPILED)) MODULE_KIND_MAP = { MODULE_KIND_SOURCE: importlib.machinery.SourceFileLoader, MODULE_KIND_COMPILED: importlib.machinery.SourcelessFileLoader, MODULE_KIND_EXTENSION: importlib.machinery.ExtensionFileLoader } # pylint: enable=no-member else: SUFFIXES = imp.get_suffixes() PY3_PRE_EXT = \ re.compile(r'\.cpython-{0}{1}(\.opt-[1-9])?'.format(*sys.version_info[:2])) # Because on the cloud drivers we do `from salt.cloud.libcloudfuncs import *` # which simplifies code readability, it adds some unsupported functions into # the driver's module scope. # We list un-supported functions here. These will be removed from the loaded. # TODO: remove the need for this cross-module code. Maybe use NotImplemented LIBCLOUD_FUNCS_NOT_SUPPORTED = ( 'parallels.avail_sizes', 'parallels.avail_locations', 'proxmox.avail_sizes', ) # Will be set to pyximport module at runtime if cython is enabled in config. pyximport = None def static_loader( opts, ext_type, tag, pack=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, filter_name=None, ): funcs = LazyLoader( _module_dirs( opts, ext_type, tag, int_type, ext_dirs, ext_type_dirs, base_path, ), opts, tag=tag, pack=pack, ) ret = {} funcs._load_all() if filter_name: funcs = FilterDictWrapper(funcs, filter_name) for key in funcs: ret[key] = funcs[key] return ret def _format_entrypoint_target(ep): ''' Makes a string describing the target of an EntryPoint object. Base strongly on EntryPoint.__str__(). ''' s = ep.module_name if ep.attrs: s += ':' + '.'.join(ep.attrs) return s def _module_dirs( opts, ext_type, tag=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, ): if tag is None: tag = ext_type sys_types = os.path.join(base_path or SALT_BASE_PATH, int_type or ext_type) ext_types = os.path.join(opts['extension_modules'], ext_type) ext_type_types = [] if ext_dirs: if ext_type_dirs is None: ext_type_dirs = '{0}_dirs'.format(tag) if ext_type_dirs in opts: ext_type_types.extend(opts[ext_type_dirs]) if HAS_PKG_RESOURCES and ext_type_dirs: for entry_point in pkg_resources.iter_entry_points('salt.loader', ext_type_dirs): try: loaded_entry_point = entry_point.load() for path in loaded_entry_point(): ext_type_types.append(path) except Exception as exc: log.error("Error getting module directories from %s: %s", _format_entrypoint_target(entry_point), exc) log.debug("Full backtrace for module directories error", exc_info=True) cli_module_dirs = [] # The dirs can be any module dir, or a in-tree _{ext_type} dir for _dir in opts.get('module_dirs', []): # Prepend to the list to match cli argument ordering maybe_dir = os.path.join(_dir, ext_type) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) continue maybe_dir = os.path.join(_dir, '_{0}'.format(ext_type)) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) return cli_module_dirs + ext_type_types + [ext_types, sys_types] def minion_mods( opts, context=None, utils=None, whitelist=None, initial_load=False, loaded_base_name=None, notify=False, static_modules=None, proxy=None): ''' Load execution modules Returns a dictionary of execution modules appropriate for the current system by evaluating the __virtual__() function in each module. :param dict opts: The Salt options dictionary :param dict context: A Salt context that should be made present inside generated modules in __context__ :param dict utils: Utility functions which should be made available to Salt modules in __utils__. See `utils_dirs` in salt.config for additional information about configuration. :param list whitelist: A list of modules which should be whitelisted. :param bool initial_load: Deprecated flag! Unused. :param str loaded_base_name: A string marker for the loaded base name. :param bool notify: Flag indicating that an event should be fired upon completion of module loading. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) __opts__['grains'] = __grains__ __utils__ = salt.loader.utils(__opts__) __salt__ = salt.loader.minion_mods(__opts__, utils=__utils__) __salt__['test.ping']() ''' # TODO Publish documentation for module whitelisting if not whitelist: whitelist = opts.get('whitelist_modules', None) ret = LazyLoader( _module_dirs(opts, 'modules', 'module'), opts, tag='module', pack={'__context__': context, '__utils__': utils, '__proxy__': proxy}, whitelist=whitelist, loaded_base_name=loaded_base_name, static_modules=static_modules, ) ret.pack['__salt__'] = ret # Load any provider overrides from the configuration file providers option # Note: Providers can be pkg, service, user or group - not to be confused # with cloud providers. providers = opts.get('providers', False) if providers and isinstance(providers, dict): for mod in providers: # sometimes providers opts is not to diverge modules but # for other configuration try: funcs = raw_mod(opts, providers[mod], ret) except TypeError: break else: if funcs: for func in funcs: f_key = '{0}{1}'.format(mod, func[func.rindex('.'):]) ret[f_key] = funcs[func] if notify: evt = salt.utils.event.get_event('minion', opts=opts, listen=False) evt.fire_event({'complete': True}, tag=salt.defaults.events.MINION_MOD_COMPLETE) return ret def raw_mod(opts, name, functions, mod='modules'): ''' Returns a single module loaded raw and bypassing the __virtual__ function .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') testmod = salt.loader.raw_mod(__opts__, 'test', None) testmod['test.ping']() ''' loader = LazyLoader( _module_dirs(opts, mod, 'module'), opts, tag='rawmodule', virtual_enable=False, pack={'__salt__': functions}, ) # if we don't have the module, return an empty dict if name not in loader.file_mapping: return {} loader._load_module(name) # load a single module (the one passed in) return dict(loader._dict) # return a copy of *just* the funcs for `name` def metaproxy(opts): ''' Return functions used in the meta proxy ''' return LazyLoader( _module_dirs(opts, 'metaproxy'), opts, tag='metaproxy' ) def matchers(opts): ''' Return the matcher services plugins ''' return LazyLoader( _module_dirs(opts, 'matchers'), opts, tag='matchers' ) def engines(opts, functions, runners, utils, proxy=None): ''' Return the master services plugins ''' pack = {'__salt__': functions, '__runners__': runners, '__proxy__': proxy, '__utils__': utils} return LazyLoader( _module_dirs(opts, 'engines'), opts, tag='engines', pack=pack, ) def proxy(opts, functions=None, returners=None, whitelist=None, utils=None): ''' Returns the proxy module for this salt-proxy-minion ''' ret = LazyLoader( _module_dirs(opts, 'proxy'), opts, tag='proxy', pack={'__salt__': functions, '__ret__': returners, '__utils__': utils}, ) ret.pack['__proxy__'] = ret return ret def returners(opts, functions, whitelist=None, context=None, proxy=None): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'returners', 'returner'), opts, tag='returner', whitelist=whitelist, pack={'__salt__': functions, '__context__': context, '__proxy__': proxy or {}}, ) def utils(opts, whitelist=None, context=None, proxy=proxy): ''' Returns the utility modules ''' return LazyLoader( _module_dirs(opts, 'utils', ext_type_dirs='utils_dirs'), opts, tag='utils', whitelist=whitelist, pack={'__context__': context, '__proxy__': proxy or {}}, ) def pillars(opts, functions, context=None): ''' Returns the pillars modules ''' ret = LazyLoader(_module_dirs(opts, 'pillar'), opts, tag='pillar', pack={'__salt__': functions, '__context__': context, '__utils__': utils(opts)}) ret.pack['__ext_pillar__'] = ret return FilterDictWrapper(ret, '.ext_pillar') def tops(opts): ''' Returns the tops modules ''' if 'master_tops' not in opts: return {} whitelist = list(opts['master_tops'].keys()) ret = LazyLoader( _module_dirs(opts, 'tops', 'top'), opts, tag='top', whitelist=whitelist, ) return FilterDictWrapper(ret, '.top') def wheels(opts, whitelist=None, context=None): ''' Returns the wheels modules ''' if context is None: context = {} return LazyLoader( _module_dirs(opts, 'wheel'), opts, tag='wheel', whitelist=whitelist, pack={'__context__': context}, ) def outputters(opts): ''' Returns the outputters modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only outputters present in the keyspace ''' ret = LazyLoader( _module_dirs(opts, 'output', ext_type_dirs='outputter_dirs'), opts, tag='output', ) wrapped_ret = FilterDictWrapper(ret, '.output') # TODO: this name seems terrible... __salt__ should always be execution mods ret.pack['__salt__'] = wrapped_ret return wrapped_ret def serializers(opts): ''' Returns the serializers modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only serializers present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'serializers'), opts, tag='serializers', ) def eauth_tokens(opts): ''' Returns the tokens modules :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only token backends present in the keyspace ''' return LazyLoader( _module_dirs(opts, 'tokens'), opts, tag='tokens', ) def auth(opts, whitelist=None): ''' Returns the auth modules :param dict opts: The Salt options dictionary :returns: LazyLoader ''' return LazyLoader( _module_dirs(opts, 'auth'), opts, tag='auth', whitelist=whitelist, pack={'__salt__': minion_mods(opts)}, ) def fileserver(opts, backends): ''' Returns the file server modules ''' return LazyLoader(_module_dirs(opts, 'fileserver'), opts, tag='fileserver', whitelist=backends, pack={'__utils__': utils(opts)}) def roster(opts, runner=None, utils=None, whitelist=None): ''' Returns the roster modules ''' return LazyLoader( _module_dirs(opts, 'roster'), opts, tag='roster', whitelist=whitelist, pack={ '__runner__': runner, '__utils__': utils, }, ) def thorium(opts, functions, runners): ''' Load the thorium runtime modules ''' pack = {'__salt__': functions, '__runner__': runners, '__context__': {}} ret = LazyLoader(_module_dirs(opts, 'thorium'), opts, tag='thorium', pack=pack) ret.pack['__thorium__'] = ret return ret def states(opts, functions, utils, serializers, whitelist=None, proxy=None, context=None): ''' Returns the state modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') statemods = salt.loader.states(__opts__, None, None) ''' if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'states'), opts, tag='states', pack={'__salt__': functions, '__proxy__': proxy or {}}, whitelist=whitelist, ) ret.pack['__states__'] = ret ret.pack['__utils__'] = utils ret.pack['__serializers__'] = serializers ret.pack['__context__'] = context return ret def beacons(opts, functions, context=None, proxy=None): ''' Load the beacon modules :param dict opts: The Salt options dictionary :param dict functions: A dictionary of minion modules, with module names as keys and funcs as values. ''' return LazyLoader( _module_dirs(opts, 'beacons'), opts, tag='beacons', pack={'__context__': context, '__salt__': functions, '__proxy__': proxy or {}}, virtual_funcs=[], ) def log_handlers(opts): ''' Returns the custom logging handler modules :param dict opts: The Salt options dictionary ''' ret = LazyLoader( _module_dirs( opts, 'log_handlers', int_type='handlers', base_path=os.path.join(SALT_BASE_PATH, 'log'), ), opts, tag='log_handlers', ) return FilterDictWrapper(ret, '.setup_handlers') def ssh_wrapper(opts, functions=None, context=None): ''' Returns the custom logging handler modules ''' return LazyLoader( _module_dirs( opts, 'wrapper', base_path=os.path.join(SALT_BASE_PATH, os.path.join('client', 'ssh')), ), opts, tag='wrapper', pack={ '__salt__': functions, '__grains__': opts.get('grains', {}), '__pillar__': opts.get('pillar', {}), '__context__': context, }, ) def render(opts, functions, states=None, proxy=None, context=None): ''' Returns the render modules ''' if context is None: context = {} pack = {'__salt__': functions, '__grains__': opts.get('grains', {}), '__context__': context} if states: pack['__states__'] = states pack['__proxy__'] = proxy or {} ret = LazyLoader( _module_dirs( opts, 'renderers', 'render', ext_type_dirs='render_dirs', ), opts, tag='render', pack=pack, ) rend = FilterDictWrapper(ret, '.render') if not check_render_pipe_str(opts['renderer'], rend, opts['renderer_blacklist'], opts['renderer_whitelist']): err = ('The renderer {0} is unavailable, this error is often because ' 'the needed software is unavailable'.format(opts['renderer'])) log.critical(err) raise LoaderError(err) return rend def grain_funcs(opts, proxy=None): ''' Returns the grain functions .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') grainfuncs = salt.loader.grain_funcs(__opts__) ''' ret = LazyLoader( _module_dirs( opts, 'grains', 'grain', ext_type_dirs='grains_dirs', ), opts, tag='grains', ) ret.pack['__utils__'] = utils(opts, proxy=proxy) return ret def _load_cached_grains(opts, cfn): ''' Returns the grains cached in cfn, or None if the cache is too old or is corrupted. ''' if not os.path.isfile(cfn): log.debug('Grains cache file does not exist.') return None grains_cache_age = int(time.time() - os.path.getmtime(cfn)) if grains_cache_age > opts.get('grains_cache_expiration', 300): log.debug( 'Grains cache last modified %s seconds ago and cache ' 'expiration is set to %s. Grains cache expired. ' 'Refreshing.', grains_cache_age, opts.get('grains_cache_expiration', 300) ) return None if opts.get('refresh_grains_cache', False): log.debug('refresh_grains_cache requested, Refreshing.') return None log.debug('Retrieving grains from cache') try: serial = salt.payload.Serial(opts) with salt.utils.files.fopen(cfn, 'rb') as fp_: cached_grains = salt.utils.data.decode(serial.load(fp_), preserve_tuples=True) if not cached_grains: log.debug('Cached grains are empty, cache might be corrupted. Refreshing.') return None return cached_grains except (IOError, OSError): return None def grains(opts, force_refresh=False, proxy=None): ''' Return the functions for the dynamic grains and the values for the static grains. Since grains are computed early in the startup process, grains functions do not have __salt__ or __proxy__ available. At proxy-minion startup, this function is called with the proxymodule LazyLoader object so grains functions can communicate with their controlled device. .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) print __grains__['id'] ''' # Need to re-import salt.config, somehow it got lost when a minion is starting import salt.config # if we have no grains, lets try loading from disk (TODO: move to decorator?) cfn = os.path.join( opts['cachedir'], 'grains.cache.p' ) if not force_refresh and opts.get('grains_cache', False): cached_grains = _load_cached_grains(opts, cfn) if cached_grains: return cached_grains else: log.debug('Grains refresh requested. Refreshing grains.') if opts.get('skip_grains', False): return {} grains_deep_merge = opts.get('grains_deep_merge', False) is True if 'conf_file' in opts: pre_opts = {} pre_opts.update(salt.config.load_config( opts['conf_file'], 'SALT_MINION_CONFIG', salt.config.DEFAULT_MINION_OPTS['conf_file'] )) default_include = pre_opts.get( 'default_include', opts['default_include'] ) include = pre_opts.get('include', []) pre_opts.update(salt.config.include_config( default_include, opts['conf_file'], verbose=False )) pre_opts.update(salt.config.include_config( include, opts['conf_file'], verbose=True )) if 'grains' in pre_opts: opts['grains'] = pre_opts['grains'] else: opts['grains'] = {} else: opts['grains'] = {} grains_data = {} blist = opts.get('grains_blacklist', []) funcs = grain_funcs(opts, proxy=proxy) if force_refresh: # if we refresh, lets reload grain modules funcs.clear() # Run core grains for key in funcs: if not key.startswith('core.'): continue log.trace('Loading %s grain', key) ret = funcs[key]() if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) # Run the rest of the grains for key in funcs: if key.startswith('core.') or key == '_errors': continue try: # Grains are loaded too early to take advantage of the injected # __proxy__ variable. Pass an instance of that LazyLoader # here instead to grains functions if the grains functions take # one parameter. Then the grains can have access to the # proxymodule for retrieving information from the connected # device. log.trace('Loading %s grain', key) parameters = salt.utils.args.get_function_argspec(funcs[key]).args kwargs = {} if 'proxy' in parameters: kwargs['proxy'] = proxy if 'grains' in parameters: kwargs['grains'] = grains_data ret = funcs[key](**kwargs) except Exception: if salt.utils.platform.is_proxy(): log.info('The following CRITICAL message may not be an error; the proxy may not be completely established yet.') log.critical( 'Failed to load grains defined in grain file %s in ' 'function %s, error:\n', key, funcs[key], exc_info=True ) continue if not isinstance(ret, dict): continue if blist: for key in list(ret): for block in blist: if salt.utils.stringutils.expr_match(key, block): del ret[key] log.trace('Filtering %s grain', key) if not ret: continue if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) if opts.get('proxy_merge_grains_in_module', True) and proxy: try: proxytype = proxy.opts['proxy']['proxytype'] if proxytype + '.grains' in proxy: if proxytype + '.initialized' in proxy and proxy[proxytype + '.initialized'](): try: proxytype = proxy.opts['proxy']['proxytype'] ret = proxy[proxytype + '.grains']() if grains_deep_merge: salt.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) except Exception: log.critical('Failed to run proxy\'s grains function!', exc_info=True ) except KeyError: pass grains_data.update(opts['grains']) # Write cache if enabled if opts.get('grains_cache', False): with salt.utils.files.set_umask(0o077): try: if salt.utils.platform.is_windows(): # Late import import salt.modules.cmdmod # Make sure cache file isn't read-only salt.modules.cmdmod._run_quiet('attrib -R "{0}"'.format(cfn)) with salt.utils.files.fopen(cfn, 'w+b') as fp_: try: serial = salt.payload.Serial(opts) serial.dump(grains_data, fp_) except TypeError as e: log.error('Failed to serialize grains cache: %s', e) raise # re-throw for cleanup except Exception as e: log.error('Unable to write to grains cache file %s: %s', cfn, e) # Based on the original exception, the file may or may not have been # created. If it was, we will remove it now, as the exception means # the serialized data is not to be trusted, no matter what the # exception is. if os.path.isfile(cfn): os.unlink(cfn) if grains_deep_merge: salt.utils.dictupdate.update(grains_data, opts['grains']) else: grains_data.update(opts['grains']) return salt.utils.data.decode(grains_data, preserve_tuples=True) # TODO: get rid of? Does anyone use this? You should use raw() instead def call(fun, **kwargs): ''' Directly call a function inside a loader directory ''' args = kwargs.get('args', []) dirs = kwargs.get('dirs', []) funcs = LazyLoader( [os.path.join(SALT_BASE_PATH, 'modules')] + dirs, None, tag='modules', virtual_enable=False, ) return funcs[fun](*args) def runner(opts, utils=None, context=None, whitelist=None): ''' Directly call a function inside a loader directory ''' if utils is None: utils = {} if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'runners', 'runner', ext_type_dirs='runner_dirs'), opts, tag='runners', pack={'__utils__': utils, '__context__': context}, whitelist=whitelist, ) # TODO: change from __salt__ to something else, we overload __salt__ too much ret.pack['__salt__'] = ret return ret def queues(opts): ''' Directly call a function inside a loader directory ''' return LazyLoader( _module_dirs(opts, 'queues', 'queue', ext_type_dirs='queue_dirs'), opts, tag='queues', ) def sdb(opts, functions=None, whitelist=None, utils=None): ''' Make a very small database call ''' if utils is None: utils = {} return LazyLoader( _module_dirs(opts, 'sdb'), opts, tag='sdb', pack={ '__sdb__': functions, '__opts__': opts, '__utils__': utils, '__salt__': minion_mods(opts, utils), }, whitelist=whitelist, ) def pkgdb(opts): ''' Return modules for SPM's package database .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgdb', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgdb' ) def pkgfiles(opts): ''' Return modules for SPM's file handling .. versionadded:: 2015.8.0 ''' return LazyLoader( _module_dirs( opts, 'pkgfiles', base_path=os.path.join(SALT_BASE_PATH, 'spm') ), opts, tag='pkgfiles' ) def clouds(opts): ''' Return the cloud functions ''' # Let's bring __active_provider_name__, defaulting to None, to all cloud # drivers. This will get temporarily updated/overridden with a context # manager when needed. functions = LazyLoader( _module_dirs(opts, 'clouds', 'cloud', base_path=os.path.join(SALT_BASE_PATH, 'cloud'), int_type='clouds'), opts, tag='clouds', pack={'__utils__': salt.loader.utils(opts), '__active_provider_name__': None}, ) for funcname in LIBCLOUD_FUNCS_NOT_SUPPORTED: log.trace( '\'%s\' has been marked as not supported. Removing from the ' 'list of supported cloud functions', funcname ) functions.pop(funcname, None) return functions def netapi(opts): ''' Return the network api functions ''' return LazyLoader( _module_dirs(opts, 'netapi'), opts, tag='netapi', ) def executors(opts, functions=None, context=None, proxy=None): ''' Returns the executor modules ''' executors = LazyLoader( _module_dirs(opts, 'executors', 'executor'), opts, tag='executor', pack={'__salt__': functions, '__context__': context or {}, '__proxy__': proxy or {}}, ) executors.pack['__executors__'] = executors return executors def cache(opts, serial): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'cache', 'cache'), opts, tag='cache', pack={'__opts__': opts, '__context__': {'serial': serial}}, ) def _generate_module(name): if name in sys.modules: return code = "'''Salt loaded {0} parent module'''".format(name.split('.')[-1]) # ModuleType can't accept a unicode type on PY2 module = types.ModuleType(str(name)) # future lint: disable=blacklisted-function exec(code, module.__dict__) sys.modules[name] = module def _mod_type(module_path): if module_path.startswith(SALT_BASE_PATH): return 'int' return 'ext' def _inject_into_mod(mod, name, value, force_lock=False): ''' Inject a variable into a module. This is used to inject "globals" like ``__salt__``, ``__pillar``, or ``grains``. Instead of injecting the value directly, a ``ThreadLocalProxy`` is created. If such a proxy is already present under the specified name, it is updated with the new value. This update only affects the current thread, so that the same name can refer to different values depending on the thread of execution. This is important for data that is not truly global. For example, pillar data might be dynamically overriden through function parameters and thus the actual values available in pillar might depend on the thread that is calling a module. mod: module object into which the value is going to be injected. name: name of the variable that is injected into the module. value: value that is injected into the variable. The value is not injected directly, but instead set as the new reference of the proxy that has been created for the variable. force_lock: whether the lock should be acquired before checking whether a proxy object for the specified name has already been injected into the module. If ``False`` (the default), this function checks for the module's variable without acquiring the lock and only acquires the lock if a new proxy has to be created and injected. ''' old_value = getattr(mod, name, None) # We use a double-checked locking scheme in order to avoid taking the lock # when a proxy object has already been injected. # In most programming languages, double-checked locking is considered # unsafe when used without explicit memory barriers because one might read # an uninitialized value. In CPython it is safe due to the global # interpreter lock (GIL). In Python implementations that do not have the # GIL, it could be unsafe, but at least Jython also guarantees that (for # Python objects) memory is not corrupted when writing and reading without # explicit synchronization # (http://www.jython.org/jythonbook/en/1.0/Concurrency.html). # Please note that in order to make this code safe in a runtime environment # that does not make this guarantees, it is not sufficient. The # ThreadLocalProxy must also be created with fallback_to_shared set to # False or a lock must be added to the ThreadLocalProxy. if force_lock: with _inject_into_mod.lock: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: setattr(mod, name, ThreadLocalProxy(value, True)) else: if isinstance(old_value, ThreadLocalProxy): ThreadLocalProxy.set_reference(old_value, value) else: _inject_into_mod(mod, name, value, True) # Lock used when injecting globals. This is needed to avoid a race condition # when two threads try to load the same module concurrently. This must be # outside the loader because there might be more than one loader for the same # namespace. _inject_into_mod.lock = threading.RLock() # TODO: move somewhere else? class FilterDictWrapper(MutableMapping): ''' Create a dict which wraps another dict with a specific key suffix on get This is to replace "filter_load" ''' def __init__(self, d, suffix): self._dict = d self.suffix = suffix def __setitem__(self, key, val): self._dict[key] = val def __delitem__(self, key): del self._dict[key] def __getitem__(self, key): return self._dict[key + self.suffix] def __len__(self): return len(self._dict) def __iter__(self): for key in self._dict: if key.endswith(self.suffix): yield key.replace(self.suffix, '') class LazyLoader(salt.utils.lazy.LazyDict): ''' A pseduo-dictionary which has a set of keys which are the name of the module and function, delimited by a dot. When the value of the key is accessed, the function is then loaded from disk and into memory. .. note:: Iterating over keys will cause all modules to be loaded. :param list module_dirs: A list of directories on disk to search for modules :param dict opts: The salt options dictionary. :param str tag: The tag for the type of module to load :param func mod_type_check: A function which can be used to verify files :param dict pack: A dictionary of function to be packed into modules as they are loaded :param list whitelist: A list of modules to whitelist :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules. :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality. If not true, the module will not load. :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values are function references themselves which are loaded on-demand. # TODO: - move modules_max_memory into here - singletons (per tag) ''' mod_dict_class = salt.utils.odict.OrderedDict def __init__(self, module_dirs, opts=None, tag='module', loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, proxy=None, virtual_funcs=None, ): # pylint: disable=W0231 ''' In pack, if any of the values are None they will be replaced with an empty context-specific dict ''' self.inject_globals = {} self.pack = {} if pack is None else pack if opts is None: opts = {} threadsafety = not opts.get('multiprocessing') self.context_dict = salt.utils.context.ContextDict(threadsafe=threadsafety) self.opts = self.__prep_mod_opts(opts) self.module_dirs = module_dirs self.tag = tag self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME self.mod_type_check = mod_type_check or _mod_type if '__context__' not in self.pack: self.pack['__context__'] = None for k, v in six.iteritems(self.pack): if v is None: # if the value of a pack is None, lets make an empty dict value = self.context_dict.get(k, {}) if isinstance(value, ThreadLocalProxy): value = ThreadLocalProxy.unproxy(value) self.context_dict[k] = value self.pack[k] = salt.utils.context.NamespacedDictWrapper(self.context_dict, k) self.whitelist = whitelist self.virtual_enable = virtual_enable self.initial_load = True # names of modules that we don't have (errors, __virtual__, etc.) self.missing_modules = {} # mapping of name -> error self.loaded_modules = {} # mapping of module_name -> dict_of_functions self.loaded_files = set() # TODO: just remove them from file_mapping? self.static_modules = static_modules if static_modules else [] if virtual_funcs is None: virtual_funcs = [] self.virtual_funcs = virtual_funcs self.disabled = set( self.opts.get( 'disable_{0}{1}'.format( self.tag, '' if self.tag[-1] == 's' else 's' ), [] ) ) # A map of suffix to description for imp self.suffix_map = {} # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [''] for (suffix, mode, kind) in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) self._lock = threading.RLock() self._refresh_file_mapping() super(LazyLoader, self).__init__() # late init the lazy loader # create all of the import namespaces _generate_module('{0}.int'.format(self.loaded_base_name)) _generate_module('{0}.int.{1}'.format(self.loaded_base_name, tag)) _generate_module('{0}.ext'.format(self.loaded_base_name)) _generate_module('{0}.ext.{1}'.format(self.loaded_base_name, tag)) def __getitem__(self, item): ''' Override the __getitem__ in order to decorate the returned function if we need to last-minute inject globals ''' func = super(LazyLoader, self).__getitem__(item) if self.inject_globals: return global_injector_decorator(self.inject_globals)(func) else: return func def __getattr__(self, mod_name): ''' Allow for "direct" attribute access-- this allows jinja templates to access things like `salt.test.ping()` ''' if mod_name in ('__getstate__', '__setstate__'): return object.__getattribute__(self, mod_name) # if we have an attribute named that, lets return it. try: return object.__getattr__(self, mod_name) # pylint: disable=no-member except AttributeError: pass # otherwise we assume its jinja template access if mod_name not in self.loaded_modules and not self.loaded: for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and mod_name in self.loaded_modules: break if mod_name in self.loaded_modules: return self.loaded_modules[mod_name] else: raise AttributeError(mod_name) def missing_fun_string(self, function_name): ''' Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ''' mod_name = function_name.split('.')[0] if mod_name in self.loaded_modules: return '\'{0}\' is not available.'.format(function_name) else: try: reason = self.missing_modules[mod_name] except KeyError: return '\'{0}\' is not available.'.format(function_name) else: if reason is not None: return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason) else: return '\'{0}\' __virtual__ returned False'.format(mod_name) def _refresh_file_mapping(self): ''' refresh the mapping of the FS on disk ''' # map of suffix to description for imp if self.opts.get('cython_enable', True) is True: try: global pyximport pyximport = __import__('pyximport') # pylint: disable=import-error pyximport.install() # add to suffix_map so file_mapping will pick it up self.suffix_map['.pyx'] = tuple() except ImportError: log.info('Cython is enabled in the options but not present ' 'in the system path. Skipping Cython modules.') # Allow for zipimport of modules if self.opts.get('enable_zip_modules', True) is True: self.suffix_map['.zip'] = tuple() # allow for module dirs if USE_IMPORTLIB: self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY) else: self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY) # create mapping of filename (without suffix) to (path, suffix) # The files are added in order of priority, so order *must* be retained. self.file_mapping = salt.utils.odict.OrderedDict() opt_match = [] def _replace_pre_ext(obj): ''' Hack so we can get the optimization level that we replaced (if any) out of the re.sub call below. We use a list here because it is a persistent data structure that we will be able to access after re.sub is called. ''' opt_match.append(obj) return '' for mod_dir in self.module_dirs: try: # Make sure we have a sorted listdir in order to have # expectable override results files = sorted( x for x in os.listdir(mod_dir) if x != '__pycache__' ) except OSError: continue # Next mod_dir if six.PY3: try: pycache_files = [ os.path.join('__pycache__', x) for x in sorted(os.listdir(os.path.join(mod_dir, '__pycache__'))) ] except OSError: pass else: files.extend(pycache_files) for filename in files: try: dirname, basename = os.path.split(filename) if basename.startswith('_'): # skip private modules # log messages omitted for obviousness continue # Next filename f_noext, ext = os.path.splitext(basename) if six.PY3: f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext) try: opt_level = int( opt_match.pop().group(1).rsplit('-', 1)[-1] ) except (AttributeError, IndexError, ValueError): # No regex match or no optimization level matched opt_level = 0 try: opt_index = self.opts['optimization_order'].index(opt_level) except KeyError: log.trace( 'Disallowed optimization level %d for module ' 'name \'%s\', skipping. Add %d to the ' '\'optimization_order\' config option if you ' 'do not want to ignore this optimization ' 'level.', opt_level, f_noext, opt_level ) continue else: # Optimization level not reflected in filename on PY2 opt_index = 0 # make sure it is a suffix we support if ext not in self.suffix_map: continue # Next filename if f_noext in self.disabled: log.trace( 'Skipping %s, it is disabled by configuration', filename ) continue # Next filename fpath = os.path.join(mod_dir, filename) # if its a directory, lets allow us to load that if ext == '': # is there something __init__? subfiles = os.listdir(fpath) for suffix in self.suffix_order: if '' == suffix: continue # Next suffix (__init__ must have a suffix) init_file = '__init__{0}'.format(suffix) if init_file in subfiles: break else: continue # Next filename try: curr_ext = self.file_mapping[f_noext][1] curr_opt_index = self.file_mapping[f_noext][2] except KeyError: pass else: if '' in (curr_ext, ext) and curr_ext != ext: log.error( 'Module/package collision: \'%s\' and \'%s\'', fpath, self.file_mapping[f_noext][0] ) if six.PY3 and ext == '.pyc' and curr_ext == '.pyc': # Check the optimization level if opt_index >= curr_opt_index: # Module name match, but a higher-priority # optimization level was already matched, skipping. continue elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext): # Match found but a higher-priorty match already # exists, so skip this. continue if six.PY3 and not dirname and ext == '.pyc': # On Python 3, we should only load .pyc files from the # __pycache__ subdirectory (i.e. when dirname is not an # empty string). continue # Made it this far - add it self.file_mapping[f_noext] = (fpath, ext, opt_index) except OSError: continue for smod in self.static_modules: f_noext = smod.split('.')[-1] self.file_mapping[f_noext] = (smod, '.o', 0) def clear(self): ''' Clear the dict ''' with self._lock: super(LazyLoader, self).clear() # clear the lazy loader self.loaded_files = set() self.missing_modules = {} self.loaded_modules = {} # if we have been loaded before, lets clear the file mapping since # we obviously want a re-do if hasattr(self, 'opts'): self._refresh_file_mapping() self.initial_load = False def __prep_mod_opts(self, opts): ''' Strip out of the opts any logger instance ''' if '__grains__' not in self.pack: grains = opts.get('grains', {}) if isinstance(grains, ThreadLocalProxy): grains = ThreadLocalProxy.unproxy(grains) self.context_dict['grains'] = grains self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains') if '__pillar__' not in self.pack: pillar = opts.get('pillar', {}) if isinstance(pillar, ThreadLocalProxy): pillar = ThreadLocalProxy.unproxy(pillar) self.context_dict['pillar'] = pillar self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar') mod_opts = {} for key, val in list(opts.items()): if key == 'logger': continue mod_opts[key] = val return mod_opts def _iter_files(self, mod_name): ''' Iterate over all file_mapping files in order of closeness to mod_name ''' # do we have an exact match? if mod_name in self.file_mapping: yield mod_name # do we have a partial match? for k in self.file_mapping: if mod_name in k: yield k # anyone else? Bueller? for k in self.file_mapping: if mod_name not in k: yield k def _reload_submodules(self, mod): submodules = ( getattr(mod, sname) for sname in dir(mod) if isinstance(getattr(mod, sname), mod.__class__) ) # reload only custom "sub"modules for submodule in submodules: # it is a submodule if the name is in a namespace under mod if submodule.__name__.startswith(mod.__name__ + '.'): reload_module(submodule) self._reload_submodules(submodule) def _load_module(self, name): mod = None fpath, suffix = self.file_mapping[name][:2] self.loaded_files.add(name) fpath_dirname = os.path.dirname(fpath) try: sys.path.append(fpath_dirname) if suffix == '.pyx': mod = pyximport.load_module(name, fpath, tempfile.gettempdir()) elif suffix == '.o': top_mod = __import__(fpath, globals(), locals(), []) comps = fpath.split('.') if len(comps) < 2: mod = top_mod else: mod = top_mod for subname in comps[1:]: mod = getattr(mod, subname) elif suffix == '.zip': mod = zipimporter(fpath).load_module(name) else: desc = self.suffix_map[suffix] # if it is a directory, we don't open a file try: mod_namespace = '.'.join(( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name)) except TypeError: mod_namespace = '{0}.{1}.{2}.{3}'.format( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name) if suffix == '': if USE_IMPORTLIB: # pylint: disable=no-member # Package directory, look for __init__ loader_details = [ (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES), (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES), (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), ] file_finder = importlib.machinery.FileFinder( fpath_dirname, *loader_details ) spec = file_finder.find_spec(mod_namespace) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: mod = imp.load_module(mod_namespace, None, fpath, desc) # reload all submodules if necessary if not self.initial_load: self._reload_submodules(mod) else: if USE_IMPORTLIB: # pylint: disable=no-member loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath) spec = importlib.util.spec_from_file_location( mod_namespace, fpath, loader=loader ) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() #mod = importlib.util.module_from_spec(spec) #spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: with salt.utils.files.fopen(fpath, desc[1]) as fn_: mod = imp.load_module(mod_namespace, fn_, fpath, desc) except IOError: raise except ImportError as exc: if 'magic number' in six.text_type(exc): error_msg = 'Failed to import {0} {1}. Bad magic number. If migrating from Python2 to Python3, remove all .pyc files and try again.'.format(self.tag, name) log.warning(error_msg) self.missing_modules[name] = error_msg log.debug( 'Failed to import %s %s:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = exc return False except Exception as error: log.error( 'Failed to import %s %s, this is due most likely to a ' 'syntax error:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False except SystemExit as error: try: fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1] except Exception: pass else: tgt_fn = os.path.join('salt', 'utils', 'process.py') if fn_.endswith(tgt_fn) and '_handle_signals' in caller: # Race conditon, SIGTERM or SIGINT received while loader # was in process of loading a module. Call sys.exit to # ensure that the process is killed. sys.exit(salt.defaults.exitcodes.EX_OK) log.error( 'Failed to import %s %s as the module called exit()\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False finally: sys.path.remove(fpath_dirname) if hasattr(mod, '__opts__'): mod.__opts__.update(self.opts) else: mod.__opts__ = self.opts # pack whatever other globals we were asked to for p_name, p_value in six.iteritems(self.pack): _inject_into_mod(mod, p_name, p_value) module_name = mod.__name__.rsplit('.', 1)[-1] # Call a module's initialization method if it exists module_init = getattr(mod, '__init__', None) if inspect.isfunction(module_init): try: module_init(self.opts) except TypeError as e: log.error(e) except Exception: err_string = '__init__ failed' log.debug( 'Error loading %s.%s: %s', self.tag, module_name, err_string, exc_info=True ) self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False # if virtual modules are enabled, we need to look for the # __virtual__() function inside that module and run it. if self.virtual_enable: virtual_funcs_to_process = ['__virtual__'] + self.virtual_funcs for virtual_func in virtual_funcs_to_process: virtual_ret, module_name, virtual_err, virtual_aliases = \ self._process_virtual(mod, module_name, virtual_func) if virtual_err is not None: log.trace( 'Error loading %s.%s: %s', self.tag, module_name, virtual_err ) # if _process_virtual returned a non-True value then we are # supposed to not process this module if virtual_ret is not True and module_name not in self.missing_modules: # If a module has information about why it could not be loaded, record it self.missing_modules[module_name] = virtual_err self.missing_modules[name] = virtual_err return False else: virtual_aliases = () # If this is a proxy minion then MOST modules cannot work. Therefore, require that # any module that does work with salt-proxy-minion define __proxyenabled__ as a list # containing the names of the proxy types that the module supports. # # Render modules and state modules are OK though if 'proxy' in self.opts: if self.tag in ['grains', 'proxy']: if not hasattr(mod, '__proxyenabled__') or \ (self.opts['proxy']['proxytype'] not in mod.__proxyenabled__ and '*' not in mod.__proxyenabled__): err_string = 'not a proxy_minion enabled module' self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False if getattr(mod, '__load__', False) is not False: log.info( 'The functions from module \'%s\' are being loaded from the ' 'provided __load__ attribute', module_name ) # If we had another module by the same virtual name, we should put any # new functions under the existing dictionary. mod_names = [module_name] + list(virtual_aliases) mod_dict = dict(( (x, self.loaded_modules.get(x, self.mod_dict_class())) for x in mod_names )) for attr in getattr(mod, '__load__', dir(mod)): if attr.startswith('_') and attr != '__call__': # private functions are skipped, # except __call__ which is default entrance # for multi-function batch-like state syntax continue func = getattr(mod, attr) if not inspect.isfunction(func) and not isinstance(func, functools.partial): # Not a function!? Skip it!!! continue # Let's get the function name. # If the module has the __func_alias__ attribute, it must be a # dictionary mapping in the form of(key -> value): # <real-func-name> -> <desired-func-name> # # It default's of course to the found callable attribute name # if no alias is defined. funcname = getattr(mod, '__func_alias__', {}).get(attr, attr) for tgt_mod in mod_names: try: full_funcname = '.'.join((tgt_mod, funcname)) except TypeError: full_funcname = '{0}.{1}'.format(tgt_mod, funcname) # Save many references for lookups # Careful not to overwrite existing (higher priority) functions if full_funcname not in self._dict: self._dict[full_funcname] = func if funcname not in mod_dict[tgt_mod]: setattr(mod_dict[tgt_mod], funcname, func) mod_dict[tgt_mod][funcname] = func self._apply_outputter(func, mod) # enforce depends try: Depends.enforce_dependencies(self._dict, self.tag) except RuntimeError as exc: log.info( 'Depends.enforce_dependencies() failed for the following ' 'reason: %s', exc ) for tgt_mod in mod_names: self.loaded_modules[tgt_mod] = mod_dict[tgt_mod] return True def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise KeyError('The key \'{0}\' should contain a \'.\''.format(key)) mod_name, _ = key.split('.', 1) with self._lock: # It is possible that the key is in the dictionary after # acquiring the lock due to another thread loading it. if mod_name in self.missing_modules or key in self._dict: return True # if the modulename isn't in the whitelist, don't bother if self.whitelist and mod_name not in self.whitelist: log.error( 'Failed to load function %s because its module (%s) is ' 'not in the whitelist: %s', key, mod_name, self.whitelist ) raise KeyError(key) def _inner_load(mod_name): for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and key in self._dict: return True return False # try to load the module ret = None reloaded = False # re-scan up to once, IOErrors or a failed load cause re-scans of the # filesystem while True: try: ret = _inner_load(mod_name) if not reloaded and ret is not True: self._refresh_file_mapping() reloaded = True continue break except IOError: if not reloaded: self._refresh_file_mapping() reloaded = True continue return ret def _load_all(self): ''' Load all of them ''' with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True def reload_modules(self): with self._lock: self.loaded_files = set() self._load_all() def _apply_outputter(self, func, mod): ''' Apply the __outputter__ variable to the functions ''' if hasattr(mod, '__outputter__'): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__] def _process_virtual(self, mod, module_name, virtual_func='__virtual__'): ''' Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1] ''' # The __virtual__ function will return either a True or False value. # If it returns a True value it can also set a module level attribute # named __virtualname__ with the name that the module should be # referred to as. # # This allows us to have things like the pkg module working on all # platforms under the name 'pkg'. It also allows for modules like # augeas_cfg to be referred to as 'augeas', which would otherwise have # namespace collisions. And finally it allows modules to return False # if they are not intended to run on the given platform or are missing # dependencies. virtual_aliases = getattr(mod, '__virtual_aliases__', tuple()) try: error_reason = None if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__): try: start = time.time() virtual = getattr(mod, virtual_func)() if isinstance(virtual, tuple): error_reason = virtual[1] virtual = virtual[0] if self.opts.get('virtual_timer', False): end = time.time() - start msg = 'Virtual function took {0} seconds for {1}'.format( end, module_name) log.warning(msg) except Exception as exc: error_reason = ( 'Exception raised when processing __virtual__ function' ' for {0}. Module will not be loaded: {1}'.format( mod.__name__, exc)) log.error(error_reason, exc_info_on_loglevel=logging.DEBUG) virtual = None # Get the module's virtual name virtualname = getattr(mod, '__virtualname__', virtual) if not virtual: # if __virtual__() evaluates to False then the module # wasn't meant for this platform or it's not supposed to # load for some other reason. # Some modules might accidentally return None and are # improperly loaded if virtual is None: log.warning( '%s.__virtual__() is wrongly returning `None`. ' 'It should either return `True`, `False` or a new ' 'name. If you\'re the developer of the module ' '\'%s\', please fix this.', mod.__name__, module_name ) return (False, module_name, error_reason, virtual_aliases) # At this point, __virtual__ did not return a # boolean value, let's check for deprecated usage # or module renames if virtual is not True and module_name != virtual: # The module is renaming itself. Updating the module name # with the new name log.trace('Loaded %s as virtual %s', module_name, virtual) if virtualname != virtual: # The __virtualname__ attribute does not match what's # being returned by the __virtual__() function. This # should be considered an error. log.error( 'The module \'%s\' is showing some bad usage. Its ' '__virtualname__ attribute is set to \'%s\' yet the ' '__virtual__() function is returning \'%s\'. These ' 'values should match!', mod.__name__, virtualname, virtual ) module_name = virtualname # If the __virtual__ function returns True and __virtualname__ # is set then use it elif virtual is True and virtualname != module_name: if virtualname is not True: module_name = virtualname except KeyError: # Key errors come out of the virtual function when passing # in incomplete grains sets, these can be safely ignored # and logged to debug, still, it includes the traceback to # help debugging. log.debug('KeyError when loading %s', module_name, exc_info=True) except Exception: # If the module throws an exception during __virtual__() # then log the information and continue to the next. log.error( 'Failed to read the virtual function for %s: %s', self.tag, module_name, exc_info=True ) return (False, module_name, error_reason, virtual_aliases) return (True, module_name, None, virtual_aliases)
saltstack/salt
salt/loader.py
LazyLoader.missing_fun_string
python
def missing_fun_string(self, function_name): ''' Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ''' mod_name = function_name.split('.')[0] if mod_name in self.loaded_modules: return '\'{0}\' is not available.'.format(function_name) else: try: reason = self.missing_modules[mod_name] except KeyError: return '\'{0}\' is not available.'.format(function_name) else: if reason is not None: return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason) else: return '\'{0}\' __virtual__ returned False'.format(mod_name)
Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L1348-L1366
null
class LazyLoader(salt.utils.lazy.LazyDict): ''' A pseduo-dictionary which has a set of keys which are the name of the module and function, delimited by a dot. When the value of the key is accessed, the function is then loaded from disk and into memory. .. note:: Iterating over keys will cause all modules to be loaded. :param list module_dirs: A list of directories on disk to search for modules :param dict opts: The salt options dictionary. :param str tag: The tag for the type of module to load :param func mod_type_check: A function which can be used to verify files :param dict pack: A dictionary of function to be packed into modules as they are loaded :param list whitelist: A list of modules to whitelist :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules. :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality. If not true, the module will not load. :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values are function references themselves which are loaded on-demand. # TODO: - move modules_max_memory into here - singletons (per tag) ''' mod_dict_class = salt.utils.odict.OrderedDict def __init__(self, module_dirs, opts=None, tag='module', loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, proxy=None, virtual_funcs=None, ): # pylint: disable=W0231 ''' In pack, if any of the values are None they will be replaced with an empty context-specific dict ''' self.inject_globals = {} self.pack = {} if pack is None else pack if opts is None: opts = {} threadsafety = not opts.get('multiprocessing') self.context_dict = salt.utils.context.ContextDict(threadsafe=threadsafety) self.opts = self.__prep_mod_opts(opts) self.module_dirs = module_dirs self.tag = tag self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME self.mod_type_check = mod_type_check or _mod_type if '__context__' not in self.pack: self.pack['__context__'] = None for k, v in six.iteritems(self.pack): if v is None: # if the value of a pack is None, lets make an empty dict value = self.context_dict.get(k, {}) if isinstance(value, ThreadLocalProxy): value = ThreadLocalProxy.unproxy(value) self.context_dict[k] = value self.pack[k] = salt.utils.context.NamespacedDictWrapper(self.context_dict, k) self.whitelist = whitelist self.virtual_enable = virtual_enable self.initial_load = True # names of modules that we don't have (errors, __virtual__, etc.) self.missing_modules = {} # mapping of name -> error self.loaded_modules = {} # mapping of module_name -> dict_of_functions self.loaded_files = set() # TODO: just remove them from file_mapping? self.static_modules = static_modules if static_modules else [] if virtual_funcs is None: virtual_funcs = [] self.virtual_funcs = virtual_funcs self.disabled = set( self.opts.get( 'disable_{0}{1}'.format( self.tag, '' if self.tag[-1] == 's' else 's' ), [] ) ) # A map of suffix to description for imp self.suffix_map = {} # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [''] for (suffix, mode, kind) in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) self._lock = threading.RLock() self._refresh_file_mapping() super(LazyLoader, self).__init__() # late init the lazy loader # create all of the import namespaces _generate_module('{0}.int'.format(self.loaded_base_name)) _generate_module('{0}.int.{1}'.format(self.loaded_base_name, tag)) _generate_module('{0}.ext'.format(self.loaded_base_name)) _generate_module('{0}.ext.{1}'.format(self.loaded_base_name, tag)) def __getitem__(self, item): ''' Override the __getitem__ in order to decorate the returned function if we need to last-minute inject globals ''' func = super(LazyLoader, self).__getitem__(item) if self.inject_globals: return global_injector_decorator(self.inject_globals)(func) else: return func def __getattr__(self, mod_name): ''' Allow for "direct" attribute access-- this allows jinja templates to access things like `salt.test.ping()` ''' if mod_name in ('__getstate__', '__setstate__'): return object.__getattribute__(self, mod_name) # if we have an attribute named that, lets return it. try: return object.__getattr__(self, mod_name) # pylint: disable=no-member except AttributeError: pass # otherwise we assume its jinja template access if mod_name not in self.loaded_modules and not self.loaded: for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and mod_name in self.loaded_modules: break if mod_name in self.loaded_modules: return self.loaded_modules[mod_name] else: raise AttributeError(mod_name) def _refresh_file_mapping(self): ''' refresh the mapping of the FS on disk ''' # map of suffix to description for imp if self.opts.get('cython_enable', True) is True: try: global pyximport pyximport = __import__('pyximport') # pylint: disable=import-error pyximport.install() # add to suffix_map so file_mapping will pick it up self.suffix_map['.pyx'] = tuple() except ImportError: log.info('Cython is enabled in the options but not present ' 'in the system path. Skipping Cython modules.') # Allow for zipimport of modules if self.opts.get('enable_zip_modules', True) is True: self.suffix_map['.zip'] = tuple() # allow for module dirs if USE_IMPORTLIB: self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY) else: self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY) # create mapping of filename (without suffix) to (path, suffix) # The files are added in order of priority, so order *must* be retained. self.file_mapping = salt.utils.odict.OrderedDict() opt_match = [] def _replace_pre_ext(obj): ''' Hack so we can get the optimization level that we replaced (if any) out of the re.sub call below. We use a list here because it is a persistent data structure that we will be able to access after re.sub is called. ''' opt_match.append(obj) return '' for mod_dir in self.module_dirs: try: # Make sure we have a sorted listdir in order to have # expectable override results files = sorted( x for x in os.listdir(mod_dir) if x != '__pycache__' ) except OSError: continue # Next mod_dir if six.PY3: try: pycache_files = [ os.path.join('__pycache__', x) for x in sorted(os.listdir(os.path.join(mod_dir, '__pycache__'))) ] except OSError: pass else: files.extend(pycache_files) for filename in files: try: dirname, basename = os.path.split(filename) if basename.startswith('_'): # skip private modules # log messages omitted for obviousness continue # Next filename f_noext, ext = os.path.splitext(basename) if six.PY3: f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext) try: opt_level = int( opt_match.pop().group(1).rsplit('-', 1)[-1] ) except (AttributeError, IndexError, ValueError): # No regex match or no optimization level matched opt_level = 0 try: opt_index = self.opts['optimization_order'].index(opt_level) except KeyError: log.trace( 'Disallowed optimization level %d for module ' 'name \'%s\', skipping. Add %d to the ' '\'optimization_order\' config option if you ' 'do not want to ignore this optimization ' 'level.', opt_level, f_noext, opt_level ) continue else: # Optimization level not reflected in filename on PY2 opt_index = 0 # make sure it is a suffix we support if ext not in self.suffix_map: continue # Next filename if f_noext in self.disabled: log.trace( 'Skipping %s, it is disabled by configuration', filename ) continue # Next filename fpath = os.path.join(mod_dir, filename) # if its a directory, lets allow us to load that if ext == '': # is there something __init__? subfiles = os.listdir(fpath) for suffix in self.suffix_order: if '' == suffix: continue # Next suffix (__init__ must have a suffix) init_file = '__init__{0}'.format(suffix) if init_file in subfiles: break else: continue # Next filename try: curr_ext = self.file_mapping[f_noext][1] curr_opt_index = self.file_mapping[f_noext][2] except KeyError: pass else: if '' in (curr_ext, ext) and curr_ext != ext: log.error( 'Module/package collision: \'%s\' and \'%s\'', fpath, self.file_mapping[f_noext][0] ) if six.PY3 and ext == '.pyc' and curr_ext == '.pyc': # Check the optimization level if opt_index >= curr_opt_index: # Module name match, but a higher-priority # optimization level was already matched, skipping. continue elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext): # Match found but a higher-priorty match already # exists, so skip this. continue if six.PY3 and not dirname and ext == '.pyc': # On Python 3, we should only load .pyc files from the # __pycache__ subdirectory (i.e. when dirname is not an # empty string). continue # Made it this far - add it self.file_mapping[f_noext] = (fpath, ext, opt_index) except OSError: continue for smod in self.static_modules: f_noext = smod.split('.')[-1] self.file_mapping[f_noext] = (smod, '.o', 0) def clear(self): ''' Clear the dict ''' with self._lock: super(LazyLoader, self).clear() # clear the lazy loader self.loaded_files = set() self.missing_modules = {} self.loaded_modules = {} # if we have been loaded before, lets clear the file mapping since # we obviously want a re-do if hasattr(self, 'opts'): self._refresh_file_mapping() self.initial_load = False def __prep_mod_opts(self, opts): ''' Strip out of the opts any logger instance ''' if '__grains__' not in self.pack: grains = opts.get('grains', {}) if isinstance(grains, ThreadLocalProxy): grains = ThreadLocalProxy.unproxy(grains) self.context_dict['grains'] = grains self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains') if '__pillar__' not in self.pack: pillar = opts.get('pillar', {}) if isinstance(pillar, ThreadLocalProxy): pillar = ThreadLocalProxy.unproxy(pillar) self.context_dict['pillar'] = pillar self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar') mod_opts = {} for key, val in list(opts.items()): if key == 'logger': continue mod_opts[key] = val return mod_opts def _iter_files(self, mod_name): ''' Iterate over all file_mapping files in order of closeness to mod_name ''' # do we have an exact match? if mod_name in self.file_mapping: yield mod_name # do we have a partial match? for k in self.file_mapping: if mod_name in k: yield k # anyone else? Bueller? for k in self.file_mapping: if mod_name not in k: yield k def _reload_submodules(self, mod): submodules = ( getattr(mod, sname) for sname in dir(mod) if isinstance(getattr(mod, sname), mod.__class__) ) # reload only custom "sub"modules for submodule in submodules: # it is a submodule if the name is in a namespace under mod if submodule.__name__.startswith(mod.__name__ + '.'): reload_module(submodule) self._reload_submodules(submodule) def _load_module(self, name): mod = None fpath, suffix = self.file_mapping[name][:2] self.loaded_files.add(name) fpath_dirname = os.path.dirname(fpath) try: sys.path.append(fpath_dirname) if suffix == '.pyx': mod = pyximport.load_module(name, fpath, tempfile.gettempdir()) elif suffix == '.o': top_mod = __import__(fpath, globals(), locals(), []) comps = fpath.split('.') if len(comps) < 2: mod = top_mod else: mod = top_mod for subname in comps[1:]: mod = getattr(mod, subname) elif suffix == '.zip': mod = zipimporter(fpath).load_module(name) else: desc = self.suffix_map[suffix] # if it is a directory, we don't open a file try: mod_namespace = '.'.join(( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name)) except TypeError: mod_namespace = '{0}.{1}.{2}.{3}'.format( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name) if suffix == '': if USE_IMPORTLIB: # pylint: disable=no-member # Package directory, look for __init__ loader_details = [ (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES), (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES), (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), ] file_finder = importlib.machinery.FileFinder( fpath_dirname, *loader_details ) spec = file_finder.find_spec(mod_namespace) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: mod = imp.load_module(mod_namespace, None, fpath, desc) # reload all submodules if necessary if not self.initial_load: self._reload_submodules(mod) else: if USE_IMPORTLIB: # pylint: disable=no-member loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath) spec = importlib.util.spec_from_file_location( mod_namespace, fpath, loader=loader ) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() #mod = importlib.util.module_from_spec(spec) #spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: with salt.utils.files.fopen(fpath, desc[1]) as fn_: mod = imp.load_module(mod_namespace, fn_, fpath, desc) except IOError: raise except ImportError as exc: if 'magic number' in six.text_type(exc): error_msg = 'Failed to import {0} {1}. Bad magic number. If migrating from Python2 to Python3, remove all .pyc files and try again.'.format(self.tag, name) log.warning(error_msg) self.missing_modules[name] = error_msg log.debug( 'Failed to import %s %s:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = exc return False except Exception as error: log.error( 'Failed to import %s %s, this is due most likely to a ' 'syntax error:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False except SystemExit as error: try: fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1] except Exception: pass else: tgt_fn = os.path.join('salt', 'utils', 'process.py') if fn_.endswith(tgt_fn) and '_handle_signals' in caller: # Race conditon, SIGTERM or SIGINT received while loader # was in process of loading a module. Call sys.exit to # ensure that the process is killed. sys.exit(salt.defaults.exitcodes.EX_OK) log.error( 'Failed to import %s %s as the module called exit()\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False finally: sys.path.remove(fpath_dirname) if hasattr(mod, '__opts__'): mod.__opts__.update(self.opts) else: mod.__opts__ = self.opts # pack whatever other globals we were asked to for p_name, p_value in six.iteritems(self.pack): _inject_into_mod(mod, p_name, p_value) module_name = mod.__name__.rsplit('.', 1)[-1] # Call a module's initialization method if it exists module_init = getattr(mod, '__init__', None) if inspect.isfunction(module_init): try: module_init(self.opts) except TypeError as e: log.error(e) except Exception: err_string = '__init__ failed' log.debug( 'Error loading %s.%s: %s', self.tag, module_name, err_string, exc_info=True ) self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False # if virtual modules are enabled, we need to look for the # __virtual__() function inside that module and run it. if self.virtual_enable: virtual_funcs_to_process = ['__virtual__'] + self.virtual_funcs for virtual_func in virtual_funcs_to_process: virtual_ret, module_name, virtual_err, virtual_aliases = \ self._process_virtual(mod, module_name, virtual_func) if virtual_err is not None: log.trace( 'Error loading %s.%s: %s', self.tag, module_name, virtual_err ) # if _process_virtual returned a non-True value then we are # supposed to not process this module if virtual_ret is not True and module_name not in self.missing_modules: # If a module has information about why it could not be loaded, record it self.missing_modules[module_name] = virtual_err self.missing_modules[name] = virtual_err return False else: virtual_aliases = () # If this is a proxy minion then MOST modules cannot work. Therefore, require that # any module that does work with salt-proxy-minion define __proxyenabled__ as a list # containing the names of the proxy types that the module supports. # # Render modules and state modules are OK though if 'proxy' in self.opts: if self.tag in ['grains', 'proxy']: if not hasattr(mod, '__proxyenabled__') or \ (self.opts['proxy']['proxytype'] not in mod.__proxyenabled__ and '*' not in mod.__proxyenabled__): err_string = 'not a proxy_minion enabled module' self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False if getattr(mod, '__load__', False) is not False: log.info( 'The functions from module \'%s\' are being loaded from the ' 'provided __load__ attribute', module_name ) # If we had another module by the same virtual name, we should put any # new functions under the existing dictionary. mod_names = [module_name] + list(virtual_aliases) mod_dict = dict(( (x, self.loaded_modules.get(x, self.mod_dict_class())) for x in mod_names )) for attr in getattr(mod, '__load__', dir(mod)): if attr.startswith('_') and attr != '__call__': # private functions are skipped, # except __call__ which is default entrance # for multi-function batch-like state syntax continue func = getattr(mod, attr) if not inspect.isfunction(func) and not isinstance(func, functools.partial): # Not a function!? Skip it!!! continue # Let's get the function name. # If the module has the __func_alias__ attribute, it must be a # dictionary mapping in the form of(key -> value): # <real-func-name> -> <desired-func-name> # # It default's of course to the found callable attribute name # if no alias is defined. funcname = getattr(mod, '__func_alias__', {}).get(attr, attr) for tgt_mod in mod_names: try: full_funcname = '.'.join((tgt_mod, funcname)) except TypeError: full_funcname = '{0}.{1}'.format(tgt_mod, funcname) # Save many references for lookups # Careful not to overwrite existing (higher priority) functions if full_funcname not in self._dict: self._dict[full_funcname] = func if funcname not in mod_dict[tgt_mod]: setattr(mod_dict[tgt_mod], funcname, func) mod_dict[tgt_mod][funcname] = func self._apply_outputter(func, mod) # enforce depends try: Depends.enforce_dependencies(self._dict, self.tag) except RuntimeError as exc: log.info( 'Depends.enforce_dependencies() failed for the following ' 'reason: %s', exc ) for tgt_mod in mod_names: self.loaded_modules[tgt_mod] = mod_dict[tgt_mod] return True def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise KeyError('The key \'{0}\' should contain a \'.\''.format(key)) mod_name, _ = key.split('.', 1) with self._lock: # It is possible that the key is in the dictionary after # acquiring the lock due to another thread loading it. if mod_name in self.missing_modules or key in self._dict: return True # if the modulename isn't in the whitelist, don't bother if self.whitelist and mod_name not in self.whitelist: log.error( 'Failed to load function %s because its module (%s) is ' 'not in the whitelist: %s', key, mod_name, self.whitelist ) raise KeyError(key) def _inner_load(mod_name): for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and key in self._dict: return True return False # try to load the module ret = None reloaded = False # re-scan up to once, IOErrors or a failed load cause re-scans of the # filesystem while True: try: ret = _inner_load(mod_name) if not reloaded and ret is not True: self._refresh_file_mapping() reloaded = True continue break except IOError: if not reloaded: self._refresh_file_mapping() reloaded = True continue return ret def _load_all(self): ''' Load all of them ''' with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True def reload_modules(self): with self._lock: self.loaded_files = set() self._load_all() def _apply_outputter(self, func, mod): ''' Apply the __outputter__ variable to the functions ''' if hasattr(mod, '__outputter__'): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__] def _process_virtual(self, mod, module_name, virtual_func='__virtual__'): ''' Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1] ''' # The __virtual__ function will return either a True or False value. # If it returns a True value it can also set a module level attribute # named __virtualname__ with the name that the module should be # referred to as. # # This allows us to have things like the pkg module working on all # platforms under the name 'pkg'. It also allows for modules like # augeas_cfg to be referred to as 'augeas', which would otherwise have # namespace collisions. And finally it allows modules to return False # if they are not intended to run on the given platform or are missing # dependencies. virtual_aliases = getattr(mod, '__virtual_aliases__', tuple()) try: error_reason = None if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__): try: start = time.time() virtual = getattr(mod, virtual_func)() if isinstance(virtual, tuple): error_reason = virtual[1] virtual = virtual[0] if self.opts.get('virtual_timer', False): end = time.time() - start msg = 'Virtual function took {0} seconds for {1}'.format( end, module_name) log.warning(msg) except Exception as exc: error_reason = ( 'Exception raised when processing __virtual__ function' ' for {0}. Module will not be loaded: {1}'.format( mod.__name__, exc)) log.error(error_reason, exc_info_on_loglevel=logging.DEBUG) virtual = None # Get the module's virtual name virtualname = getattr(mod, '__virtualname__', virtual) if not virtual: # if __virtual__() evaluates to False then the module # wasn't meant for this platform or it's not supposed to # load for some other reason. # Some modules might accidentally return None and are # improperly loaded if virtual is None: log.warning( '%s.__virtual__() is wrongly returning `None`. ' 'It should either return `True`, `False` or a new ' 'name. If you\'re the developer of the module ' '\'%s\', please fix this.', mod.__name__, module_name ) return (False, module_name, error_reason, virtual_aliases) # At this point, __virtual__ did not return a # boolean value, let's check for deprecated usage # or module renames if virtual is not True and module_name != virtual: # The module is renaming itself. Updating the module name # with the new name log.trace('Loaded %s as virtual %s', module_name, virtual) if virtualname != virtual: # The __virtualname__ attribute does not match what's # being returned by the __virtual__() function. This # should be considered an error. log.error( 'The module \'%s\' is showing some bad usage. Its ' '__virtualname__ attribute is set to \'%s\' yet the ' '__virtual__() function is returning \'%s\'. These ' 'values should match!', mod.__name__, virtualname, virtual ) module_name = virtualname # If the __virtual__ function returns True and __virtualname__ # is set then use it elif virtual is True and virtualname != module_name: if virtualname is not True: module_name = virtualname except KeyError: # Key errors come out of the virtual function when passing # in incomplete grains sets, these can be safely ignored # and logged to debug, still, it includes the traceback to # help debugging. log.debug('KeyError when loading %s', module_name, exc_info=True) except Exception: # If the module throws an exception during __virtual__() # then log the information and continue to the next. log.error( 'Failed to read the virtual function for %s: %s', self.tag, module_name, exc_info=True ) return (False, module_name, error_reason, virtual_aliases) return (True, module_name, None, virtual_aliases)
saltstack/salt
salt/loader.py
LazyLoader._refresh_file_mapping
python
def _refresh_file_mapping(self): ''' refresh the mapping of the FS on disk ''' # map of suffix to description for imp if self.opts.get('cython_enable', True) is True: try: global pyximport pyximport = __import__('pyximport') # pylint: disable=import-error pyximport.install() # add to suffix_map so file_mapping will pick it up self.suffix_map['.pyx'] = tuple() except ImportError: log.info('Cython is enabled in the options but not present ' 'in the system path. Skipping Cython modules.') # Allow for zipimport of modules if self.opts.get('enable_zip_modules', True) is True: self.suffix_map['.zip'] = tuple() # allow for module dirs if USE_IMPORTLIB: self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY) else: self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY) # create mapping of filename (without suffix) to (path, suffix) # The files are added in order of priority, so order *must* be retained. self.file_mapping = salt.utils.odict.OrderedDict() opt_match = [] def _replace_pre_ext(obj): ''' Hack so we can get the optimization level that we replaced (if any) out of the re.sub call below. We use a list here because it is a persistent data structure that we will be able to access after re.sub is called. ''' opt_match.append(obj) return '' for mod_dir in self.module_dirs: try: # Make sure we have a sorted listdir in order to have # expectable override results files = sorted( x for x in os.listdir(mod_dir) if x != '__pycache__' ) except OSError: continue # Next mod_dir if six.PY3: try: pycache_files = [ os.path.join('__pycache__', x) for x in sorted(os.listdir(os.path.join(mod_dir, '__pycache__'))) ] except OSError: pass else: files.extend(pycache_files) for filename in files: try: dirname, basename = os.path.split(filename) if basename.startswith('_'): # skip private modules # log messages omitted for obviousness continue # Next filename f_noext, ext = os.path.splitext(basename) if six.PY3: f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext) try: opt_level = int( opt_match.pop().group(1).rsplit('-', 1)[-1] ) except (AttributeError, IndexError, ValueError): # No regex match or no optimization level matched opt_level = 0 try: opt_index = self.opts['optimization_order'].index(opt_level) except KeyError: log.trace( 'Disallowed optimization level %d for module ' 'name \'%s\', skipping. Add %d to the ' '\'optimization_order\' config option if you ' 'do not want to ignore this optimization ' 'level.', opt_level, f_noext, opt_level ) continue else: # Optimization level not reflected in filename on PY2 opt_index = 0 # make sure it is a suffix we support if ext not in self.suffix_map: continue # Next filename if f_noext in self.disabled: log.trace( 'Skipping %s, it is disabled by configuration', filename ) continue # Next filename fpath = os.path.join(mod_dir, filename) # if its a directory, lets allow us to load that if ext == '': # is there something __init__? subfiles = os.listdir(fpath) for suffix in self.suffix_order: if '' == suffix: continue # Next suffix (__init__ must have a suffix) init_file = '__init__{0}'.format(suffix) if init_file in subfiles: break else: continue # Next filename try: curr_ext = self.file_mapping[f_noext][1] curr_opt_index = self.file_mapping[f_noext][2] except KeyError: pass else: if '' in (curr_ext, ext) and curr_ext != ext: log.error( 'Module/package collision: \'%s\' and \'%s\'', fpath, self.file_mapping[f_noext][0] ) if six.PY3 and ext == '.pyc' and curr_ext == '.pyc': # Check the optimization level if opt_index >= curr_opt_index: # Module name match, but a higher-priority # optimization level was already matched, skipping. continue elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext): # Match found but a higher-priorty match already # exists, so skip this. continue if six.PY3 and not dirname and ext == '.pyc': # On Python 3, we should only load .pyc files from the # __pycache__ subdirectory (i.e. when dirname is not an # empty string). continue # Made it this far - add it self.file_mapping[f_noext] = (fpath, ext, opt_index) except OSError: continue for smod in self.static_modules: f_noext = smod.split('.')[-1] self.file_mapping[f_noext] = (smod, '.o', 0)
refresh the mapping of the FS on disk
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L1368-L1520
null
class LazyLoader(salt.utils.lazy.LazyDict): ''' A pseduo-dictionary which has a set of keys which are the name of the module and function, delimited by a dot. When the value of the key is accessed, the function is then loaded from disk and into memory. .. note:: Iterating over keys will cause all modules to be loaded. :param list module_dirs: A list of directories on disk to search for modules :param dict opts: The salt options dictionary. :param str tag: The tag for the type of module to load :param func mod_type_check: A function which can be used to verify files :param dict pack: A dictionary of function to be packed into modules as they are loaded :param list whitelist: A list of modules to whitelist :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules. :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality. If not true, the module will not load. :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values are function references themselves which are loaded on-demand. # TODO: - move modules_max_memory into here - singletons (per tag) ''' mod_dict_class = salt.utils.odict.OrderedDict def __init__(self, module_dirs, opts=None, tag='module', loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, proxy=None, virtual_funcs=None, ): # pylint: disable=W0231 ''' In pack, if any of the values are None they will be replaced with an empty context-specific dict ''' self.inject_globals = {} self.pack = {} if pack is None else pack if opts is None: opts = {} threadsafety = not opts.get('multiprocessing') self.context_dict = salt.utils.context.ContextDict(threadsafe=threadsafety) self.opts = self.__prep_mod_opts(opts) self.module_dirs = module_dirs self.tag = tag self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME self.mod_type_check = mod_type_check or _mod_type if '__context__' not in self.pack: self.pack['__context__'] = None for k, v in six.iteritems(self.pack): if v is None: # if the value of a pack is None, lets make an empty dict value = self.context_dict.get(k, {}) if isinstance(value, ThreadLocalProxy): value = ThreadLocalProxy.unproxy(value) self.context_dict[k] = value self.pack[k] = salt.utils.context.NamespacedDictWrapper(self.context_dict, k) self.whitelist = whitelist self.virtual_enable = virtual_enable self.initial_load = True # names of modules that we don't have (errors, __virtual__, etc.) self.missing_modules = {} # mapping of name -> error self.loaded_modules = {} # mapping of module_name -> dict_of_functions self.loaded_files = set() # TODO: just remove them from file_mapping? self.static_modules = static_modules if static_modules else [] if virtual_funcs is None: virtual_funcs = [] self.virtual_funcs = virtual_funcs self.disabled = set( self.opts.get( 'disable_{0}{1}'.format( self.tag, '' if self.tag[-1] == 's' else 's' ), [] ) ) # A map of suffix to description for imp self.suffix_map = {} # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [''] for (suffix, mode, kind) in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) self._lock = threading.RLock() self._refresh_file_mapping() super(LazyLoader, self).__init__() # late init the lazy loader # create all of the import namespaces _generate_module('{0}.int'.format(self.loaded_base_name)) _generate_module('{0}.int.{1}'.format(self.loaded_base_name, tag)) _generate_module('{0}.ext'.format(self.loaded_base_name)) _generate_module('{0}.ext.{1}'.format(self.loaded_base_name, tag)) def __getitem__(self, item): ''' Override the __getitem__ in order to decorate the returned function if we need to last-minute inject globals ''' func = super(LazyLoader, self).__getitem__(item) if self.inject_globals: return global_injector_decorator(self.inject_globals)(func) else: return func def __getattr__(self, mod_name): ''' Allow for "direct" attribute access-- this allows jinja templates to access things like `salt.test.ping()` ''' if mod_name in ('__getstate__', '__setstate__'): return object.__getattribute__(self, mod_name) # if we have an attribute named that, lets return it. try: return object.__getattr__(self, mod_name) # pylint: disable=no-member except AttributeError: pass # otherwise we assume its jinja template access if mod_name not in self.loaded_modules and not self.loaded: for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and mod_name in self.loaded_modules: break if mod_name in self.loaded_modules: return self.loaded_modules[mod_name] else: raise AttributeError(mod_name) def missing_fun_string(self, function_name): ''' Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ''' mod_name = function_name.split('.')[0] if mod_name in self.loaded_modules: return '\'{0}\' is not available.'.format(function_name) else: try: reason = self.missing_modules[mod_name] except KeyError: return '\'{0}\' is not available.'.format(function_name) else: if reason is not None: return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason) else: return '\'{0}\' __virtual__ returned False'.format(mod_name) def clear(self): ''' Clear the dict ''' with self._lock: super(LazyLoader, self).clear() # clear the lazy loader self.loaded_files = set() self.missing_modules = {} self.loaded_modules = {} # if we have been loaded before, lets clear the file mapping since # we obviously want a re-do if hasattr(self, 'opts'): self._refresh_file_mapping() self.initial_load = False def __prep_mod_opts(self, opts): ''' Strip out of the opts any logger instance ''' if '__grains__' not in self.pack: grains = opts.get('grains', {}) if isinstance(grains, ThreadLocalProxy): grains = ThreadLocalProxy.unproxy(grains) self.context_dict['grains'] = grains self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains') if '__pillar__' not in self.pack: pillar = opts.get('pillar', {}) if isinstance(pillar, ThreadLocalProxy): pillar = ThreadLocalProxy.unproxy(pillar) self.context_dict['pillar'] = pillar self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar') mod_opts = {} for key, val in list(opts.items()): if key == 'logger': continue mod_opts[key] = val return mod_opts def _iter_files(self, mod_name): ''' Iterate over all file_mapping files in order of closeness to mod_name ''' # do we have an exact match? if mod_name in self.file_mapping: yield mod_name # do we have a partial match? for k in self.file_mapping: if mod_name in k: yield k # anyone else? Bueller? for k in self.file_mapping: if mod_name not in k: yield k def _reload_submodules(self, mod): submodules = ( getattr(mod, sname) for sname in dir(mod) if isinstance(getattr(mod, sname), mod.__class__) ) # reload only custom "sub"modules for submodule in submodules: # it is a submodule if the name is in a namespace under mod if submodule.__name__.startswith(mod.__name__ + '.'): reload_module(submodule) self._reload_submodules(submodule) def _load_module(self, name): mod = None fpath, suffix = self.file_mapping[name][:2] self.loaded_files.add(name) fpath_dirname = os.path.dirname(fpath) try: sys.path.append(fpath_dirname) if suffix == '.pyx': mod = pyximport.load_module(name, fpath, tempfile.gettempdir()) elif suffix == '.o': top_mod = __import__(fpath, globals(), locals(), []) comps = fpath.split('.') if len(comps) < 2: mod = top_mod else: mod = top_mod for subname in comps[1:]: mod = getattr(mod, subname) elif suffix == '.zip': mod = zipimporter(fpath).load_module(name) else: desc = self.suffix_map[suffix] # if it is a directory, we don't open a file try: mod_namespace = '.'.join(( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name)) except TypeError: mod_namespace = '{0}.{1}.{2}.{3}'.format( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name) if suffix == '': if USE_IMPORTLIB: # pylint: disable=no-member # Package directory, look for __init__ loader_details = [ (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES), (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES), (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), ] file_finder = importlib.machinery.FileFinder( fpath_dirname, *loader_details ) spec = file_finder.find_spec(mod_namespace) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: mod = imp.load_module(mod_namespace, None, fpath, desc) # reload all submodules if necessary if not self.initial_load: self._reload_submodules(mod) else: if USE_IMPORTLIB: # pylint: disable=no-member loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath) spec = importlib.util.spec_from_file_location( mod_namespace, fpath, loader=loader ) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() #mod = importlib.util.module_from_spec(spec) #spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: with salt.utils.files.fopen(fpath, desc[1]) as fn_: mod = imp.load_module(mod_namespace, fn_, fpath, desc) except IOError: raise except ImportError as exc: if 'magic number' in six.text_type(exc): error_msg = 'Failed to import {0} {1}. Bad magic number. If migrating from Python2 to Python3, remove all .pyc files and try again.'.format(self.tag, name) log.warning(error_msg) self.missing_modules[name] = error_msg log.debug( 'Failed to import %s %s:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = exc return False except Exception as error: log.error( 'Failed to import %s %s, this is due most likely to a ' 'syntax error:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False except SystemExit as error: try: fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1] except Exception: pass else: tgt_fn = os.path.join('salt', 'utils', 'process.py') if fn_.endswith(tgt_fn) and '_handle_signals' in caller: # Race conditon, SIGTERM or SIGINT received while loader # was in process of loading a module. Call sys.exit to # ensure that the process is killed. sys.exit(salt.defaults.exitcodes.EX_OK) log.error( 'Failed to import %s %s as the module called exit()\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False finally: sys.path.remove(fpath_dirname) if hasattr(mod, '__opts__'): mod.__opts__.update(self.opts) else: mod.__opts__ = self.opts # pack whatever other globals we were asked to for p_name, p_value in six.iteritems(self.pack): _inject_into_mod(mod, p_name, p_value) module_name = mod.__name__.rsplit('.', 1)[-1] # Call a module's initialization method if it exists module_init = getattr(mod, '__init__', None) if inspect.isfunction(module_init): try: module_init(self.opts) except TypeError as e: log.error(e) except Exception: err_string = '__init__ failed' log.debug( 'Error loading %s.%s: %s', self.tag, module_name, err_string, exc_info=True ) self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False # if virtual modules are enabled, we need to look for the # __virtual__() function inside that module and run it. if self.virtual_enable: virtual_funcs_to_process = ['__virtual__'] + self.virtual_funcs for virtual_func in virtual_funcs_to_process: virtual_ret, module_name, virtual_err, virtual_aliases = \ self._process_virtual(mod, module_name, virtual_func) if virtual_err is not None: log.trace( 'Error loading %s.%s: %s', self.tag, module_name, virtual_err ) # if _process_virtual returned a non-True value then we are # supposed to not process this module if virtual_ret is not True and module_name not in self.missing_modules: # If a module has information about why it could not be loaded, record it self.missing_modules[module_name] = virtual_err self.missing_modules[name] = virtual_err return False else: virtual_aliases = () # If this is a proxy minion then MOST modules cannot work. Therefore, require that # any module that does work with salt-proxy-minion define __proxyenabled__ as a list # containing the names of the proxy types that the module supports. # # Render modules and state modules are OK though if 'proxy' in self.opts: if self.tag in ['grains', 'proxy']: if not hasattr(mod, '__proxyenabled__') or \ (self.opts['proxy']['proxytype'] not in mod.__proxyenabled__ and '*' not in mod.__proxyenabled__): err_string = 'not a proxy_minion enabled module' self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False if getattr(mod, '__load__', False) is not False: log.info( 'The functions from module \'%s\' are being loaded from the ' 'provided __load__ attribute', module_name ) # If we had another module by the same virtual name, we should put any # new functions under the existing dictionary. mod_names = [module_name] + list(virtual_aliases) mod_dict = dict(( (x, self.loaded_modules.get(x, self.mod_dict_class())) for x in mod_names )) for attr in getattr(mod, '__load__', dir(mod)): if attr.startswith('_') and attr != '__call__': # private functions are skipped, # except __call__ which is default entrance # for multi-function batch-like state syntax continue func = getattr(mod, attr) if not inspect.isfunction(func) and not isinstance(func, functools.partial): # Not a function!? Skip it!!! continue # Let's get the function name. # If the module has the __func_alias__ attribute, it must be a # dictionary mapping in the form of(key -> value): # <real-func-name> -> <desired-func-name> # # It default's of course to the found callable attribute name # if no alias is defined. funcname = getattr(mod, '__func_alias__', {}).get(attr, attr) for tgt_mod in mod_names: try: full_funcname = '.'.join((tgt_mod, funcname)) except TypeError: full_funcname = '{0}.{1}'.format(tgt_mod, funcname) # Save many references for lookups # Careful not to overwrite existing (higher priority) functions if full_funcname not in self._dict: self._dict[full_funcname] = func if funcname not in mod_dict[tgt_mod]: setattr(mod_dict[tgt_mod], funcname, func) mod_dict[tgt_mod][funcname] = func self._apply_outputter(func, mod) # enforce depends try: Depends.enforce_dependencies(self._dict, self.tag) except RuntimeError as exc: log.info( 'Depends.enforce_dependencies() failed for the following ' 'reason: %s', exc ) for tgt_mod in mod_names: self.loaded_modules[tgt_mod] = mod_dict[tgt_mod] return True def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise KeyError('The key \'{0}\' should contain a \'.\''.format(key)) mod_name, _ = key.split('.', 1) with self._lock: # It is possible that the key is in the dictionary after # acquiring the lock due to another thread loading it. if mod_name in self.missing_modules or key in self._dict: return True # if the modulename isn't in the whitelist, don't bother if self.whitelist and mod_name not in self.whitelist: log.error( 'Failed to load function %s because its module (%s) is ' 'not in the whitelist: %s', key, mod_name, self.whitelist ) raise KeyError(key) def _inner_load(mod_name): for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and key in self._dict: return True return False # try to load the module ret = None reloaded = False # re-scan up to once, IOErrors or a failed load cause re-scans of the # filesystem while True: try: ret = _inner_load(mod_name) if not reloaded and ret is not True: self._refresh_file_mapping() reloaded = True continue break except IOError: if not reloaded: self._refresh_file_mapping() reloaded = True continue return ret def _load_all(self): ''' Load all of them ''' with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True def reload_modules(self): with self._lock: self.loaded_files = set() self._load_all() def _apply_outputter(self, func, mod): ''' Apply the __outputter__ variable to the functions ''' if hasattr(mod, '__outputter__'): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__] def _process_virtual(self, mod, module_name, virtual_func='__virtual__'): ''' Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1] ''' # The __virtual__ function will return either a True or False value. # If it returns a True value it can also set a module level attribute # named __virtualname__ with the name that the module should be # referred to as. # # This allows us to have things like the pkg module working on all # platforms under the name 'pkg'. It also allows for modules like # augeas_cfg to be referred to as 'augeas', which would otherwise have # namespace collisions. And finally it allows modules to return False # if they are not intended to run on the given platform or are missing # dependencies. virtual_aliases = getattr(mod, '__virtual_aliases__', tuple()) try: error_reason = None if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__): try: start = time.time() virtual = getattr(mod, virtual_func)() if isinstance(virtual, tuple): error_reason = virtual[1] virtual = virtual[0] if self.opts.get('virtual_timer', False): end = time.time() - start msg = 'Virtual function took {0} seconds for {1}'.format( end, module_name) log.warning(msg) except Exception as exc: error_reason = ( 'Exception raised when processing __virtual__ function' ' for {0}. Module will not be loaded: {1}'.format( mod.__name__, exc)) log.error(error_reason, exc_info_on_loglevel=logging.DEBUG) virtual = None # Get the module's virtual name virtualname = getattr(mod, '__virtualname__', virtual) if not virtual: # if __virtual__() evaluates to False then the module # wasn't meant for this platform or it's not supposed to # load for some other reason. # Some modules might accidentally return None and are # improperly loaded if virtual is None: log.warning( '%s.__virtual__() is wrongly returning `None`. ' 'It should either return `True`, `False` or a new ' 'name. If you\'re the developer of the module ' '\'%s\', please fix this.', mod.__name__, module_name ) return (False, module_name, error_reason, virtual_aliases) # At this point, __virtual__ did not return a # boolean value, let's check for deprecated usage # or module renames if virtual is not True and module_name != virtual: # The module is renaming itself. Updating the module name # with the new name log.trace('Loaded %s as virtual %s', module_name, virtual) if virtualname != virtual: # The __virtualname__ attribute does not match what's # being returned by the __virtual__() function. This # should be considered an error. log.error( 'The module \'%s\' is showing some bad usage. Its ' '__virtualname__ attribute is set to \'%s\' yet the ' '__virtual__() function is returning \'%s\'. These ' 'values should match!', mod.__name__, virtualname, virtual ) module_name = virtualname # If the __virtual__ function returns True and __virtualname__ # is set then use it elif virtual is True and virtualname != module_name: if virtualname is not True: module_name = virtualname except KeyError: # Key errors come out of the virtual function when passing # in incomplete grains sets, these can be safely ignored # and logged to debug, still, it includes the traceback to # help debugging. log.debug('KeyError when loading %s', module_name, exc_info=True) except Exception: # If the module throws an exception during __virtual__() # then log the information and continue to the next. log.error( 'Failed to read the virtual function for %s: %s', self.tag, module_name, exc_info=True ) return (False, module_name, error_reason, virtual_aliases) return (True, module_name, None, virtual_aliases)
saltstack/salt
salt/loader.py
LazyLoader.clear
python
def clear(self): ''' Clear the dict ''' with self._lock: super(LazyLoader, self).clear() # clear the lazy loader self.loaded_files = set() self.missing_modules = {} self.loaded_modules = {} # if we have been loaded before, lets clear the file mapping since # we obviously want a re-do if hasattr(self, 'opts'): self._refresh_file_mapping() self.initial_load = False
Clear the dict
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L1522-L1535
null
class LazyLoader(salt.utils.lazy.LazyDict): ''' A pseduo-dictionary which has a set of keys which are the name of the module and function, delimited by a dot. When the value of the key is accessed, the function is then loaded from disk and into memory. .. note:: Iterating over keys will cause all modules to be loaded. :param list module_dirs: A list of directories on disk to search for modules :param dict opts: The salt options dictionary. :param str tag: The tag for the type of module to load :param func mod_type_check: A function which can be used to verify files :param dict pack: A dictionary of function to be packed into modules as they are loaded :param list whitelist: A list of modules to whitelist :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules. :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality. If not true, the module will not load. :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values are function references themselves which are loaded on-demand. # TODO: - move modules_max_memory into here - singletons (per tag) ''' mod_dict_class = salt.utils.odict.OrderedDict def __init__(self, module_dirs, opts=None, tag='module', loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, proxy=None, virtual_funcs=None, ): # pylint: disable=W0231 ''' In pack, if any of the values are None they will be replaced with an empty context-specific dict ''' self.inject_globals = {} self.pack = {} if pack is None else pack if opts is None: opts = {} threadsafety = not opts.get('multiprocessing') self.context_dict = salt.utils.context.ContextDict(threadsafe=threadsafety) self.opts = self.__prep_mod_opts(opts) self.module_dirs = module_dirs self.tag = tag self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME self.mod_type_check = mod_type_check or _mod_type if '__context__' not in self.pack: self.pack['__context__'] = None for k, v in six.iteritems(self.pack): if v is None: # if the value of a pack is None, lets make an empty dict value = self.context_dict.get(k, {}) if isinstance(value, ThreadLocalProxy): value = ThreadLocalProxy.unproxy(value) self.context_dict[k] = value self.pack[k] = salt.utils.context.NamespacedDictWrapper(self.context_dict, k) self.whitelist = whitelist self.virtual_enable = virtual_enable self.initial_load = True # names of modules that we don't have (errors, __virtual__, etc.) self.missing_modules = {} # mapping of name -> error self.loaded_modules = {} # mapping of module_name -> dict_of_functions self.loaded_files = set() # TODO: just remove them from file_mapping? self.static_modules = static_modules if static_modules else [] if virtual_funcs is None: virtual_funcs = [] self.virtual_funcs = virtual_funcs self.disabled = set( self.opts.get( 'disable_{0}{1}'.format( self.tag, '' if self.tag[-1] == 's' else 's' ), [] ) ) # A map of suffix to description for imp self.suffix_map = {} # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [''] for (suffix, mode, kind) in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) self._lock = threading.RLock() self._refresh_file_mapping() super(LazyLoader, self).__init__() # late init the lazy loader # create all of the import namespaces _generate_module('{0}.int'.format(self.loaded_base_name)) _generate_module('{0}.int.{1}'.format(self.loaded_base_name, tag)) _generate_module('{0}.ext'.format(self.loaded_base_name)) _generate_module('{0}.ext.{1}'.format(self.loaded_base_name, tag)) def __getitem__(self, item): ''' Override the __getitem__ in order to decorate the returned function if we need to last-minute inject globals ''' func = super(LazyLoader, self).__getitem__(item) if self.inject_globals: return global_injector_decorator(self.inject_globals)(func) else: return func def __getattr__(self, mod_name): ''' Allow for "direct" attribute access-- this allows jinja templates to access things like `salt.test.ping()` ''' if mod_name in ('__getstate__', '__setstate__'): return object.__getattribute__(self, mod_name) # if we have an attribute named that, lets return it. try: return object.__getattr__(self, mod_name) # pylint: disable=no-member except AttributeError: pass # otherwise we assume its jinja template access if mod_name not in self.loaded_modules and not self.loaded: for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and mod_name in self.loaded_modules: break if mod_name in self.loaded_modules: return self.loaded_modules[mod_name] else: raise AttributeError(mod_name) def missing_fun_string(self, function_name): ''' Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ''' mod_name = function_name.split('.')[0] if mod_name in self.loaded_modules: return '\'{0}\' is not available.'.format(function_name) else: try: reason = self.missing_modules[mod_name] except KeyError: return '\'{0}\' is not available.'.format(function_name) else: if reason is not None: return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason) else: return '\'{0}\' __virtual__ returned False'.format(mod_name) def _refresh_file_mapping(self): ''' refresh the mapping of the FS on disk ''' # map of suffix to description for imp if self.opts.get('cython_enable', True) is True: try: global pyximport pyximport = __import__('pyximport') # pylint: disable=import-error pyximport.install() # add to suffix_map so file_mapping will pick it up self.suffix_map['.pyx'] = tuple() except ImportError: log.info('Cython is enabled in the options but not present ' 'in the system path. Skipping Cython modules.') # Allow for zipimport of modules if self.opts.get('enable_zip_modules', True) is True: self.suffix_map['.zip'] = tuple() # allow for module dirs if USE_IMPORTLIB: self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY) else: self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY) # create mapping of filename (without suffix) to (path, suffix) # The files are added in order of priority, so order *must* be retained. self.file_mapping = salt.utils.odict.OrderedDict() opt_match = [] def _replace_pre_ext(obj): ''' Hack so we can get the optimization level that we replaced (if any) out of the re.sub call below. We use a list here because it is a persistent data structure that we will be able to access after re.sub is called. ''' opt_match.append(obj) return '' for mod_dir in self.module_dirs: try: # Make sure we have a sorted listdir in order to have # expectable override results files = sorted( x for x in os.listdir(mod_dir) if x != '__pycache__' ) except OSError: continue # Next mod_dir if six.PY3: try: pycache_files = [ os.path.join('__pycache__', x) for x in sorted(os.listdir(os.path.join(mod_dir, '__pycache__'))) ] except OSError: pass else: files.extend(pycache_files) for filename in files: try: dirname, basename = os.path.split(filename) if basename.startswith('_'): # skip private modules # log messages omitted for obviousness continue # Next filename f_noext, ext = os.path.splitext(basename) if six.PY3: f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext) try: opt_level = int( opt_match.pop().group(1).rsplit('-', 1)[-1] ) except (AttributeError, IndexError, ValueError): # No regex match or no optimization level matched opt_level = 0 try: opt_index = self.opts['optimization_order'].index(opt_level) except KeyError: log.trace( 'Disallowed optimization level %d for module ' 'name \'%s\', skipping. Add %d to the ' '\'optimization_order\' config option if you ' 'do not want to ignore this optimization ' 'level.', opt_level, f_noext, opt_level ) continue else: # Optimization level not reflected in filename on PY2 opt_index = 0 # make sure it is a suffix we support if ext not in self.suffix_map: continue # Next filename if f_noext in self.disabled: log.trace( 'Skipping %s, it is disabled by configuration', filename ) continue # Next filename fpath = os.path.join(mod_dir, filename) # if its a directory, lets allow us to load that if ext == '': # is there something __init__? subfiles = os.listdir(fpath) for suffix in self.suffix_order: if '' == suffix: continue # Next suffix (__init__ must have a suffix) init_file = '__init__{0}'.format(suffix) if init_file in subfiles: break else: continue # Next filename try: curr_ext = self.file_mapping[f_noext][1] curr_opt_index = self.file_mapping[f_noext][2] except KeyError: pass else: if '' in (curr_ext, ext) and curr_ext != ext: log.error( 'Module/package collision: \'%s\' and \'%s\'', fpath, self.file_mapping[f_noext][0] ) if six.PY3 and ext == '.pyc' and curr_ext == '.pyc': # Check the optimization level if opt_index >= curr_opt_index: # Module name match, but a higher-priority # optimization level was already matched, skipping. continue elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext): # Match found but a higher-priorty match already # exists, so skip this. continue if six.PY3 and not dirname and ext == '.pyc': # On Python 3, we should only load .pyc files from the # __pycache__ subdirectory (i.e. when dirname is not an # empty string). continue # Made it this far - add it self.file_mapping[f_noext] = (fpath, ext, opt_index) except OSError: continue for smod in self.static_modules: f_noext = smod.split('.')[-1] self.file_mapping[f_noext] = (smod, '.o', 0) def __prep_mod_opts(self, opts): ''' Strip out of the opts any logger instance ''' if '__grains__' not in self.pack: grains = opts.get('grains', {}) if isinstance(grains, ThreadLocalProxy): grains = ThreadLocalProxy.unproxy(grains) self.context_dict['grains'] = grains self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains') if '__pillar__' not in self.pack: pillar = opts.get('pillar', {}) if isinstance(pillar, ThreadLocalProxy): pillar = ThreadLocalProxy.unproxy(pillar) self.context_dict['pillar'] = pillar self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar') mod_opts = {} for key, val in list(opts.items()): if key == 'logger': continue mod_opts[key] = val return mod_opts def _iter_files(self, mod_name): ''' Iterate over all file_mapping files in order of closeness to mod_name ''' # do we have an exact match? if mod_name in self.file_mapping: yield mod_name # do we have a partial match? for k in self.file_mapping: if mod_name in k: yield k # anyone else? Bueller? for k in self.file_mapping: if mod_name not in k: yield k def _reload_submodules(self, mod): submodules = ( getattr(mod, sname) for sname in dir(mod) if isinstance(getattr(mod, sname), mod.__class__) ) # reload only custom "sub"modules for submodule in submodules: # it is a submodule if the name is in a namespace under mod if submodule.__name__.startswith(mod.__name__ + '.'): reload_module(submodule) self._reload_submodules(submodule) def _load_module(self, name): mod = None fpath, suffix = self.file_mapping[name][:2] self.loaded_files.add(name) fpath_dirname = os.path.dirname(fpath) try: sys.path.append(fpath_dirname) if suffix == '.pyx': mod = pyximport.load_module(name, fpath, tempfile.gettempdir()) elif suffix == '.o': top_mod = __import__(fpath, globals(), locals(), []) comps = fpath.split('.') if len(comps) < 2: mod = top_mod else: mod = top_mod for subname in comps[1:]: mod = getattr(mod, subname) elif suffix == '.zip': mod = zipimporter(fpath).load_module(name) else: desc = self.suffix_map[suffix] # if it is a directory, we don't open a file try: mod_namespace = '.'.join(( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name)) except TypeError: mod_namespace = '{0}.{1}.{2}.{3}'.format( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name) if suffix == '': if USE_IMPORTLIB: # pylint: disable=no-member # Package directory, look for __init__ loader_details = [ (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES), (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES), (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), ] file_finder = importlib.machinery.FileFinder( fpath_dirname, *loader_details ) spec = file_finder.find_spec(mod_namespace) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: mod = imp.load_module(mod_namespace, None, fpath, desc) # reload all submodules if necessary if not self.initial_load: self._reload_submodules(mod) else: if USE_IMPORTLIB: # pylint: disable=no-member loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath) spec = importlib.util.spec_from_file_location( mod_namespace, fpath, loader=loader ) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() #mod = importlib.util.module_from_spec(spec) #spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: with salt.utils.files.fopen(fpath, desc[1]) as fn_: mod = imp.load_module(mod_namespace, fn_, fpath, desc) except IOError: raise except ImportError as exc: if 'magic number' in six.text_type(exc): error_msg = 'Failed to import {0} {1}. Bad magic number. If migrating from Python2 to Python3, remove all .pyc files and try again.'.format(self.tag, name) log.warning(error_msg) self.missing_modules[name] = error_msg log.debug( 'Failed to import %s %s:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = exc return False except Exception as error: log.error( 'Failed to import %s %s, this is due most likely to a ' 'syntax error:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False except SystemExit as error: try: fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1] except Exception: pass else: tgt_fn = os.path.join('salt', 'utils', 'process.py') if fn_.endswith(tgt_fn) and '_handle_signals' in caller: # Race conditon, SIGTERM or SIGINT received while loader # was in process of loading a module. Call sys.exit to # ensure that the process is killed. sys.exit(salt.defaults.exitcodes.EX_OK) log.error( 'Failed to import %s %s as the module called exit()\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False finally: sys.path.remove(fpath_dirname) if hasattr(mod, '__opts__'): mod.__opts__.update(self.opts) else: mod.__opts__ = self.opts # pack whatever other globals we were asked to for p_name, p_value in six.iteritems(self.pack): _inject_into_mod(mod, p_name, p_value) module_name = mod.__name__.rsplit('.', 1)[-1] # Call a module's initialization method if it exists module_init = getattr(mod, '__init__', None) if inspect.isfunction(module_init): try: module_init(self.opts) except TypeError as e: log.error(e) except Exception: err_string = '__init__ failed' log.debug( 'Error loading %s.%s: %s', self.tag, module_name, err_string, exc_info=True ) self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False # if virtual modules are enabled, we need to look for the # __virtual__() function inside that module and run it. if self.virtual_enable: virtual_funcs_to_process = ['__virtual__'] + self.virtual_funcs for virtual_func in virtual_funcs_to_process: virtual_ret, module_name, virtual_err, virtual_aliases = \ self._process_virtual(mod, module_name, virtual_func) if virtual_err is not None: log.trace( 'Error loading %s.%s: %s', self.tag, module_name, virtual_err ) # if _process_virtual returned a non-True value then we are # supposed to not process this module if virtual_ret is not True and module_name not in self.missing_modules: # If a module has information about why it could not be loaded, record it self.missing_modules[module_name] = virtual_err self.missing_modules[name] = virtual_err return False else: virtual_aliases = () # If this is a proxy minion then MOST modules cannot work. Therefore, require that # any module that does work with salt-proxy-minion define __proxyenabled__ as a list # containing the names of the proxy types that the module supports. # # Render modules and state modules are OK though if 'proxy' in self.opts: if self.tag in ['grains', 'proxy']: if not hasattr(mod, '__proxyenabled__') or \ (self.opts['proxy']['proxytype'] not in mod.__proxyenabled__ and '*' not in mod.__proxyenabled__): err_string = 'not a proxy_minion enabled module' self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False if getattr(mod, '__load__', False) is not False: log.info( 'The functions from module \'%s\' are being loaded from the ' 'provided __load__ attribute', module_name ) # If we had another module by the same virtual name, we should put any # new functions under the existing dictionary. mod_names = [module_name] + list(virtual_aliases) mod_dict = dict(( (x, self.loaded_modules.get(x, self.mod_dict_class())) for x in mod_names )) for attr in getattr(mod, '__load__', dir(mod)): if attr.startswith('_') and attr != '__call__': # private functions are skipped, # except __call__ which is default entrance # for multi-function batch-like state syntax continue func = getattr(mod, attr) if not inspect.isfunction(func) and not isinstance(func, functools.partial): # Not a function!? Skip it!!! continue # Let's get the function name. # If the module has the __func_alias__ attribute, it must be a # dictionary mapping in the form of(key -> value): # <real-func-name> -> <desired-func-name> # # It default's of course to the found callable attribute name # if no alias is defined. funcname = getattr(mod, '__func_alias__', {}).get(attr, attr) for tgt_mod in mod_names: try: full_funcname = '.'.join((tgt_mod, funcname)) except TypeError: full_funcname = '{0}.{1}'.format(tgt_mod, funcname) # Save many references for lookups # Careful not to overwrite existing (higher priority) functions if full_funcname not in self._dict: self._dict[full_funcname] = func if funcname not in mod_dict[tgt_mod]: setattr(mod_dict[tgt_mod], funcname, func) mod_dict[tgt_mod][funcname] = func self._apply_outputter(func, mod) # enforce depends try: Depends.enforce_dependencies(self._dict, self.tag) except RuntimeError as exc: log.info( 'Depends.enforce_dependencies() failed for the following ' 'reason: %s', exc ) for tgt_mod in mod_names: self.loaded_modules[tgt_mod] = mod_dict[tgt_mod] return True def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise KeyError('The key \'{0}\' should contain a \'.\''.format(key)) mod_name, _ = key.split('.', 1) with self._lock: # It is possible that the key is in the dictionary after # acquiring the lock due to another thread loading it. if mod_name in self.missing_modules or key in self._dict: return True # if the modulename isn't in the whitelist, don't bother if self.whitelist and mod_name not in self.whitelist: log.error( 'Failed to load function %s because its module (%s) is ' 'not in the whitelist: %s', key, mod_name, self.whitelist ) raise KeyError(key) def _inner_load(mod_name): for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and key in self._dict: return True return False # try to load the module ret = None reloaded = False # re-scan up to once, IOErrors or a failed load cause re-scans of the # filesystem while True: try: ret = _inner_load(mod_name) if not reloaded and ret is not True: self._refresh_file_mapping() reloaded = True continue break except IOError: if not reloaded: self._refresh_file_mapping() reloaded = True continue return ret def _load_all(self): ''' Load all of them ''' with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True def reload_modules(self): with self._lock: self.loaded_files = set() self._load_all() def _apply_outputter(self, func, mod): ''' Apply the __outputter__ variable to the functions ''' if hasattr(mod, '__outputter__'): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__] def _process_virtual(self, mod, module_name, virtual_func='__virtual__'): ''' Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1] ''' # The __virtual__ function will return either a True or False value. # If it returns a True value it can also set a module level attribute # named __virtualname__ with the name that the module should be # referred to as. # # This allows us to have things like the pkg module working on all # platforms under the name 'pkg'. It also allows for modules like # augeas_cfg to be referred to as 'augeas', which would otherwise have # namespace collisions. And finally it allows modules to return False # if they are not intended to run on the given platform or are missing # dependencies. virtual_aliases = getattr(mod, '__virtual_aliases__', tuple()) try: error_reason = None if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__): try: start = time.time() virtual = getattr(mod, virtual_func)() if isinstance(virtual, tuple): error_reason = virtual[1] virtual = virtual[0] if self.opts.get('virtual_timer', False): end = time.time() - start msg = 'Virtual function took {0} seconds for {1}'.format( end, module_name) log.warning(msg) except Exception as exc: error_reason = ( 'Exception raised when processing __virtual__ function' ' for {0}. Module will not be loaded: {1}'.format( mod.__name__, exc)) log.error(error_reason, exc_info_on_loglevel=logging.DEBUG) virtual = None # Get the module's virtual name virtualname = getattr(mod, '__virtualname__', virtual) if not virtual: # if __virtual__() evaluates to False then the module # wasn't meant for this platform or it's not supposed to # load for some other reason. # Some modules might accidentally return None and are # improperly loaded if virtual is None: log.warning( '%s.__virtual__() is wrongly returning `None`. ' 'It should either return `True`, `False` or a new ' 'name. If you\'re the developer of the module ' '\'%s\', please fix this.', mod.__name__, module_name ) return (False, module_name, error_reason, virtual_aliases) # At this point, __virtual__ did not return a # boolean value, let's check for deprecated usage # or module renames if virtual is not True and module_name != virtual: # The module is renaming itself. Updating the module name # with the new name log.trace('Loaded %s as virtual %s', module_name, virtual) if virtualname != virtual: # The __virtualname__ attribute does not match what's # being returned by the __virtual__() function. This # should be considered an error. log.error( 'The module \'%s\' is showing some bad usage. Its ' '__virtualname__ attribute is set to \'%s\' yet the ' '__virtual__() function is returning \'%s\'. These ' 'values should match!', mod.__name__, virtualname, virtual ) module_name = virtualname # If the __virtual__ function returns True and __virtualname__ # is set then use it elif virtual is True and virtualname != module_name: if virtualname is not True: module_name = virtualname except KeyError: # Key errors come out of the virtual function when passing # in incomplete grains sets, these can be safely ignored # and logged to debug, still, it includes the traceback to # help debugging. log.debug('KeyError when loading %s', module_name, exc_info=True) except Exception: # If the module throws an exception during __virtual__() # then log the information and continue to the next. log.error( 'Failed to read the virtual function for %s: %s', self.tag, module_name, exc_info=True ) return (False, module_name, error_reason, virtual_aliases) return (True, module_name, None, virtual_aliases)
saltstack/salt
salt/loader.py
LazyLoader.__prep_mod_opts
python
def __prep_mod_opts(self, opts): ''' Strip out of the opts any logger instance ''' if '__grains__' not in self.pack: grains = opts.get('grains', {}) if isinstance(grains, ThreadLocalProxy): grains = ThreadLocalProxy.unproxy(grains) self.context_dict['grains'] = grains self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains') if '__pillar__' not in self.pack: pillar = opts.get('pillar', {}) if isinstance(pillar, ThreadLocalProxy): pillar = ThreadLocalProxy.unproxy(pillar) self.context_dict['pillar'] = pillar self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar') mod_opts = {} for key, val in list(opts.items()): if key == 'logger': continue mod_opts[key] = val return mod_opts
Strip out of the opts any logger instance
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L1537-L1564
null
class LazyLoader(salt.utils.lazy.LazyDict): ''' A pseduo-dictionary which has a set of keys which are the name of the module and function, delimited by a dot. When the value of the key is accessed, the function is then loaded from disk and into memory. .. note:: Iterating over keys will cause all modules to be loaded. :param list module_dirs: A list of directories on disk to search for modules :param dict opts: The salt options dictionary. :param str tag: The tag for the type of module to load :param func mod_type_check: A function which can be used to verify files :param dict pack: A dictionary of function to be packed into modules as they are loaded :param list whitelist: A list of modules to whitelist :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules. :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality. If not true, the module will not load. :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values are function references themselves which are loaded on-demand. # TODO: - move modules_max_memory into here - singletons (per tag) ''' mod_dict_class = salt.utils.odict.OrderedDict def __init__(self, module_dirs, opts=None, tag='module', loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, proxy=None, virtual_funcs=None, ): # pylint: disable=W0231 ''' In pack, if any of the values are None they will be replaced with an empty context-specific dict ''' self.inject_globals = {} self.pack = {} if pack is None else pack if opts is None: opts = {} threadsafety = not opts.get('multiprocessing') self.context_dict = salt.utils.context.ContextDict(threadsafe=threadsafety) self.opts = self.__prep_mod_opts(opts) self.module_dirs = module_dirs self.tag = tag self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME self.mod_type_check = mod_type_check or _mod_type if '__context__' not in self.pack: self.pack['__context__'] = None for k, v in six.iteritems(self.pack): if v is None: # if the value of a pack is None, lets make an empty dict value = self.context_dict.get(k, {}) if isinstance(value, ThreadLocalProxy): value = ThreadLocalProxy.unproxy(value) self.context_dict[k] = value self.pack[k] = salt.utils.context.NamespacedDictWrapper(self.context_dict, k) self.whitelist = whitelist self.virtual_enable = virtual_enable self.initial_load = True # names of modules that we don't have (errors, __virtual__, etc.) self.missing_modules = {} # mapping of name -> error self.loaded_modules = {} # mapping of module_name -> dict_of_functions self.loaded_files = set() # TODO: just remove them from file_mapping? self.static_modules = static_modules if static_modules else [] if virtual_funcs is None: virtual_funcs = [] self.virtual_funcs = virtual_funcs self.disabled = set( self.opts.get( 'disable_{0}{1}'.format( self.tag, '' if self.tag[-1] == 's' else 's' ), [] ) ) # A map of suffix to description for imp self.suffix_map = {} # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [''] for (suffix, mode, kind) in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) self._lock = threading.RLock() self._refresh_file_mapping() super(LazyLoader, self).__init__() # late init the lazy loader # create all of the import namespaces _generate_module('{0}.int'.format(self.loaded_base_name)) _generate_module('{0}.int.{1}'.format(self.loaded_base_name, tag)) _generate_module('{0}.ext'.format(self.loaded_base_name)) _generate_module('{0}.ext.{1}'.format(self.loaded_base_name, tag)) def __getitem__(self, item): ''' Override the __getitem__ in order to decorate the returned function if we need to last-minute inject globals ''' func = super(LazyLoader, self).__getitem__(item) if self.inject_globals: return global_injector_decorator(self.inject_globals)(func) else: return func def __getattr__(self, mod_name): ''' Allow for "direct" attribute access-- this allows jinja templates to access things like `salt.test.ping()` ''' if mod_name in ('__getstate__', '__setstate__'): return object.__getattribute__(self, mod_name) # if we have an attribute named that, lets return it. try: return object.__getattr__(self, mod_name) # pylint: disable=no-member except AttributeError: pass # otherwise we assume its jinja template access if mod_name not in self.loaded_modules and not self.loaded: for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and mod_name in self.loaded_modules: break if mod_name in self.loaded_modules: return self.loaded_modules[mod_name] else: raise AttributeError(mod_name) def missing_fun_string(self, function_name): ''' Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ''' mod_name = function_name.split('.')[0] if mod_name in self.loaded_modules: return '\'{0}\' is not available.'.format(function_name) else: try: reason = self.missing_modules[mod_name] except KeyError: return '\'{0}\' is not available.'.format(function_name) else: if reason is not None: return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason) else: return '\'{0}\' __virtual__ returned False'.format(mod_name) def _refresh_file_mapping(self): ''' refresh the mapping of the FS on disk ''' # map of suffix to description for imp if self.opts.get('cython_enable', True) is True: try: global pyximport pyximport = __import__('pyximport') # pylint: disable=import-error pyximport.install() # add to suffix_map so file_mapping will pick it up self.suffix_map['.pyx'] = tuple() except ImportError: log.info('Cython is enabled in the options but not present ' 'in the system path. Skipping Cython modules.') # Allow for zipimport of modules if self.opts.get('enable_zip_modules', True) is True: self.suffix_map['.zip'] = tuple() # allow for module dirs if USE_IMPORTLIB: self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY) else: self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY) # create mapping of filename (without suffix) to (path, suffix) # The files are added in order of priority, so order *must* be retained. self.file_mapping = salt.utils.odict.OrderedDict() opt_match = [] def _replace_pre_ext(obj): ''' Hack so we can get the optimization level that we replaced (if any) out of the re.sub call below. We use a list here because it is a persistent data structure that we will be able to access after re.sub is called. ''' opt_match.append(obj) return '' for mod_dir in self.module_dirs: try: # Make sure we have a sorted listdir in order to have # expectable override results files = sorted( x for x in os.listdir(mod_dir) if x != '__pycache__' ) except OSError: continue # Next mod_dir if six.PY3: try: pycache_files = [ os.path.join('__pycache__', x) for x in sorted(os.listdir(os.path.join(mod_dir, '__pycache__'))) ] except OSError: pass else: files.extend(pycache_files) for filename in files: try: dirname, basename = os.path.split(filename) if basename.startswith('_'): # skip private modules # log messages omitted for obviousness continue # Next filename f_noext, ext = os.path.splitext(basename) if six.PY3: f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext) try: opt_level = int( opt_match.pop().group(1).rsplit('-', 1)[-1] ) except (AttributeError, IndexError, ValueError): # No regex match or no optimization level matched opt_level = 0 try: opt_index = self.opts['optimization_order'].index(opt_level) except KeyError: log.trace( 'Disallowed optimization level %d for module ' 'name \'%s\', skipping. Add %d to the ' '\'optimization_order\' config option if you ' 'do not want to ignore this optimization ' 'level.', opt_level, f_noext, opt_level ) continue else: # Optimization level not reflected in filename on PY2 opt_index = 0 # make sure it is a suffix we support if ext not in self.suffix_map: continue # Next filename if f_noext in self.disabled: log.trace( 'Skipping %s, it is disabled by configuration', filename ) continue # Next filename fpath = os.path.join(mod_dir, filename) # if its a directory, lets allow us to load that if ext == '': # is there something __init__? subfiles = os.listdir(fpath) for suffix in self.suffix_order: if '' == suffix: continue # Next suffix (__init__ must have a suffix) init_file = '__init__{0}'.format(suffix) if init_file in subfiles: break else: continue # Next filename try: curr_ext = self.file_mapping[f_noext][1] curr_opt_index = self.file_mapping[f_noext][2] except KeyError: pass else: if '' in (curr_ext, ext) and curr_ext != ext: log.error( 'Module/package collision: \'%s\' and \'%s\'', fpath, self.file_mapping[f_noext][0] ) if six.PY3 and ext == '.pyc' and curr_ext == '.pyc': # Check the optimization level if opt_index >= curr_opt_index: # Module name match, but a higher-priority # optimization level was already matched, skipping. continue elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext): # Match found but a higher-priorty match already # exists, so skip this. continue if six.PY3 and not dirname and ext == '.pyc': # On Python 3, we should only load .pyc files from the # __pycache__ subdirectory (i.e. when dirname is not an # empty string). continue # Made it this far - add it self.file_mapping[f_noext] = (fpath, ext, opt_index) except OSError: continue for smod in self.static_modules: f_noext = smod.split('.')[-1] self.file_mapping[f_noext] = (smod, '.o', 0) def clear(self): ''' Clear the dict ''' with self._lock: super(LazyLoader, self).clear() # clear the lazy loader self.loaded_files = set() self.missing_modules = {} self.loaded_modules = {} # if we have been loaded before, lets clear the file mapping since # we obviously want a re-do if hasattr(self, 'opts'): self._refresh_file_mapping() self.initial_load = False def _iter_files(self, mod_name): ''' Iterate over all file_mapping files in order of closeness to mod_name ''' # do we have an exact match? if mod_name in self.file_mapping: yield mod_name # do we have a partial match? for k in self.file_mapping: if mod_name in k: yield k # anyone else? Bueller? for k in self.file_mapping: if mod_name not in k: yield k def _reload_submodules(self, mod): submodules = ( getattr(mod, sname) for sname in dir(mod) if isinstance(getattr(mod, sname), mod.__class__) ) # reload only custom "sub"modules for submodule in submodules: # it is a submodule if the name is in a namespace under mod if submodule.__name__.startswith(mod.__name__ + '.'): reload_module(submodule) self._reload_submodules(submodule) def _load_module(self, name): mod = None fpath, suffix = self.file_mapping[name][:2] self.loaded_files.add(name) fpath_dirname = os.path.dirname(fpath) try: sys.path.append(fpath_dirname) if suffix == '.pyx': mod = pyximport.load_module(name, fpath, tempfile.gettempdir()) elif suffix == '.o': top_mod = __import__(fpath, globals(), locals(), []) comps = fpath.split('.') if len(comps) < 2: mod = top_mod else: mod = top_mod for subname in comps[1:]: mod = getattr(mod, subname) elif suffix == '.zip': mod = zipimporter(fpath).load_module(name) else: desc = self.suffix_map[suffix] # if it is a directory, we don't open a file try: mod_namespace = '.'.join(( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name)) except TypeError: mod_namespace = '{0}.{1}.{2}.{3}'.format( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name) if suffix == '': if USE_IMPORTLIB: # pylint: disable=no-member # Package directory, look for __init__ loader_details = [ (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES), (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES), (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), ] file_finder = importlib.machinery.FileFinder( fpath_dirname, *loader_details ) spec = file_finder.find_spec(mod_namespace) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: mod = imp.load_module(mod_namespace, None, fpath, desc) # reload all submodules if necessary if not self.initial_load: self._reload_submodules(mod) else: if USE_IMPORTLIB: # pylint: disable=no-member loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath) spec = importlib.util.spec_from_file_location( mod_namespace, fpath, loader=loader ) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() #mod = importlib.util.module_from_spec(spec) #spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: with salt.utils.files.fopen(fpath, desc[1]) as fn_: mod = imp.load_module(mod_namespace, fn_, fpath, desc) except IOError: raise except ImportError as exc: if 'magic number' in six.text_type(exc): error_msg = 'Failed to import {0} {1}. Bad magic number. If migrating from Python2 to Python3, remove all .pyc files and try again.'.format(self.tag, name) log.warning(error_msg) self.missing_modules[name] = error_msg log.debug( 'Failed to import %s %s:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = exc return False except Exception as error: log.error( 'Failed to import %s %s, this is due most likely to a ' 'syntax error:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False except SystemExit as error: try: fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1] except Exception: pass else: tgt_fn = os.path.join('salt', 'utils', 'process.py') if fn_.endswith(tgt_fn) and '_handle_signals' in caller: # Race conditon, SIGTERM or SIGINT received while loader # was in process of loading a module. Call sys.exit to # ensure that the process is killed. sys.exit(salt.defaults.exitcodes.EX_OK) log.error( 'Failed to import %s %s as the module called exit()\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False finally: sys.path.remove(fpath_dirname) if hasattr(mod, '__opts__'): mod.__opts__.update(self.opts) else: mod.__opts__ = self.opts # pack whatever other globals we were asked to for p_name, p_value in six.iteritems(self.pack): _inject_into_mod(mod, p_name, p_value) module_name = mod.__name__.rsplit('.', 1)[-1] # Call a module's initialization method if it exists module_init = getattr(mod, '__init__', None) if inspect.isfunction(module_init): try: module_init(self.opts) except TypeError as e: log.error(e) except Exception: err_string = '__init__ failed' log.debug( 'Error loading %s.%s: %s', self.tag, module_name, err_string, exc_info=True ) self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False # if virtual modules are enabled, we need to look for the # __virtual__() function inside that module and run it. if self.virtual_enable: virtual_funcs_to_process = ['__virtual__'] + self.virtual_funcs for virtual_func in virtual_funcs_to_process: virtual_ret, module_name, virtual_err, virtual_aliases = \ self._process_virtual(mod, module_name, virtual_func) if virtual_err is not None: log.trace( 'Error loading %s.%s: %s', self.tag, module_name, virtual_err ) # if _process_virtual returned a non-True value then we are # supposed to not process this module if virtual_ret is not True and module_name not in self.missing_modules: # If a module has information about why it could not be loaded, record it self.missing_modules[module_name] = virtual_err self.missing_modules[name] = virtual_err return False else: virtual_aliases = () # If this is a proxy minion then MOST modules cannot work. Therefore, require that # any module that does work with salt-proxy-minion define __proxyenabled__ as a list # containing the names of the proxy types that the module supports. # # Render modules and state modules are OK though if 'proxy' in self.opts: if self.tag in ['grains', 'proxy']: if not hasattr(mod, '__proxyenabled__') or \ (self.opts['proxy']['proxytype'] not in mod.__proxyenabled__ and '*' not in mod.__proxyenabled__): err_string = 'not a proxy_minion enabled module' self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False if getattr(mod, '__load__', False) is not False: log.info( 'The functions from module \'%s\' are being loaded from the ' 'provided __load__ attribute', module_name ) # If we had another module by the same virtual name, we should put any # new functions under the existing dictionary. mod_names = [module_name] + list(virtual_aliases) mod_dict = dict(( (x, self.loaded_modules.get(x, self.mod_dict_class())) for x in mod_names )) for attr in getattr(mod, '__load__', dir(mod)): if attr.startswith('_') and attr != '__call__': # private functions are skipped, # except __call__ which is default entrance # for multi-function batch-like state syntax continue func = getattr(mod, attr) if not inspect.isfunction(func) and not isinstance(func, functools.partial): # Not a function!? Skip it!!! continue # Let's get the function name. # If the module has the __func_alias__ attribute, it must be a # dictionary mapping in the form of(key -> value): # <real-func-name> -> <desired-func-name> # # It default's of course to the found callable attribute name # if no alias is defined. funcname = getattr(mod, '__func_alias__', {}).get(attr, attr) for tgt_mod in mod_names: try: full_funcname = '.'.join((tgt_mod, funcname)) except TypeError: full_funcname = '{0}.{1}'.format(tgt_mod, funcname) # Save many references for lookups # Careful not to overwrite existing (higher priority) functions if full_funcname not in self._dict: self._dict[full_funcname] = func if funcname not in mod_dict[tgt_mod]: setattr(mod_dict[tgt_mod], funcname, func) mod_dict[tgt_mod][funcname] = func self._apply_outputter(func, mod) # enforce depends try: Depends.enforce_dependencies(self._dict, self.tag) except RuntimeError as exc: log.info( 'Depends.enforce_dependencies() failed for the following ' 'reason: %s', exc ) for tgt_mod in mod_names: self.loaded_modules[tgt_mod] = mod_dict[tgt_mod] return True def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise KeyError('The key \'{0}\' should contain a \'.\''.format(key)) mod_name, _ = key.split('.', 1) with self._lock: # It is possible that the key is in the dictionary after # acquiring the lock due to another thread loading it. if mod_name in self.missing_modules or key in self._dict: return True # if the modulename isn't in the whitelist, don't bother if self.whitelist and mod_name not in self.whitelist: log.error( 'Failed to load function %s because its module (%s) is ' 'not in the whitelist: %s', key, mod_name, self.whitelist ) raise KeyError(key) def _inner_load(mod_name): for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and key in self._dict: return True return False # try to load the module ret = None reloaded = False # re-scan up to once, IOErrors or a failed load cause re-scans of the # filesystem while True: try: ret = _inner_load(mod_name) if not reloaded and ret is not True: self._refresh_file_mapping() reloaded = True continue break except IOError: if not reloaded: self._refresh_file_mapping() reloaded = True continue return ret def _load_all(self): ''' Load all of them ''' with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True def reload_modules(self): with self._lock: self.loaded_files = set() self._load_all() def _apply_outputter(self, func, mod): ''' Apply the __outputter__ variable to the functions ''' if hasattr(mod, '__outputter__'): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__] def _process_virtual(self, mod, module_name, virtual_func='__virtual__'): ''' Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1] ''' # The __virtual__ function will return either a True or False value. # If it returns a True value it can also set a module level attribute # named __virtualname__ with the name that the module should be # referred to as. # # This allows us to have things like the pkg module working on all # platforms under the name 'pkg'. It also allows for modules like # augeas_cfg to be referred to as 'augeas', which would otherwise have # namespace collisions. And finally it allows modules to return False # if they are not intended to run on the given platform or are missing # dependencies. virtual_aliases = getattr(mod, '__virtual_aliases__', tuple()) try: error_reason = None if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__): try: start = time.time() virtual = getattr(mod, virtual_func)() if isinstance(virtual, tuple): error_reason = virtual[1] virtual = virtual[0] if self.opts.get('virtual_timer', False): end = time.time() - start msg = 'Virtual function took {0} seconds for {1}'.format( end, module_name) log.warning(msg) except Exception as exc: error_reason = ( 'Exception raised when processing __virtual__ function' ' for {0}. Module will not be loaded: {1}'.format( mod.__name__, exc)) log.error(error_reason, exc_info_on_loglevel=logging.DEBUG) virtual = None # Get the module's virtual name virtualname = getattr(mod, '__virtualname__', virtual) if not virtual: # if __virtual__() evaluates to False then the module # wasn't meant for this platform or it's not supposed to # load for some other reason. # Some modules might accidentally return None and are # improperly loaded if virtual is None: log.warning( '%s.__virtual__() is wrongly returning `None`. ' 'It should either return `True`, `False` or a new ' 'name. If you\'re the developer of the module ' '\'%s\', please fix this.', mod.__name__, module_name ) return (False, module_name, error_reason, virtual_aliases) # At this point, __virtual__ did not return a # boolean value, let's check for deprecated usage # or module renames if virtual is not True and module_name != virtual: # The module is renaming itself. Updating the module name # with the new name log.trace('Loaded %s as virtual %s', module_name, virtual) if virtualname != virtual: # The __virtualname__ attribute does not match what's # being returned by the __virtual__() function. This # should be considered an error. log.error( 'The module \'%s\' is showing some bad usage. Its ' '__virtualname__ attribute is set to \'%s\' yet the ' '__virtual__() function is returning \'%s\'. These ' 'values should match!', mod.__name__, virtualname, virtual ) module_name = virtualname # If the __virtual__ function returns True and __virtualname__ # is set then use it elif virtual is True and virtualname != module_name: if virtualname is not True: module_name = virtualname except KeyError: # Key errors come out of the virtual function when passing # in incomplete grains sets, these can be safely ignored # and logged to debug, still, it includes the traceback to # help debugging. log.debug('KeyError when loading %s', module_name, exc_info=True) except Exception: # If the module throws an exception during __virtual__() # then log the information and continue to the next. log.error( 'Failed to read the virtual function for %s: %s', self.tag, module_name, exc_info=True ) return (False, module_name, error_reason, virtual_aliases) return (True, module_name, None, virtual_aliases)
saltstack/salt
salt/loader.py
LazyLoader._iter_files
python
def _iter_files(self, mod_name): ''' Iterate over all file_mapping files in order of closeness to mod_name ''' # do we have an exact match? if mod_name in self.file_mapping: yield mod_name # do we have a partial match? for k in self.file_mapping: if mod_name in k: yield k # anyone else? Bueller? for k in self.file_mapping: if mod_name not in k: yield k
Iterate over all file_mapping files in order of closeness to mod_name
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L1566-L1582
null
class LazyLoader(salt.utils.lazy.LazyDict): ''' A pseduo-dictionary which has a set of keys which are the name of the module and function, delimited by a dot. When the value of the key is accessed, the function is then loaded from disk and into memory. .. note:: Iterating over keys will cause all modules to be loaded. :param list module_dirs: A list of directories on disk to search for modules :param dict opts: The salt options dictionary. :param str tag: The tag for the type of module to load :param func mod_type_check: A function which can be used to verify files :param dict pack: A dictionary of function to be packed into modules as they are loaded :param list whitelist: A list of modules to whitelist :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules. :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality. If not true, the module will not load. :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values are function references themselves which are loaded on-demand. # TODO: - move modules_max_memory into here - singletons (per tag) ''' mod_dict_class = salt.utils.odict.OrderedDict def __init__(self, module_dirs, opts=None, tag='module', loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, proxy=None, virtual_funcs=None, ): # pylint: disable=W0231 ''' In pack, if any of the values are None they will be replaced with an empty context-specific dict ''' self.inject_globals = {} self.pack = {} if pack is None else pack if opts is None: opts = {} threadsafety = not opts.get('multiprocessing') self.context_dict = salt.utils.context.ContextDict(threadsafe=threadsafety) self.opts = self.__prep_mod_opts(opts) self.module_dirs = module_dirs self.tag = tag self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME self.mod_type_check = mod_type_check or _mod_type if '__context__' not in self.pack: self.pack['__context__'] = None for k, v in six.iteritems(self.pack): if v is None: # if the value of a pack is None, lets make an empty dict value = self.context_dict.get(k, {}) if isinstance(value, ThreadLocalProxy): value = ThreadLocalProxy.unproxy(value) self.context_dict[k] = value self.pack[k] = salt.utils.context.NamespacedDictWrapper(self.context_dict, k) self.whitelist = whitelist self.virtual_enable = virtual_enable self.initial_load = True # names of modules that we don't have (errors, __virtual__, etc.) self.missing_modules = {} # mapping of name -> error self.loaded_modules = {} # mapping of module_name -> dict_of_functions self.loaded_files = set() # TODO: just remove them from file_mapping? self.static_modules = static_modules if static_modules else [] if virtual_funcs is None: virtual_funcs = [] self.virtual_funcs = virtual_funcs self.disabled = set( self.opts.get( 'disable_{0}{1}'.format( self.tag, '' if self.tag[-1] == 's' else 's' ), [] ) ) # A map of suffix to description for imp self.suffix_map = {} # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [''] for (suffix, mode, kind) in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) self._lock = threading.RLock() self._refresh_file_mapping() super(LazyLoader, self).__init__() # late init the lazy loader # create all of the import namespaces _generate_module('{0}.int'.format(self.loaded_base_name)) _generate_module('{0}.int.{1}'.format(self.loaded_base_name, tag)) _generate_module('{0}.ext'.format(self.loaded_base_name)) _generate_module('{0}.ext.{1}'.format(self.loaded_base_name, tag)) def __getitem__(self, item): ''' Override the __getitem__ in order to decorate the returned function if we need to last-minute inject globals ''' func = super(LazyLoader, self).__getitem__(item) if self.inject_globals: return global_injector_decorator(self.inject_globals)(func) else: return func def __getattr__(self, mod_name): ''' Allow for "direct" attribute access-- this allows jinja templates to access things like `salt.test.ping()` ''' if mod_name in ('__getstate__', '__setstate__'): return object.__getattribute__(self, mod_name) # if we have an attribute named that, lets return it. try: return object.__getattr__(self, mod_name) # pylint: disable=no-member except AttributeError: pass # otherwise we assume its jinja template access if mod_name not in self.loaded_modules and not self.loaded: for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and mod_name in self.loaded_modules: break if mod_name in self.loaded_modules: return self.loaded_modules[mod_name] else: raise AttributeError(mod_name) def missing_fun_string(self, function_name): ''' Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ''' mod_name = function_name.split('.')[0] if mod_name in self.loaded_modules: return '\'{0}\' is not available.'.format(function_name) else: try: reason = self.missing_modules[mod_name] except KeyError: return '\'{0}\' is not available.'.format(function_name) else: if reason is not None: return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason) else: return '\'{0}\' __virtual__ returned False'.format(mod_name) def _refresh_file_mapping(self): ''' refresh the mapping of the FS on disk ''' # map of suffix to description for imp if self.opts.get('cython_enable', True) is True: try: global pyximport pyximport = __import__('pyximport') # pylint: disable=import-error pyximport.install() # add to suffix_map so file_mapping will pick it up self.suffix_map['.pyx'] = tuple() except ImportError: log.info('Cython is enabled in the options but not present ' 'in the system path. Skipping Cython modules.') # Allow for zipimport of modules if self.opts.get('enable_zip_modules', True) is True: self.suffix_map['.zip'] = tuple() # allow for module dirs if USE_IMPORTLIB: self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY) else: self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY) # create mapping of filename (without suffix) to (path, suffix) # The files are added in order of priority, so order *must* be retained. self.file_mapping = salt.utils.odict.OrderedDict() opt_match = [] def _replace_pre_ext(obj): ''' Hack so we can get the optimization level that we replaced (if any) out of the re.sub call below. We use a list here because it is a persistent data structure that we will be able to access after re.sub is called. ''' opt_match.append(obj) return '' for mod_dir in self.module_dirs: try: # Make sure we have a sorted listdir in order to have # expectable override results files = sorted( x for x in os.listdir(mod_dir) if x != '__pycache__' ) except OSError: continue # Next mod_dir if six.PY3: try: pycache_files = [ os.path.join('__pycache__', x) for x in sorted(os.listdir(os.path.join(mod_dir, '__pycache__'))) ] except OSError: pass else: files.extend(pycache_files) for filename in files: try: dirname, basename = os.path.split(filename) if basename.startswith('_'): # skip private modules # log messages omitted for obviousness continue # Next filename f_noext, ext = os.path.splitext(basename) if six.PY3: f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext) try: opt_level = int( opt_match.pop().group(1).rsplit('-', 1)[-1] ) except (AttributeError, IndexError, ValueError): # No regex match or no optimization level matched opt_level = 0 try: opt_index = self.opts['optimization_order'].index(opt_level) except KeyError: log.trace( 'Disallowed optimization level %d for module ' 'name \'%s\', skipping. Add %d to the ' '\'optimization_order\' config option if you ' 'do not want to ignore this optimization ' 'level.', opt_level, f_noext, opt_level ) continue else: # Optimization level not reflected in filename on PY2 opt_index = 0 # make sure it is a suffix we support if ext not in self.suffix_map: continue # Next filename if f_noext in self.disabled: log.trace( 'Skipping %s, it is disabled by configuration', filename ) continue # Next filename fpath = os.path.join(mod_dir, filename) # if its a directory, lets allow us to load that if ext == '': # is there something __init__? subfiles = os.listdir(fpath) for suffix in self.suffix_order: if '' == suffix: continue # Next suffix (__init__ must have a suffix) init_file = '__init__{0}'.format(suffix) if init_file in subfiles: break else: continue # Next filename try: curr_ext = self.file_mapping[f_noext][1] curr_opt_index = self.file_mapping[f_noext][2] except KeyError: pass else: if '' in (curr_ext, ext) and curr_ext != ext: log.error( 'Module/package collision: \'%s\' and \'%s\'', fpath, self.file_mapping[f_noext][0] ) if six.PY3 and ext == '.pyc' and curr_ext == '.pyc': # Check the optimization level if opt_index >= curr_opt_index: # Module name match, but a higher-priority # optimization level was already matched, skipping. continue elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext): # Match found but a higher-priorty match already # exists, so skip this. continue if six.PY3 and not dirname and ext == '.pyc': # On Python 3, we should only load .pyc files from the # __pycache__ subdirectory (i.e. when dirname is not an # empty string). continue # Made it this far - add it self.file_mapping[f_noext] = (fpath, ext, opt_index) except OSError: continue for smod in self.static_modules: f_noext = smod.split('.')[-1] self.file_mapping[f_noext] = (smod, '.o', 0) def clear(self): ''' Clear the dict ''' with self._lock: super(LazyLoader, self).clear() # clear the lazy loader self.loaded_files = set() self.missing_modules = {} self.loaded_modules = {} # if we have been loaded before, lets clear the file mapping since # we obviously want a re-do if hasattr(self, 'opts'): self._refresh_file_mapping() self.initial_load = False def __prep_mod_opts(self, opts): ''' Strip out of the opts any logger instance ''' if '__grains__' not in self.pack: grains = opts.get('grains', {}) if isinstance(grains, ThreadLocalProxy): grains = ThreadLocalProxy.unproxy(grains) self.context_dict['grains'] = grains self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains') if '__pillar__' not in self.pack: pillar = opts.get('pillar', {}) if isinstance(pillar, ThreadLocalProxy): pillar = ThreadLocalProxy.unproxy(pillar) self.context_dict['pillar'] = pillar self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar') mod_opts = {} for key, val in list(opts.items()): if key == 'logger': continue mod_opts[key] = val return mod_opts def _reload_submodules(self, mod): submodules = ( getattr(mod, sname) for sname in dir(mod) if isinstance(getattr(mod, sname), mod.__class__) ) # reload only custom "sub"modules for submodule in submodules: # it is a submodule if the name is in a namespace under mod if submodule.__name__.startswith(mod.__name__ + '.'): reload_module(submodule) self._reload_submodules(submodule) def _load_module(self, name): mod = None fpath, suffix = self.file_mapping[name][:2] self.loaded_files.add(name) fpath_dirname = os.path.dirname(fpath) try: sys.path.append(fpath_dirname) if suffix == '.pyx': mod = pyximport.load_module(name, fpath, tempfile.gettempdir()) elif suffix == '.o': top_mod = __import__(fpath, globals(), locals(), []) comps = fpath.split('.') if len(comps) < 2: mod = top_mod else: mod = top_mod for subname in comps[1:]: mod = getattr(mod, subname) elif suffix == '.zip': mod = zipimporter(fpath).load_module(name) else: desc = self.suffix_map[suffix] # if it is a directory, we don't open a file try: mod_namespace = '.'.join(( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name)) except TypeError: mod_namespace = '{0}.{1}.{2}.{3}'.format( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name) if suffix == '': if USE_IMPORTLIB: # pylint: disable=no-member # Package directory, look for __init__ loader_details = [ (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES), (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES), (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), ] file_finder = importlib.machinery.FileFinder( fpath_dirname, *loader_details ) spec = file_finder.find_spec(mod_namespace) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: mod = imp.load_module(mod_namespace, None, fpath, desc) # reload all submodules if necessary if not self.initial_load: self._reload_submodules(mod) else: if USE_IMPORTLIB: # pylint: disable=no-member loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath) spec = importlib.util.spec_from_file_location( mod_namespace, fpath, loader=loader ) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() #mod = importlib.util.module_from_spec(spec) #spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: with salt.utils.files.fopen(fpath, desc[1]) as fn_: mod = imp.load_module(mod_namespace, fn_, fpath, desc) except IOError: raise except ImportError as exc: if 'magic number' in six.text_type(exc): error_msg = 'Failed to import {0} {1}. Bad magic number. If migrating from Python2 to Python3, remove all .pyc files and try again.'.format(self.tag, name) log.warning(error_msg) self.missing_modules[name] = error_msg log.debug( 'Failed to import %s %s:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = exc return False except Exception as error: log.error( 'Failed to import %s %s, this is due most likely to a ' 'syntax error:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False except SystemExit as error: try: fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1] except Exception: pass else: tgt_fn = os.path.join('salt', 'utils', 'process.py') if fn_.endswith(tgt_fn) and '_handle_signals' in caller: # Race conditon, SIGTERM or SIGINT received while loader # was in process of loading a module. Call sys.exit to # ensure that the process is killed. sys.exit(salt.defaults.exitcodes.EX_OK) log.error( 'Failed to import %s %s as the module called exit()\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False finally: sys.path.remove(fpath_dirname) if hasattr(mod, '__opts__'): mod.__opts__.update(self.opts) else: mod.__opts__ = self.opts # pack whatever other globals we were asked to for p_name, p_value in six.iteritems(self.pack): _inject_into_mod(mod, p_name, p_value) module_name = mod.__name__.rsplit('.', 1)[-1] # Call a module's initialization method if it exists module_init = getattr(mod, '__init__', None) if inspect.isfunction(module_init): try: module_init(self.opts) except TypeError as e: log.error(e) except Exception: err_string = '__init__ failed' log.debug( 'Error loading %s.%s: %s', self.tag, module_name, err_string, exc_info=True ) self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False # if virtual modules are enabled, we need to look for the # __virtual__() function inside that module and run it. if self.virtual_enable: virtual_funcs_to_process = ['__virtual__'] + self.virtual_funcs for virtual_func in virtual_funcs_to_process: virtual_ret, module_name, virtual_err, virtual_aliases = \ self._process_virtual(mod, module_name, virtual_func) if virtual_err is not None: log.trace( 'Error loading %s.%s: %s', self.tag, module_name, virtual_err ) # if _process_virtual returned a non-True value then we are # supposed to not process this module if virtual_ret is not True and module_name not in self.missing_modules: # If a module has information about why it could not be loaded, record it self.missing_modules[module_name] = virtual_err self.missing_modules[name] = virtual_err return False else: virtual_aliases = () # If this is a proxy minion then MOST modules cannot work. Therefore, require that # any module that does work with salt-proxy-minion define __proxyenabled__ as a list # containing the names of the proxy types that the module supports. # # Render modules and state modules are OK though if 'proxy' in self.opts: if self.tag in ['grains', 'proxy']: if not hasattr(mod, '__proxyenabled__') or \ (self.opts['proxy']['proxytype'] not in mod.__proxyenabled__ and '*' not in mod.__proxyenabled__): err_string = 'not a proxy_minion enabled module' self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False if getattr(mod, '__load__', False) is not False: log.info( 'The functions from module \'%s\' are being loaded from the ' 'provided __load__ attribute', module_name ) # If we had another module by the same virtual name, we should put any # new functions under the existing dictionary. mod_names = [module_name] + list(virtual_aliases) mod_dict = dict(( (x, self.loaded_modules.get(x, self.mod_dict_class())) for x in mod_names )) for attr in getattr(mod, '__load__', dir(mod)): if attr.startswith('_') and attr != '__call__': # private functions are skipped, # except __call__ which is default entrance # for multi-function batch-like state syntax continue func = getattr(mod, attr) if not inspect.isfunction(func) and not isinstance(func, functools.partial): # Not a function!? Skip it!!! continue # Let's get the function name. # If the module has the __func_alias__ attribute, it must be a # dictionary mapping in the form of(key -> value): # <real-func-name> -> <desired-func-name> # # It default's of course to the found callable attribute name # if no alias is defined. funcname = getattr(mod, '__func_alias__', {}).get(attr, attr) for tgt_mod in mod_names: try: full_funcname = '.'.join((tgt_mod, funcname)) except TypeError: full_funcname = '{0}.{1}'.format(tgt_mod, funcname) # Save many references for lookups # Careful not to overwrite existing (higher priority) functions if full_funcname not in self._dict: self._dict[full_funcname] = func if funcname not in mod_dict[tgt_mod]: setattr(mod_dict[tgt_mod], funcname, func) mod_dict[tgt_mod][funcname] = func self._apply_outputter(func, mod) # enforce depends try: Depends.enforce_dependencies(self._dict, self.tag) except RuntimeError as exc: log.info( 'Depends.enforce_dependencies() failed for the following ' 'reason: %s', exc ) for tgt_mod in mod_names: self.loaded_modules[tgt_mod] = mod_dict[tgt_mod] return True def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise KeyError('The key \'{0}\' should contain a \'.\''.format(key)) mod_name, _ = key.split('.', 1) with self._lock: # It is possible that the key is in the dictionary after # acquiring the lock due to another thread loading it. if mod_name in self.missing_modules or key in self._dict: return True # if the modulename isn't in the whitelist, don't bother if self.whitelist and mod_name not in self.whitelist: log.error( 'Failed to load function %s because its module (%s) is ' 'not in the whitelist: %s', key, mod_name, self.whitelist ) raise KeyError(key) def _inner_load(mod_name): for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and key in self._dict: return True return False # try to load the module ret = None reloaded = False # re-scan up to once, IOErrors or a failed load cause re-scans of the # filesystem while True: try: ret = _inner_load(mod_name) if not reloaded and ret is not True: self._refresh_file_mapping() reloaded = True continue break except IOError: if not reloaded: self._refresh_file_mapping() reloaded = True continue return ret def _load_all(self): ''' Load all of them ''' with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True def reload_modules(self): with self._lock: self.loaded_files = set() self._load_all() def _apply_outputter(self, func, mod): ''' Apply the __outputter__ variable to the functions ''' if hasattr(mod, '__outputter__'): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__] def _process_virtual(self, mod, module_name, virtual_func='__virtual__'): ''' Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1] ''' # The __virtual__ function will return either a True or False value. # If it returns a True value it can also set a module level attribute # named __virtualname__ with the name that the module should be # referred to as. # # This allows us to have things like the pkg module working on all # platforms under the name 'pkg'. It also allows for modules like # augeas_cfg to be referred to as 'augeas', which would otherwise have # namespace collisions. And finally it allows modules to return False # if they are not intended to run on the given platform or are missing # dependencies. virtual_aliases = getattr(mod, '__virtual_aliases__', tuple()) try: error_reason = None if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__): try: start = time.time() virtual = getattr(mod, virtual_func)() if isinstance(virtual, tuple): error_reason = virtual[1] virtual = virtual[0] if self.opts.get('virtual_timer', False): end = time.time() - start msg = 'Virtual function took {0} seconds for {1}'.format( end, module_name) log.warning(msg) except Exception as exc: error_reason = ( 'Exception raised when processing __virtual__ function' ' for {0}. Module will not be loaded: {1}'.format( mod.__name__, exc)) log.error(error_reason, exc_info_on_loglevel=logging.DEBUG) virtual = None # Get the module's virtual name virtualname = getattr(mod, '__virtualname__', virtual) if not virtual: # if __virtual__() evaluates to False then the module # wasn't meant for this platform or it's not supposed to # load for some other reason. # Some modules might accidentally return None and are # improperly loaded if virtual is None: log.warning( '%s.__virtual__() is wrongly returning `None`. ' 'It should either return `True`, `False` or a new ' 'name. If you\'re the developer of the module ' '\'%s\', please fix this.', mod.__name__, module_name ) return (False, module_name, error_reason, virtual_aliases) # At this point, __virtual__ did not return a # boolean value, let's check for deprecated usage # or module renames if virtual is not True and module_name != virtual: # The module is renaming itself. Updating the module name # with the new name log.trace('Loaded %s as virtual %s', module_name, virtual) if virtualname != virtual: # The __virtualname__ attribute does not match what's # being returned by the __virtual__() function. This # should be considered an error. log.error( 'The module \'%s\' is showing some bad usage. Its ' '__virtualname__ attribute is set to \'%s\' yet the ' '__virtual__() function is returning \'%s\'. These ' 'values should match!', mod.__name__, virtualname, virtual ) module_name = virtualname # If the __virtual__ function returns True and __virtualname__ # is set then use it elif virtual is True and virtualname != module_name: if virtualname is not True: module_name = virtualname except KeyError: # Key errors come out of the virtual function when passing # in incomplete grains sets, these can be safely ignored # and logged to debug, still, it includes the traceback to # help debugging. log.debug('KeyError when loading %s', module_name, exc_info=True) except Exception: # If the module throws an exception during __virtual__() # then log the information and continue to the next. log.error( 'Failed to read the virtual function for %s: %s', self.tag, module_name, exc_info=True ) return (False, module_name, error_reason, virtual_aliases) return (True, module_name, None, virtual_aliases)
saltstack/salt
salt/loader.py
LazyLoader._load
python
def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise KeyError('The key \'{0}\' should contain a \'.\''.format(key)) mod_name, _ = key.split('.', 1) with self._lock: # It is possible that the key is in the dictionary after # acquiring the lock due to another thread loading it. if mod_name in self.missing_modules or key in self._dict: return True # if the modulename isn't in the whitelist, don't bother if self.whitelist and mod_name not in self.whitelist: log.error( 'Failed to load function %s because its module (%s) is ' 'not in the whitelist: %s', key, mod_name, self.whitelist ) raise KeyError(key) def _inner_load(mod_name): for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and key in self._dict: return True return False # try to load the module ret = None reloaded = False # re-scan up to once, IOErrors or a failed load cause re-scans of the # filesystem while True: try: ret = _inner_load(mod_name) if not reloaded and ret is not True: self._refresh_file_mapping() reloaded = True continue break except IOError: if not reloaded: self._refresh_file_mapping() reloaded = True continue return ret
Load a single item if you have it
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L1851-L1902
null
class LazyLoader(salt.utils.lazy.LazyDict): ''' A pseduo-dictionary which has a set of keys which are the name of the module and function, delimited by a dot. When the value of the key is accessed, the function is then loaded from disk and into memory. .. note:: Iterating over keys will cause all modules to be loaded. :param list module_dirs: A list of directories on disk to search for modules :param dict opts: The salt options dictionary. :param str tag: The tag for the type of module to load :param func mod_type_check: A function which can be used to verify files :param dict pack: A dictionary of function to be packed into modules as they are loaded :param list whitelist: A list of modules to whitelist :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules. :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality. If not true, the module will not load. :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values are function references themselves which are loaded on-demand. # TODO: - move modules_max_memory into here - singletons (per tag) ''' mod_dict_class = salt.utils.odict.OrderedDict def __init__(self, module_dirs, opts=None, tag='module', loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, proxy=None, virtual_funcs=None, ): # pylint: disable=W0231 ''' In pack, if any of the values are None they will be replaced with an empty context-specific dict ''' self.inject_globals = {} self.pack = {} if pack is None else pack if opts is None: opts = {} threadsafety = not opts.get('multiprocessing') self.context_dict = salt.utils.context.ContextDict(threadsafe=threadsafety) self.opts = self.__prep_mod_opts(opts) self.module_dirs = module_dirs self.tag = tag self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME self.mod_type_check = mod_type_check or _mod_type if '__context__' not in self.pack: self.pack['__context__'] = None for k, v in six.iteritems(self.pack): if v is None: # if the value of a pack is None, lets make an empty dict value = self.context_dict.get(k, {}) if isinstance(value, ThreadLocalProxy): value = ThreadLocalProxy.unproxy(value) self.context_dict[k] = value self.pack[k] = salt.utils.context.NamespacedDictWrapper(self.context_dict, k) self.whitelist = whitelist self.virtual_enable = virtual_enable self.initial_load = True # names of modules that we don't have (errors, __virtual__, etc.) self.missing_modules = {} # mapping of name -> error self.loaded_modules = {} # mapping of module_name -> dict_of_functions self.loaded_files = set() # TODO: just remove them from file_mapping? self.static_modules = static_modules if static_modules else [] if virtual_funcs is None: virtual_funcs = [] self.virtual_funcs = virtual_funcs self.disabled = set( self.opts.get( 'disable_{0}{1}'.format( self.tag, '' if self.tag[-1] == 's' else 's' ), [] ) ) # A map of suffix to description for imp self.suffix_map = {} # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [''] for (suffix, mode, kind) in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) self._lock = threading.RLock() self._refresh_file_mapping() super(LazyLoader, self).__init__() # late init the lazy loader # create all of the import namespaces _generate_module('{0}.int'.format(self.loaded_base_name)) _generate_module('{0}.int.{1}'.format(self.loaded_base_name, tag)) _generate_module('{0}.ext'.format(self.loaded_base_name)) _generate_module('{0}.ext.{1}'.format(self.loaded_base_name, tag)) def __getitem__(self, item): ''' Override the __getitem__ in order to decorate the returned function if we need to last-minute inject globals ''' func = super(LazyLoader, self).__getitem__(item) if self.inject_globals: return global_injector_decorator(self.inject_globals)(func) else: return func def __getattr__(self, mod_name): ''' Allow for "direct" attribute access-- this allows jinja templates to access things like `salt.test.ping()` ''' if mod_name in ('__getstate__', '__setstate__'): return object.__getattribute__(self, mod_name) # if we have an attribute named that, lets return it. try: return object.__getattr__(self, mod_name) # pylint: disable=no-member except AttributeError: pass # otherwise we assume its jinja template access if mod_name not in self.loaded_modules and not self.loaded: for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and mod_name in self.loaded_modules: break if mod_name in self.loaded_modules: return self.loaded_modules[mod_name] else: raise AttributeError(mod_name) def missing_fun_string(self, function_name): ''' Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ''' mod_name = function_name.split('.')[0] if mod_name in self.loaded_modules: return '\'{0}\' is not available.'.format(function_name) else: try: reason = self.missing_modules[mod_name] except KeyError: return '\'{0}\' is not available.'.format(function_name) else: if reason is not None: return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason) else: return '\'{0}\' __virtual__ returned False'.format(mod_name) def _refresh_file_mapping(self): ''' refresh the mapping of the FS on disk ''' # map of suffix to description for imp if self.opts.get('cython_enable', True) is True: try: global pyximport pyximport = __import__('pyximport') # pylint: disable=import-error pyximport.install() # add to suffix_map so file_mapping will pick it up self.suffix_map['.pyx'] = tuple() except ImportError: log.info('Cython is enabled in the options but not present ' 'in the system path. Skipping Cython modules.') # Allow for zipimport of modules if self.opts.get('enable_zip_modules', True) is True: self.suffix_map['.zip'] = tuple() # allow for module dirs if USE_IMPORTLIB: self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY) else: self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY) # create mapping of filename (without suffix) to (path, suffix) # The files are added in order of priority, so order *must* be retained. self.file_mapping = salt.utils.odict.OrderedDict() opt_match = [] def _replace_pre_ext(obj): ''' Hack so we can get the optimization level that we replaced (if any) out of the re.sub call below. We use a list here because it is a persistent data structure that we will be able to access after re.sub is called. ''' opt_match.append(obj) return '' for mod_dir in self.module_dirs: try: # Make sure we have a sorted listdir in order to have # expectable override results files = sorted( x for x in os.listdir(mod_dir) if x != '__pycache__' ) except OSError: continue # Next mod_dir if six.PY3: try: pycache_files = [ os.path.join('__pycache__', x) for x in sorted(os.listdir(os.path.join(mod_dir, '__pycache__'))) ] except OSError: pass else: files.extend(pycache_files) for filename in files: try: dirname, basename = os.path.split(filename) if basename.startswith('_'): # skip private modules # log messages omitted for obviousness continue # Next filename f_noext, ext = os.path.splitext(basename) if six.PY3: f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext) try: opt_level = int( opt_match.pop().group(1).rsplit('-', 1)[-1] ) except (AttributeError, IndexError, ValueError): # No regex match or no optimization level matched opt_level = 0 try: opt_index = self.opts['optimization_order'].index(opt_level) except KeyError: log.trace( 'Disallowed optimization level %d for module ' 'name \'%s\', skipping. Add %d to the ' '\'optimization_order\' config option if you ' 'do not want to ignore this optimization ' 'level.', opt_level, f_noext, opt_level ) continue else: # Optimization level not reflected in filename on PY2 opt_index = 0 # make sure it is a suffix we support if ext not in self.suffix_map: continue # Next filename if f_noext in self.disabled: log.trace( 'Skipping %s, it is disabled by configuration', filename ) continue # Next filename fpath = os.path.join(mod_dir, filename) # if its a directory, lets allow us to load that if ext == '': # is there something __init__? subfiles = os.listdir(fpath) for suffix in self.suffix_order: if '' == suffix: continue # Next suffix (__init__ must have a suffix) init_file = '__init__{0}'.format(suffix) if init_file in subfiles: break else: continue # Next filename try: curr_ext = self.file_mapping[f_noext][1] curr_opt_index = self.file_mapping[f_noext][2] except KeyError: pass else: if '' in (curr_ext, ext) and curr_ext != ext: log.error( 'Module/package collision: \'%s\' and \'%s\'', fpath, self.file_mapping[f_noext][0] ) if six.PY3 and ext == '.pyc' and curr_ext == '.pyc': # Check the optimization level if opt_index >= curr_opt_index: # Module name match, but a higher-priority # optimization level was already matched, skipping. continue elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext): # Match found but a higher-priorty match already # exists, so skip this. continue if six.PY3 and not dirname and ext == '.pyc': # On Python 3, we should only load .pyc files from the # __pycache__ subdirectory (i.e. when dirname is not an # empty string). continue # Made it this far - add it self.file_mapping[f_noext] = (fpath, ext, opt_index) except OSError: continue for smod in self.static_modules: f_noext = smod.split('.')[-1] self.file_mapping[f_noext] = (smod, '.o', 0) def clear(self): ''' Clear the dict ''' with self._lock: super(LazyLoader, self).clear() # clear the lazy loader self.loaded_files = set() self.missing_modules = {} self.loaded_modules = {} # if we have been loaded before, lets clear the file mapping since # we obviously want a re-do if hasattr(self, 'opts'): self._refresh_file_mapping() self.initial_load = False def __prep_mod_opts(self, opts): ''' Strip out of the opts any logger instance ''' if '__grains__' not in self.pack: grains = opts.get('grains', {}) if isinstance(grains, ThreadLocalProxy): grains = ThreadLocalProxy.unproxy(grains) self.context_dict['grains'] = grains self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains') if '__pillar__' not in self.pack: pillar = opts.get('pillar', {}) if isinstance(pillar, ThreadLocalProxy): pillar = ThreadLocalProxy.unproxy(pillar) self.context_dict['pillar'] = pillar self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar') mod_opts = {} for key, val in list(opts.items()): if key == 'logger': continue mod_opts[key] = val return mod_opts def _iter_files(self, mod_name): ''' Iterate over all file_mapping files in order of closeness to mod_name ''' # do we have an exact match? if mod_name in self.file_mapping: yield mod_name # do we have a partial match? for k in self.file_mapping: if mod_name in k: yield k # anyone else? Bueller? for k in self.file_mapping: if mod_name not in k: yield k def _reload_submodules(self, mod): submodules = ( getattr(mod, sname) for sname in dir(mod) if isinstance(getattr(mod, sname), mod.__class__) ) # reload only custom "sub"modules for submodule in submodules: # it is a submodule if the name is in a namespace under mod if submodule.__name__.startswith(mod.__name__ + '.'): reload_module(submodule) self._reload_submodules(submodule) def _load_module(self, name): mod = None fpath, suffix = self.file_mapping[name][:2] self.loaded_files.add(name) fpath_dirname = os.path.dirname(fpath) try: sys.path.append(fpath_dirname) if suffix == '.pyx': mod = pyximport.load_module(name, fpath, tempfile.gettempdir()) elif suffix == '.o': top_mod = __import__(fpath, globals(), locals(), []) comps = fpath.split('.') if len(comps) < 2: mod = top_mod else: mod = top_mod for subname in comps[1:]: mod = getattr(mod, subname) elif suffix == '.zip': mod = zipimporter(fpath).load_module(name) else: desc = self.suffix_map[suffix] # if it is a directory, we don't open a file try: mod_namespace = '.'.join(( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name)) except TypeError: mod_namespace = '{0}.{1}.{2}.{3}'.format( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name) if suffix == '': if USE_IMPORTLIB: # pylint: disable=no-member # Package directory, look for __init__ loader_details = [ (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES), (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES), (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), ] file_finder = importlib.machinery.FileFinder( fpath_dirname, *loader_details ) spec = file_finder.find_spec(mod_namespace) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: mod = imp.load_module(mod_namespace, None, fpath, desc) # reload all submodules if necessary if not self.initial_load: self._reload_submodules(mod) else: if USE_IMPORTLIB: # pylint: disable=no-member loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath) spec = importlib.util.spec_from_file_location( mod_namespace, fpath, loader=loader ) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() #mod = importlib.util.module_from_spec(spec) #spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: with salt.utils.files.fopen(fpath, desc[1]) as fn_: mod = imp.load_module(mod_namespace, fn_, fpath, desc) except IOError: raise except ImportError as exc: if 'magic number' in six.text_type(exc): error_msg = 'Failed to import {0} {1}. Bad magic number. If migrating from Python2 to Python3, remove all .pyc files and try again.'.format(self.tag, name) log.warning(error_msg) self.missing_modules[name] = error_msg log.debug( 'Failed to import %s %s:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = exc return False except Exception as error: log.error( 'Failed to import %s %s, this is due most likely to a ' 'syntax error:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False except SystemExit as error: try: fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1] except Exception: pass else: tgt_fn = os.path.join('salt', 'utils', 'process.py') if fn_.endswith(tgt_fn) and '_handle_signals' in caller: # Race conditon, SIGTERM or SIGINT received while loader # was in process of loading a module. Call sys.exit to # ensure that the process is killed. sys.exit(salt.defaults.exitcodes.EX_OK) log.error( 'Failed to import %s %s as the module called exit()\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False finally: sys.path.remove(fpath_dirname) if hasattr(mod, '__opts__'): mod.__opts__.update(self.opts) else: mod.__opts__ = self.opts # pack whatever other globals we were asked to for p_name, p_value in six.iteritems(self.pack): _inject_into_mod(mod, p_name, p_value) module_name = mod.__name__.rsplit('.', 1)[-1] # Call a module's initialization method if it exists module_init = getattr(mod, '__init__', None) if inspect.isfunction(module_init): try: module_init(self.opts) except TypeError as e: log.error(e) except Exception: err_string = '__init__ failed' log.debug( 'Error loading %s.%s: %s', self.tag, module_name, err_string, exc_info=True ) self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False # if virtual modules are enabled, we need to look for the # __virtual__() function inside that module and run it. if self.virtual_enable: virtual_funcs_to_process = ['__virtual__'] + self.virtual_funcs for virtual_func in virtual_funcs_to_process: virtual_ret, module_name, virtual_err, virtual_aliases = \ self._process_virtual(mod, module_name, virtual_func) if virtual_err is not None: log.trace( 'Error loading %s.%s: %s', self.tag, module_name, virtual_err ) # if _process_virtual returned a non-True value then we are # supposed to not process this module if virtual_ret is not True and module_name not in self.missing_modules: # If a module has information about why it could not be loaded, record it self.missing_modules[module_name] = virtual_err self.missing_modules[name] = virtual_err return False else: virtual_aliases = () # If this is a proxy minion then MOST modules cannot work. Therefore, require that # any module that does work with salt-proxy-minion define __proxyenabled__ as a list # containing the names of the proxy types that the module supports. # # Render modules and state modules are OK though if 'proxy' in self.opts: if self.tag in ['grains', 'proxy']: if not hasattr(mod, '__proxyenabled__') or \ (self.opts['proxy']['proxytype'] not in mod.__proxyenabled__ and '*' not in mod.__proxyenabled__): err_string = 'not a proxy_minion enabled module' self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False if getattr(mod, '__load__', False) is not False: log.info( 'The functions from module \'%s\' are being loaded from the ' 'provided __load__ attribute', module_name ) # If we had another module by the same virtual name, we should put any # new functions under the existing dictionary. mod_names = [module_name] + list(virtual_aliases) mod_dict = dict(( (x, self.loaded_modules.get(x, self.mod_dict_class())) for x in mod_names )) for attr in getattr(mod, '__load__', dir(mod)): if attr.startswith('_') and attr != '__call__': # private functions are skipped, # except __call__ which is default entrance # for multi-function batch-like state syntax continue func = getattr(mod, attr) if not inspect.isfunction(func) and not isinstance(func, functools.partial): # Not a function!? Skip it!!! continue # Let's get the function name. # If the module has the __func_alias__ attribute, it must be a # dictionary mapping in the form of(key -> value): # <real-func-name> -> <desired-func-name> # # It default's of course to the found callable attribute name # if no alias is defined. funcname = getattr(mod, '__func_alias__', {}).get(attr, attr) for tgt_mod in mod_names: try: full_funcname = '.'.join((tgt_mod, funcname)) except TypeError: full_funcname = '{0}.{1}'.format(tgt_mod, funcname) # Save many references for lookups # Careful not to overwrite existing (higher priority) functions if full_funcname not in self._dict: self._dict[full_funcname] = func if funcname not in mod_dict[tgt_mod]: setattr(mod_dict[tgt_mod], funcname, func) mod_dict[tgt_mod][funcname] = func self._apply_outputter(func, mod) # enforce depends try: Depends.enforce_dependencies(self._dict, self.tag) except RuntimeError as exc: log.info( 'Depends.enforce_dependencies() failed for the following ' 'reason: %s', exc ) for tgt_mod in mod_names: self.loaded_modules[tgt_mod] = mod_dict[tgt_mod] return True def _load_all(self): ''' Load all of them ''' with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True def reload_modules(self): with self._lock: self.loaded_files = set() self._load_all() def _apply_outputter(self, func, mod): ''' Apply the __outputter__ variable to the functions ''' if hasattr(mod, '__outputter__'): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__] def _process_virtual(self, mod, module_name, virtual_func='__virtual__'): ''' Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1] ''' # The __virtual__ function will return either a True or False value. # If it returns a True value it can also set a module level attribute # named __virtualname__ with the name that the module should be # referred to as. # # This allows us to have things like the pkg module working on all # platforms under the name 'pkg'. It also allows for modules like # augeas_cfg to be referred to as 'augeas', which would otherwise have # namespace collisions. And finally it allows modules to return False # if they are not intended to run on the given platform or are missing # dependencies. virtual_aliases = getattr(mod, '__virtual_aliases__', tuple()) try: error_reason = None if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__): try: start = time.time() virtual = getattr(mod, virtual_func)() if isinstance(virtual, tuple): error_reason = virtual[1] virtual = virtual[0] if self.opts.get('virtual_timer', False): end = time.time() - start msg = 'Virtual function took {0} seconds for {1}'.format( end, module_name) log.warning(msg) except Exception as exc: error_reason = ( 'Exception raised when processing __virtual__ function' ' for {0}. Module will not be loaded: {1}'.format( mod.__name__, exc)) log.error(error_reason, exc_info_on_loglevel=logging.DEBUG) virtual = None # Get the module's virtual name virtualname = getattr(mod, '__virtualname__', virtual) if not virtual: # if __virtual__() evaluates to False then the module # wasn't meant for this platform or it's not supposed to # load for some other reason. # Some modules might accidentally return None and are # improperly loaded if virtual is None: log.warning( '%s.__virtual__() is wrongly returning `None`. ' 'It should either return `True`, `False` or a new ' 'name. If you\'re the developer of the module ' '\'%s\', please fix this.', mod.__name__, module_name ) return (False, module_name, error_reason, virtual_aliases) # At this point, __virtual__ did not return a # boolean value, let's check for deprecated usage # or module renames if virtual is not True and module_name != virtual: # The module is renaming itself. Updating the module name # with the new name log.trace('Loaded %s as virtual %s', module_name, virtual) if virtualname != virtual: # The __virtualname__ attribute does not match what's # being returned by the __virtual__() function. This # should be considered an error. log.error( 'The module \'%s\' is showing some bad usage. Its ' '__virtualname__ attribute is set to \'%s\' yet the ' '__virtual__() function is returning \'%s\'. These ' 'values should match!', mod.__name__, virtualname, virtual ) module_name = virtualname # If the __virtual__ function returns True and __virtualname__ # is set then use it elif virtual is True and virtualname != module_name: if virtualname is not True: module_name = virtualname except KeyError: # Key errors come out of the virtual function when passing # in incomplete grains sets, these can be safely ignored # and logged to debug, still, it includes the traceback to # help debugging. log.debug('KeyError when loading %s', module_name, exc_info=True) except Exception: # If the module throws an exception during __virtual__() # then log the information and continue to the next. log.error( 'Failed to read the virtual function for %s: %s', self.tag, module_name, exc_info=True ) return (False, module_name, error_reason, virtual_aliases) return (True, module_name, None, virtual_aliases)
saltstack/salt
salt/loader.py
LazyLoader._load_all
python
def _load_all(self): ''' Load all of them ''' with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True
Load all of them
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L1904-L1914
null
class LazyLoader(salt.utils.lazy.LazyDict): ''' A pseduo-dictionary which has a set of keys which are the name of the module and function, delimited by a dot. When the value of the key is accessed, the function is then loaded from disk and into memory. .. note:: Iterating over keys will cause all modules to be loaded. :param list module_dirs: A list of directories on disk to search for modules :param dict opts: The salt options dictionary. :param str tag: The tag for the type of module to load :param func mod_type_check: A function which can be used to verify files :param dict pack: A dictionary of function to be packed into modules as they are loaded :param list whitelist: A list of modules to whitelist :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules. :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality. If not true, the module will not load. :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values are function references themselves which are loaded on-demand. # TODO: - move modules_max_memory into here - singletons (per tag) ''' mod_dict_class = salt.utils.odict.OrderedDict def __init__(self, module_dirs, opts=None, tag='module', loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, proxy=None, virtual_funcs=None, ): # pylint: disable=W0231 ''' In pack, if any of the values are None they will be replaced with an empty context-specific dict ''' self.inject_globals = {} self.pack = {} if pack is None else pack if opts is None: opts = {} threadsafety = not opts.get('multiprocessing') self.context_dict = salt.utils.context.ContextDict(threadsafe=threadsafety) self.opts = self.__prep_mod_opts(opts) self.module_dirs = module_dirs self.tag = tag self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME self.mod_type_check = mod_type_check or _mod_type if '__context__' not in self.pack: self.pack['__context__'] = None for k, v in six.iteritems(self.pack): if v is None: # if the value of a pack is None, lets make an empty dict value = self.context_dict.get(k, {}) if isinstance(value, ThreadLocalProxy): value = ThreadLocalProxy.unproxy(value) self.context_dict[k] = value self.pack[k] = salt.utils.context.NamespacedDictWrapper(self.context_dict, k) self.whitelist = whitelist self.virtual_enable = virtual_enable self.initial_load = True # names of modules that we don't have (errors, __virtual__, etc.) self.missing_modules = {} # mapping of name -> error self.loaded_modules = {} # mapping of module_name -> dict_of_functions self.loaded_files = set() # TODO: just remove them from file_mapping? self.static_modules = static_modules if static_modules else [] if virtual_funcs is None: virtual_funcs = [] self.virtual_funcs = virtual_funcs self.disabled = set( self.opts.get( 'disable_{0}{1}'.format( self.tag, '' if self.tag[-1] == 's' else 's' ), [] ) ) # A map of suffix to description for imp self.suffix_map = {} # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [''] for (suffix, mode, kind) in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) self._lock = threading.RLock() self._refresh_file_mapping() super(LazyLoader, self).__init__() # late init the lazy loader # create all of the import namespaces _generate_module('{0}.int'.format(self.loaded_base_name)) _generate_module('{0}.int.{1}'.format(self.loaded_base_name, tag)) _generate_module('{0}.ext'.format(self.loaded_base_name)) _generate_module('{0}.ext.{1}'.format(self.loaded_base_name, tag)) def __getitem__(self, item): ''' Override the __getitem__ in order to decorate the returned function if we need to last-minute inject globals ''' func = super(LazyLoader, self).__getitem__(item) if self.inject_globals: return global_injector_decorator(self.inject_globals)(func) else: return func def __getattr__(self, mod_name): ''' Allow for "direct" attribute access-- this allows jinja templates to access things like `salt.test.ping()` ''' if mod_name in ('__getstate__', '__setstate__'): return object.__getattribute__(self, mod_name) # if we have an attribute named that, lets return it. try: return object.__getattr__(self, mod_name) # pylint: disable=no-member except AttributeError: pass # otherwise we assume its jinja template access if mod_name not in self.loaded_modules and not self.loaded: for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and mod_name in self.loaded_modules: break if mod_name in self.loaded_modules: return self.loaded_modules[mod_name] else: raise AttributeError(mod_name) def missing_fun_string(self, function_name): ''' Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ''' mod_name = function_name.split('.')[0] if mod_name in self.loaded_modules: return '\'{0}\' is not available.'.format(function_name) else: try: reason = self.missing_modules[mod_name] except KeyError: return '\'{0}\' is not available.'.format(function_name) else: if reason is not None: return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason) else: return '\'{0}\' __virtual__ returned False'.format(mod_name) def _refresh_file_mapping(self): ''' refresh the mapping of the FS on disk ''' # map of suffix to description for imp if self.opts.get('cython_enable', True) is True: try: global pyximport pyximport = __import__('pyximport') # pylint: disable=import-error pyximport.install() # add to suffix_map so file_mapping will pick it up self.suffix_map['.pyx'] = tuple() except ImportError: log.info('Cython is enabled in the options but not present ' 'in the system path. Skipping Cython modules.') # Allow for zipimport of modules if self.opts.get('enable_zip_modules', True) is True: self.suffix_map['.zip'] = tuple() # allow for module dirs if USE_IMPORTLIB: self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY) else: self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY) # create mapping of filename (without suffix) to (path, suffix) # The files are added in order of priority, so order *must* be retained. self.file_mapping = salt.utils.odict.OrderedDict() opt_match = [] def _replace_pre_ext(obj): ''' Hack so we can get the optimization level that we replaced (if any) out of the re.sub call below. We use a list here because it is a persistent data structure that we will be able to access after re.sub is called. ''' opt_match.append(obj) return '' for mod_dir in self.module_dirs: try: # Make sure we have a sorted listdir in order to have # expectable override results files = sorted( x for x in os.listdir(mod_dir) if x != '__pycache__' ) except OSError: continue # Next mod_dir if six.PY3: try: pycache_files = [ os.path.join('__pycache__', x) for x in sorted(os.listdir(os.path.join(mod_dir, '__pycache__'))) ] except OSError: pass else: files.extend(pycache_files) for filename in files: try: dirname, basename = os.path.split(filename) if basename.startswith('_'): # skip private modules # log messages omitted for obviousness continue # Next filename f_noext, ext = os.path.splitext(basename) if six.PY3: f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext) try: opt_level = int( opt_match.pop().group(1).rsplit('-', 1)[-1] ) except (AttributeError, IndexError, ValueError): # No regex match or no optimization level matched opt_level = 0 try: opt_index = self.opts['optimization_order'].index(opt_level) except KeyError: log.trace( 'Disallowed optimization level %d for module ' 'name \'%s\', skipping. Add %d to the ' '\'optimization_order\' config option if you ' 'do not want to ignore this optimization ' 'level.', opt_level, f_noext, opt_level ) continue else: # Optimization level not reflected in filename on PY2 opt_index = 0 # make sure it is a suffix we support if ext not in self.suffix_map: continue # Next filename if f_noext in self.disabled: log.trace( 'Skipping %s, it is disabled by configuration', filename ) continue # Next filename fpath = os.path.join(mod_dir, filename) # if its a directory, lets allow us to load that if ext == '': # is there something __init__? subfiles = os.listdir(fpath) for suffix in self.suffix_order: if '' == suffix: continue # Next suffix (__init__ must have a suffix) init_file = '__init__{0}'.format(suffix) if init_file in subfiles: break else: continue # Next filename try: curr_ext = self.file_mapping[f_noext][1] curr_opt_index = self.file_mapping[f_noext][2] except KeyError: pass else: if '' in (curr_ext, ext) and curr_ext != ext: log.error( 'Module/package collision: \'%s\' and \'%s\'', fpath, self.file_mapping[f_noext][0] ) if six.PY3 and ext == '.pyc' and curr_ext == '.pyc': # Check the optimization level if opt_index >= curr_opt_index: # Module name match, but a higher-priority # optimization level was already matched, skipping. continue elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext): # Match found but a higher-priorty match already # exists, so skip this. continue if six.PY3 and not dirname and ext == '.pyc': # On Python 3, we should only load .pyc files from the # __pycache__ subdirectory (i.e. when dirname is not an # empty string). continue # Made it this far - add it self.file_mapping[f_noext] = (fpath, ext, opt_index) except OSError: continue for smod in self.static_modules: f_noext = smod.split('.')[-1] self.file_mapping[f_noext] = (smod, '.o', 0) def clear(self): ''' Clear the dict ''' with self._lock: super(LazyLoader, self).clear() # clear the lazy loader self.loaded_files = set() self.missing_modules = {} self.loaded_modules = {} # if we have been loaded before, lets clear the file mapping since # we obviously want a re-do if hasattr(self, 'opts'): self._refresh_file_mapping() self.initial_load = False def __prep_mod_opts(self, opts): ''' Strip out of the opts any logger instance ''' if '__grains__' not in self.pack: grains = opts.get('grains', {}) if isinstance(grains, ThreadLocalProxy): grains = ThreadLocalProxy.unproxy(grains) self.context_dict['grains'] = grains self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains') if '__pillar__' not in self.pack: pillar = opts.get('pillar', {}) if isinstance(pillar, ThreadLocalProxy): pillar = ThreadLocalProxy.unproxy(pillar) self.context_dict['pillar'] = pillar self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar') mod_opts = {} for key, val in list(opts.items()): if key == 'logger': continue mod_opts[key] = val return mod_opts def _iter_files(self, mod_name): ''' Iterate over all file_mapping files in order of closeness to mod_name ''' # do we have an exact match? if mod_name in self.file_mapping: yield mod_name # do we have a partial match? for k in self.file_mapping: if mod_name in k: yield k # anyone else? Bueller? for k in self.file_mapping: if mod_name not in k: yield k def _reload_submodules(self, mod): submodules = ( getattr(mod, sname) for sname in dir(mod) if isinstance(getattr(mod, sname), mod.__class__) ) # reload only custom "sub"modules for submodule in submodules: # it is a submodule if the name is in a namespace under mod if submodule.__name__.startswith(mod.__name__ + '.'): reload_module(submodule) self._reload_submodules(submodule) def _load_module(self, name): mod = None fpath, suffix = self.file_mapping[name][:2] self.loaded_files.add(name) fpath_dirname = os.path.dirname(fpath) try: sys.path.append(fpath_dirname) if suffix == '.pyx': mod = pyximport.load_module(name, fpath, tempfile.gettempdir()) elif suffix == '.o': top_mod = __import__(fpath, globals(), locals(), []) comps = fpath.split('.') if len(comps) < 2: mod = top_mod else: mod = top_mod for subname in comps[1:]: mod = getattr(mod, subname) elif suffix == '.zip': mod = zipimporter(fpath).load_module(name) else: desc = self.suffix_map[suffix] # if it is a directory, we don't open a file try: mod_namespace = '.'.join(( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name)) except TypeError: mod_namespace = '{0}.{1}.{2}.{3}'.format( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name) if suffix == '': if USE_IMPORTLIB: # pylint: disable=no-member # Package directory, look for __init__ loader_details = [ (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES), (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES), (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), ] file_finder = importlib.machinery.FileFinder( fpath_dirname, *loader_details ) spec = file_finder.find_spec(mod_namespace) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: mod = imp.load_module(mod_namespace, None, fpath, desc) # reload all submodules if necessary if not self.initial_load: self._reload_submodules(mod) else: if USE_IMPORTLIB: # pylint: disable=no-member loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath) spec = importlib.util.spec_from_file_location( mod_namespace, fpath, loader=loader ) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() #mod = importlib.util.module_from_spec(spec) #spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: with salt.utils.files.fopen(fpath, desc[1]) as fn_: mod = imp.load_module(mod_namespace, fn_, fpath, desc) except IOError: raise except ImportError as exc: if 'magic number' in six.text_type(exc): error_msg = 'Failed to import {0} {1}. Bad magic number. If migrating from Python2 to Python3, remove all .pyc files and try again.'.format(self.tag, name) log.warning(error_msg) self.missing_modules[name] = error_msg log.debug( 'Failed to import %s %s:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = exc return False except Exception as error: log.error( 'Failed to import %s %s, this is due most likely to a ' 'syntax error:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False except SystemExit as error: try: fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1] except Exception: pass else: tgt_fn = os.path.join('salt', 'utils', 'process.py') if fn_.endswith(tgt_fn) and '_handle_signals' in caller: # Race conditon, SIGTERM or SIGINT received while loader # was in process of loading a module. Call sys.exit to # ensure that the process is killed. sys.exit(salt.defaults.exitcodes.EX_OK) log.error( 'Failed to import %s %s as the module called exit()\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False finally: sys.path.remove(fpath_dirname) if hasattr(mod, '__opts__'): mod.__opts__.update(self.opts) else: mod.__opts__ = self.opts # pack whatever other globals we were asked to for p_name, p_value in six.iteritems(self.pack): _inject_into_mod(mod, p_name, p_value) module_name = mod.__name__.rsplit('.', 1)[-1] # Call a module's initialization method if it exists module_init = getattr(mod, '__init__', None) if inspect.isfunction(module_init): try: module_init(self.opts) except TypeError as e: log.error(e) except Exception: err_string = '__init__ failed' log.debug( 'Error loading %s.%s: %s', self.tag, module_name, err_string, exc_info=True ) self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False # if virtual modules are enabled, we need to look for the # __virtual__() function inside that module and run it. if self.virtual_enable: virtual_funcs_to_process = ['__virtual__'] + self.virtual_funcs for virtual_func in virtual_funcs_to_process: virtual_ret, module_name, virtual_err, virtual_aliases = \ self._process_virtual(mod, module_name, virtual_func) if virtual_err is not None: log.trace( 'Error loading %s.%s: %s', self.tag, module_name, virtual_err ) # if _process_virtual returned a non-True value then we are # supposed to not process this module if virtual_ret is not True and module_name not in self.missing_modules: # If a module has information about why it could not be loaded, record it self.missing_modules[module_name] = virtual_err self.missing_modules[name] = virtual_err return False else: virtual_aliases = () # If this is a proxy minion then MOST modules cannot work. Therefore, require that # any module that does work with salt-proxy-minion define __proxyenabled__ as a list # containing the names of the proxy types that the module supports. # # Render modules and state modules are OK though if 'proxy' in self.opts: if self.tag in ['grains', 'proxy']: if not hasattr(mod, '__proxyenabled__') or \ (self.opts['proxy']['proxytype'] not in mod.__proxyenabled__ and '*' not in mod.__proxyenabled__): err_string = 'not a proxy_minion enabled module' self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False if getattr(mod, '__load__', False) is not False: log.info( 'The functions from module \'%s\' are being loaded from the ' 'provided __load__ attribute', module_name ) # If we had another module by the same virtual name, we should put any # new functions under the existing dictionary. mod_names = [module_name] + list(virtual_aliases) mod_dict = dict(( (x, self.loaded_modules.get(x, self.mod_dict_class())) for x in mod_names )) for attr in getattr(mod, '__load__', dir(mod)): if attr.startswith('_') and attr != '__call__': # private functions are skipped, # except __call__ which is default entrance # for multi-function batch-like state syntax continue func = getattr(mod, attr) if not inspect.isfunction(func) and not isinstance(func, functools.partial): # Not a function!? Skip it!!! continue # Let's get the function name. # If the module has the __func_alias__ attribute, it must be a # dictionary mapping in the form of(key -> value): # <real-func-name> -> <desired-func-name> # # It default's of course to the found callable attribute name # if no alias is defined. funcname = getattr(mod, '__func_alias__', {}).get(attr, attr) for tgt_mod in mod_names: try: full_funcname = '.'.join((tgt_mod, funcname)) except TypeError: full_funcname = '{0}.{1}'.format(tgt_mod, funcname) # Save many references for lookups # Careful not to overwrite existing (higher priority) functions if full_funcname not in self._dict: self._dict[full_funcname] = func if funcname not in mod_dict[tgt_mod]: setattr(mod_dict[tgt_mod], funcname, func) mod_dict[tgt_mod][funcname] = func self._apply_outputter(func, mod) # enforce depends try: Depends.enforce_dependencies(self._dict, self.tag) except RuntimeError as exc: log.info( 'Depends.enforce_dependencies() failed for the following ' 'reason: %s', exc ) for tgt_mod in mod_names: self.loaded_modules[tgt_mod] = mod_dict[tgt_mod] return True def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise KeyError('The key \'{0}\' should contain a \'.\''.format(key)) mod_name, _ = key.split('.', 1) with self._lock: # It is possible that the key is in the dictionary after # acquiring the lock due to another thread loading it. if mod_name in self.missing_modules or key in self._dict: return True # if the modulename isn't in the whitelist, don't bother if self.whitelist and mod_name not in self.whitelist: log.error( 'Failed to load function %s because its module (%s) is ' 'not in the whitelist: %s', key, mod_name, self.whitelist ) raise KeyError(key) def _inner_load(mod_name): for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and key in self._dict: return True return False # try to load the module ret = None reloaded = False # re-scan up to once, IOErrors or a failed load cause re-scans of the # filesystem while True: try: ret = _inner_load(mod_name) if not reloaded and ret is not True: self._refresh_file_mapping() reloaded = True continue break except IOError: if not reloaded: self._refresh_file_mapping() reloaded = True continue return ret def reload_modules(self): with self._lock: self.loaded_files = set() self._load_all() def _apply_outputter(self, func, mod): ''' Apply the __outputter__ variable to the functions ''' if hasattr(mod, '__outputter__'): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__] def _process_virtual(self, mod, module_name, virtual_func='__virtual__'): ''' Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1] ''' # The __virtual__ function will return either a True or False value. # If it returns a True value it can also set a module level attribute # named __virtualname__ with the name that the module should be # referred to as. # # This allows us to have things like the pkg module working on all # platforms under the name 'pkg'. It also allows for modules like # augeas_cfg to be referred to as 'augeas', which would otherwise have # namespace collisions. And finally it allows modules to return False # if they are not intended to run on the given platform or are missing # dependencies. virtual_aliases = getattr(mod, '__virtual_aliases__', tuple()) try: error_reason = None if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__): try: start = time.time() virtual = getattr(mod, virtual_func)() if isinstance(virtual, tuple): error_reason = virtual[1] virtual = virtual[0] if self.opts.get('virtual_timer', False): end = time.time() - start msg = 'Virtual function took {0} seconds for {1}'.format( end, module_name) log.warning(msg) except Exception as exc: error_reason = ( 'Exception raised when processing __virtual__ function' ' for {0}. Module will not be loaded: {1}'.format( mod.__name__, exc)) log.error(error_reason, exc_info_on_loglevel=logging.DEBUG) virtual = None # Get the module's virtual name virtualname = getattr(mod, '__virtualname__', virtual) if not virtual: # if __virtual__() evaluates to False then the module # wasn't meant for this platform or it's not supposed to # load for some other reason. # Some modules might accidentally return None and are # improperly loaded if virtual is None: log.warning( '%s.__virtual__() is wrongly returning `None`. ' 'It should either return `True`, `False` or a new ' 'name. If you\'re the developer of the module ' '\'%s\', please fix this.', mod.__name__, module_name ) return (False, module_name, error_reason, virtual_aliases) # At this point, __virtual__ did not return a # boolean value, let's check for deprecated usage # or module renames if virtual is not True and module_name != virtual: # The module is renaming itself. Updating the module name # with the new name log.trace('Loaded %s as virtual %s', module_name, virtual) if virtualname != virtual: # The __virtualname__ attribute does not match what's # being returned by the __virtual__() function. This # should be considered an error. log.error( 'The module \'%s\' is showing some bad usage. Its ' '__virtualname__ attribute is set to \'%s\' yet the ' '__virtual__() function is returning \'%s\'. These ' 'values should match!', mod.__name__, virtualname, virtual ) module_name = virtualname # If the __virtual__ function returns True and __virtualname__ # is set then use it elif virtual is True and virtualname != module_name: if virtualname is not True: module_name = virtualname except KeyError: # Key errors come out of the virtual function when passing # in incomplete grains sets, these can be safely ignored # and logged to debug, still, it includes the traceback to # help debugging. log.debug('KeyError when loading %s', module_name, exc_info=True) except Exception: # If the module throws an exception during __virtual__() # then log the information and continue to the next. log.error( 'Failed to read the virtual function for %s: %s', self.tag, module_name, exc_info=True ) return (False, module_name, error_reason, virtual_aliases) return (True, module_name, None, virtual_aliases)
saltstack/salt
salt/loader.py
LazyLoader._apply_outputter
python
def _apply_outputter(self, func, mod): ''' Apply the __outputter__ variable to the functions ''' if hasattr(mod, '__outputter__'): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__]
Apply the __outputter__ variable to the functions
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L1921-L1928
null
class LazyLoader(salt.utils.lazy.LazyDict): ''' A pseduo-dictionary which has a set of keys which are the name of the module and function, delimited by a dot. When the value of the key is accessed, the function is then loaded from disk and into memory. .. note:: Iterating over keys will cause all modules to be loaded. :param list module_dirs: A list of directories on disk to search for modules :param dict opts: The salt options dictionary. :param str tag: The tag for the type of module to load :param func mod_type_check: A function which can be used to verify files :param dict pack: A dictionary of function to be packed into modules as they are loaded :param list whitelist: A list of modules to whitelist :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules. :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality. If not true, the module will not load. :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values are function references themselves which are loaded on-demand. # TODO: - move modules_max_memory into here - singletons (per tag) ''' mod_dict_class = salt.utils.odict.OrderedDict def __init__(self, module_dirs, opts=None, tag='module', loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, proxy=None, virtual_funcs=None, ): # pylint: disable=W0231 ''' In pack, if any of the values are None they will be replaced with an empty context-specific dict ''' self.inject_globals = {} self.pack = {} if pack is None else pack if opts is None: opts = {} threadsafety = not opts.get('multiprocessing') self.context_dict = salt.utils.context.ContextDict(threadsafe=threadsafety) self.opts = self.__prep_mod_opts(opts) self.module_dirs = module_dirs self.tag = tag self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME self.mod_type_check = mod_type_check or _mod_type if '__context__' not in self.pack: self.pack['__context__'] = None for k, v in six.iteritems(self.pack): if v is None: # if the value of a pack is None, lets make an empty dict value = self.context_dict.get(k, {}) if isinstance(value, ThreadLocalProxy): value = ThreadLocalProxy.unproxy(value) self.context_dict[k] = value self.pack[k] = salt.utils.context.NamespacedDictWrapper(self.context_dict, k) self.whitelist = whitelist self.virtual_enable = virtual_enable self.initial_load = True # names of modules that we don't have (errors, __virtual__, etc.) self.missing_modules = {} # mapping of name -> error self.loaded_modules = {} # mapping of module_name -> dict_of_functions self.loaded_files = set() # TODO: just remove them from file_mapping? self.static_modules = static_modules if static_modules else [] if virtual_funcs is None: virtual_funcs = [] self.virtual_funcs = virtual_funcs self.disabled = set( self.opts.get( 'disable_{0}{1}'.format( self.tag, '' if self.tag[-1] == 's' else 's' ), [] ) ) # A map of suffix to description for imp self.suffix_map = {} # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [''] for (suffix, mode, kind) in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) self._lock = threading.RLock() self._refresh_file_mapping() super(LazyLoader, self).__init__() # late init the lazy loader # create all of the import namespaces _generate_module('{0}.int'.format(self.loaded_base_name)) _generate_module('{0}.int.{1}'.format(self.loaded_base_name, tag)) _generate_module('{0}.ext'.format(self.loaded_base_name)) _generate_module('{0}.ext.{1}'.format(self.loaded_base_name, tag)) def __getitem__(self, item): ''' Override the __getitem__ in order to decorate the returned function if we need to last-minute inject globals ''' func = super(LazyLoader, self).__getitem__(item) if self.inject_globals: return global_injector_decorator(self.inject_globals)(func) else: return func def __getattr__(self, mod_name): ''' Allow for "direct" attribute access-- this allows jinja templates to access things like `salt.test.ping()` ''' if mod_name in ('__getstate__', '__setstate__'): return object.__getattribute__(self, mod_name) # if we have an attribute named that, lets return it. try: return object.__getattr__(self, mod_name) # pylint: disable=no-member except AttributeError: pass # otherwise we assume its jinja template access if mod_name not in self.loaded_modules and not self.loaded: for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and mod_name in self.loaded_modules: break if mod_name in self.loaded_modules: return self.loaded_modules[mod_name] else: raise AttributeError(mod_name) def missing_fun_string(self, function_name): ''' Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ''' mod_name = function_name.split('.')[0] if mod_name in self.loaded_modules: return '\'{0}\' is not available.'.format(function_name) else: try: reason = self.missing_modules[mod_name] except KeyError: return '\'{0}\' is not available.'.format(function_name) else: if reason is not None: return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason) else: return '\'{0}\' __virtual__ returned False'.format(mod_name) def _refresh_file_mapping(self): ''' refresh the mapping of the FS on disk ''' # map of suffix to description for imp if self.opts.get('cython_enable', True) is True: try: global pyximport pyximport = __import__('pyximport') # pylint: disable=import-error pyximport.install() # add to suffix_map so file_mapping will pick it up self.suffix_map['.pyx'] = tuple() except ImportError: log.info('Cython is enabled in the options but not present ' 'in the system path. Skipping Cython modules.') # Allow for zipimport of modules if self.opts.get('enable_zip_modules', True) is True: self.suffix_map['.zip'] = tuple() # allow for module dirs if USE_IMPORTLIB: self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY) else: self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY) # create mapping of filename (without suffix) to (path, suffix) # The files are added in order of priority, so order *must* be retained. self.file_mapping = salt.utils.odict.OrderedDict() opt_match = [] def _replace_pre_ext(obj): ''' Hack so we can get the optimization level that we replaced (if any) out of the re.sub call below. We use a list here because it is a persistent data structure that we will be able to access after re.sub is called. ''' opt_match.append(obj) return '' for mod_dir in self.module_dirs: try: # Make sure we have a sorted listdir in order to have # expectable override results files = sorted( x for x in os.listdir(mod_dir) if x != '__pycache__' ) except OSError: continue # Next mod_dir if six.PY3: try: pycache_files = [ os.path.join('__pycache__', x) for x in sorted(os.listdir(os.path.join(mod_dir, '__pycache__'))) ] except OSError: pass else: files.extend(pycache_files) for filename in files: try: dirname, basename = os.path.split(filename) if basename.startswith('_'): # skip private modules # log messages omitted for obviousness continue # Next filename f_noext, ext = os.path.splitext(basename) if six.PY3: f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext) try: opt_level = int( opt_match.pop().group(1).rsplit('-', 1)[-1] ) except (AttributeError, IndexError, ValueError): # No regex match or no optimization level matched opt_level = 0 try: opt_index = self.opts['optimization_order'].index(opt_level) except KeyError: log.trace( 'Disallowed optimization level %d for module ' 'name \'%s\', skipping. Add %d to the ' '\'optimization_order\' config option if you ' 'do not want to ignore this optimization ' 'level.', opt_level, f_noext, opt_level ) continue else: # Optimization level not reflected in filename on PY2 opt_index = 0 # make sure it is a suffix we support if ext not in self.suffix_map: continue # Next filename if f_noext in self.disabled: log.trace( 'Skipping %s, it is disabled by configuration', filename ) continue # Next filename fpath = os.path.join(mod_dir, filename) # if its a directory, lets allow us to load that if ext == '': # is there something __init__? subfiles = os.listdir(fpath) for suffix in self.suffix_order: if '' == suffix: continue # Next suffix (__init__ must have a suffix) init_file = '__init__{0}'.format(suffix) if init_file in subfiles: break else: continue # Next filename try: curr_ext = self.file_mapping[f_noext][1] curr_opt_index = self.file_mapping[f_noext][2] except KeyError: pass else: if '' in (curr_ext, ext) and curr_ext != ext: log.error( 'Module/package collision: \'%s\' and \'%s\'', fpath, self.file_mapping[f_noext][0] ) if six.PY3 and ext == '.pyc' and curr_ext == '.pyc': # Check the optimization level if opt_index >= curr_opt_index: # Module name match, but a higher-priority # optimization level was already matched, skipping. continue elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext): # Match found but a higher-priorty match already # exists, so skip this. continue if six.PY3 and not dirname and ext == '.pyc': # On Python 3, we should only load .pyc files from the # __pycache__ subdirectory (i.e. when dirname is not an # empty string). continue # Made it this far - add it self.file_mapping[f_noext] = (fpath, ext, opt_index) except OSError: continue for smod in self.static_modules: f_noext = smod.split('.')[-1] self.file_mapping[f_noext] = (smod, '.o', 0) def clear(self): ''' Clear the dict ''' with self._lock: super(LazyLoader, self).clear() # clear the lazy loader self.loaded_files = set() self.missing_modules = {} self.loaded_modules = {} # if we have been loaded before, lets clear the file mapping since # we obviously want a re-do if hasattr(self, 'opts'): self._refresh_file_mapping() self.initial_load = False def __prep_mod_opts(self, opts): ''' Strip out of the opts any logger instance ''' if '__grains__' not in self.pack: grains = opts.get('grains', {}) if isinstance(grains, ThreadLocalProxy): grains = ThreadLocalProxy.unproxy(grains) self.context_dict['grains'] = grains self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains') if '__pillar__' not in self.pack: pillar = opts.get('pillar', {}) if isinstance(pillar, ThreadLocalProxy): pillar = ThreadLocalProxy.unproxy(pillar) self.context_dict['pillar'] = pillar self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar') mod_opts = {} for key, val in list(opts.items()): if key == 'logger': continue mod_opts[key] = val return mod_opts def _iter_files(self, mod_name): ''' Iterate over all file_mapping files in order of closeness to mod_name ''' # do we have an exact match? if mod_name in self.file_mapping: yield mod_name # do we have a partial match? for k in self.file_mapping: if mod_name in k: yield k # anyone else? Bueller? for k in self.file_mapping: if mod_name not in k: yield k def _reload_submodules(self, mod): submodules = ( getattr(mod, sname) for sname in dir(mod) if isinstance(getattr(mod, sname), mod.__class__) ) # reload only custom "sub"modules for submodule in submodules: # it is a submodule if the name is in a namespace under mod if submodule.__name__.startswith(mod.__name__ + '.'): reload_module(submodule) self._reload_submodules(submodule) def _load_module(self, name): mod = None fpath, suffix = self.file_mapping[name][:2] self.loaded_files.add(name) fpath_dirname = os.path.dirname(fpath) try: sys.path.append(fpath_dirname) if suffix == '.pyx': mod = pyximport.load_module(name, fpath, tempfile.gettempdir()) elif suffix == '.o': top_mod = __import__(fpath, globals(), locals(), []) comps = fpath.split('.') if len(comps) < 2: mod = top_mod else: mod = top_mod for subname in comps[1:]: mod = getattr(mod, subname) elif suffix == '.zip': mod = zipimporter(fpath).load_module(name) else: desc = self.suffix_map[suffix] # if it is a directory, we don't open a file try: mod_namespace = '.'.join(( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name)) except TypeError: mod_namespace = '{0}.{1}.{2}.{3}'.format( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name) if suffix == '': if USE_IMPORTLIB: # pylint: disable=no-member # Package directory, look for __init__ loader_details = [ (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES), (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES), (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), ] file_finder = importlib.machinery.FileFinder( fpath_dirname, *loader_details ) spec = file_finder.find_spec(mod_namespace) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: mod = imp.load_module(mod_namespace, None, fpath, desc) # reload all submodules if necessary if not self.initial_load: self._reload_submodules(mod) else: if USE_IMPORTLIB: # pylint: disable=no-member loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath) spec = importlib.util.spec_from_file_location( mod_namespace, fpath, loader=loader ) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() #mod = importlib.util.module_from_spec(spec) #spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: with salt.utils.files.fopen(fpath, desc[1]) as fn_: mod = imp.load_module(mod_namespace, fn_, fpath, desc) except IOError: raise except ImportError as exc: if 'magic number' in six.text_type(exc): error_msg = 'Failed to import {0} {1}. Bad magic number. If migrating from Python2 to Python3, remove all .pyc files and try again.'.format(self.tag, name) log.warning(error_msg) self.missing_modules[name] = error_msg log.debug( 'Failed to import %s %s:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = exc return False except Exception as error: log.error( 'Failed to import %s %s, this is due most likely to a ' 'syntax error:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False except SystemExit as error: try: fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1] except Exception: pass else: tgt_fn = os.path.join('salt', 'utils', 'process.py') if fn_.endswith(tgt_fn) and '_handle_signals' in caller: # Race conditon, SIGTERM or SIGINT received while loader # was in process of loading a module. Call sys.exit to # ensure that the process is killed. sys.exit(salt.defaults.exitcodes.EX_OK) log.error( 'Failed to import %s %s as the module called exit()\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False finally: sys.path.remove(fpath_dirname) if hasattr(mod, '__opts__'): mod.__opts__.update(self.opts) else: mod.__opts__ = self.opts # pack whatever other globals we were asked to for p_name, p_value in six.iteritems(self.pack): _inject_into_mod(mod, p_name, p_value) module_name = mod.__name__.rsplit('.', 1)[-1] # Call a module's initialization method if it exists module_init = getattr(mod, '__init__', None) if inspect.isfunction(module_init): try: module_init(self.opts) except TypeError as e: log.error(e) except Exception: err_string = '__init__ failed' log.debug( 'Error loading %s.%s: %s', self.tag, module_name, err_string, exc_info=True ) self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False # if virtual modules are enabled, we need to look for the # __virtual__() function inside that module and run it. if self.virtual_enable: virtual_funcs_to_process = ['__virtual__'] + self.virtual_funcs for virtual_func in virtual_funcs_to_process: virtual_ret, module_name, virtual_err, virtual_aliases = \ self._process_virtual(mod, module_name, virtual_func) if virtual_err is not None: log.trace( 'Error loading %s.%s: %s', self.tag, module_name, virtual_err ) # if _process_virtual returned a non-True value then we are # supposed to not process this module if virtual_ret is not True and module_name not in self.missing_modules: # If a module has information about why it could not be loaded, record it self.missing_modules[module_name] = virtual_err self.missing_modules[name] = virtual_err return False else: virtual_aliases = () # If this is a proxy minion then MOST modules cannot work. Therefore, require that # any module that does work with salt-proxy-minion define __proxyenabled__ as a list # containing the names of the proxy types that the module supports. # # Render modules and state modules are OK though if 'proxy' in self.opts: if self.tag in ['grains', 'proxy']: if not hasattr(mod, '__proxyenabled__') or \ (self.opts['proxy']['proxytype'] not in mod.__proxyenabled__ and '*' not in mod.__proxyenabled__): err_string = 'not a proxy_minion enabled module' self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False if getattr(mod, '__load__', False) is not False: log.info( 'The functions from module \'%s\' are being loaded from the ' 'provided __load__ attribute', module_name ) # If we had another module by the same virtual name, we should put any # new functions under the existing dictionary. mod_names = [module_name] + list(virtual_aliases) mod_dict = dict(( (x, self.loaded_modules.get(x, self.mod_dict_class())) for x in mod_names )) for attr in getattr(mod, '__load__', dir(mod)): if attr.startswith('_') and attr != '__call__': # private functions are skipped, # except __call__ which is default entrance # for multi-function batch-like state syntax continue func = getattr(mod, attr) if not inspect.isfunction(func) and not isinstance(func, functools.partial): # Not a function!? Skip it!!! continue # Let's get the function name. # If the module has the __func_alias__ attribute, it must be a # dictionary mapping in the form of(key -> value): # <real-func-name> -> <desired-func-name> # # It default's of course to the found callable attribute name # if no alias is defined. funcname = getattr(mod, '__func_alias__', {}).get(attr, attr) for tgt_mod in mod_names: try: full_funcname = '.'.join((tgt_mod, funcname)) except TypeError: full_funcname = '{0}.{1}'.format(tgt_mod, funcname) # Save many references for lookups # Careful not to overwrite existing (higher priority) functions if full_funcname not in self._dict: self._dict[full_funcname] = func if funcname not in mod_dict[tgt_mod]: setattr(mod_dict[tgt_mod], funcname, func) mod_dict[tgt_mod][funcname] = func self._apply_outputter(func, mod) # enforce depends try: Depends.enforce_dependencies(self._dict, self.tag) except RuntimeError as exc: log.info( 'Depends.enforce_dependencies() failed for the following ' 'reason: %s', exc ) for tgt_mod in mod_names: self.loaded_modules[tgt_mod] = mod_dict[tgt_mod] return True def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise KeyError('The key \'{0}\' should contain a \'.\''.format(key)) mod_name, _ = key.split('.', 1) with self._lock: # It is possible that the key is in the dictionary after # acquiring the lock due to another thread loading it. if mod_name in self.missing_modules or key in self._dict: return True # if the modulename isn't in the whitelist, don't bother if self.whitelist and mod_name not in self.whitelist: log.error( 'Failed to load function %s because its module (%s) is ' 'not in the whitelist: %s', key, mod_name, self.whitelist ) raise KeyError(key) def _inner_load(mod_name): for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and key in self._dict: return True return False # try to load the module ret = None reloaded = False # re-scan up to once, IOErrors or a failed load cause re-scans of the # filesystem while True: try: ret = _inner_load(mod_name) if not reloaded and ret is not True: self._refresh_file_mapping() reloaded = True continue break except IOError: if not reloaded: self._refresh_file_mapping() reloaded = True continue return ret def _load_all(self): ''' Load all of them ''' with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True def reload_modules(self): with self._lock: self.loaded_files = set() self._load_all() def _process_virtual(self, mod, module_name, virtual_func='__virtual__'): ''' Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1] ''' # The __virtual__ function will return either a True or False value. # If it returns a True value it can also set a module level attribute # named __virtualname__ with the name that the module should be # referred to as. # # This allows us to have things like the pkg module working on all # platforms under the name 'pkg'. It also allows for modules like # augeas_cfg to be referred to as 'augeas', which would otherwise have # namespace collisions. And finally it allows modules to return False # if they are not intended to run on the given platform or are missing # dependencies. virtual_aliases = getattr(mod, '__virtual_aliases__', tuple()) try: error_reason = None if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__): try: start = time.time() virtual = getattr(mod, virtual_func)() if isinstance(virtual, tuple): error_reason = virtual[1] virtual = virtual[0] if self.opts.get('virtual_timer', False): end = time.time() - start msg = 'Virtual function took {0} seconds for {1}'.format( end, module_name) log.warning(msg) except Exception as exc: error_reason = ( 'Exception raised when processing __virtual__ function' ' for {0}. Module will not be loaded: {1}'.format( mod.__name__, exc)) log.error(error_reason, exc_info_on_loglevel=logging.DEBUG) virtual = None # Get the module's virtual name virtualname = getattr(mod, '__virtualname__', virtual) if not virtual: # if __virtual__() evaluates to False then the module # wasn't meant for this platform or it's not supposed to # load for some other reason. # Some modules might accidentally return None and are # improperly loaded if virtual is None: log.warning( '%s.__virtual__() is wrongly returning `None`. ' 'It should either return `True`, `False` or a new ' 'name. If you\'re the developer of the module ' '\'%s\', please fix this.', mod.__name__, module_name ) return (False, module_name, error_reason, virtual_aliases) # At this point, __virtual__ did not return a # boolean value, let's check for deprecated usage # or module renames if virtual is not True and module_name != virtual: # The module is renaming itself. Updating the module name # with the new name log.trace('Loaded %s as virtual %s', module_name, virtual) if virtualname != virtual: # The __virtualname__ attribute does not match what's # being returned by the __virtual__() function. This # should be considered an error. log.error( 'The module \'%s\' is showing some bad usage. Its ' '__virtualname__ attribute is set to \'%s\' yet the ' '__virtual__() function is returning \'%s\'. These ' 'values should match!', mod.__name__, virtualname, virtual ) module_name = virtualname # If the __virtual__ function returns True and __virtualname__ # is set then use it elif virtual is True and virtualname != module_name: if virtualname is not True: module_name = virtualname except KeyError: # Key errors come out of the virtual function when passing # in incomplete grains sets, these can be safely ignored # and logged to debug, still, it includes the traceback to # help debugging. log.debug('KeyError when loading %s', module_name, exc_info=True) except Exception: # If the module throws an exception during __virtual__() # then log the information and continue to the next. log.error( 'Failed to read the virtual function for %s: %s', self.tag, module_name, exc_info=True ) return (False, module_name, error_reason, virtual_aliases) return (True, module_name, None, virtual_aliases)
saltstack/salt
salt/loader.py
LazyLoader._process_virtual
python
def _process_virtual(self, mod, module_name, virtual_func='__virtual__'): ''' Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1] ''' # The __virtual__ function will return either a True or False value. # If it returns a True value it can also set a module level attribute # named __virtualname__ with the name that the module should be # referred to as. # # This allows us to have things like the pkg module working on all # platforms under the name 'pkg'. It also allows for modules like # augeas_cfg to be referred to as 'augeas', which would otherwise have # namespace collisions. And finally it allows modules to return False # if they are not intended to run on the given platform or are missing # dependencies. virtual_aliases = getattr(mod, '__virtual_aliases__', tuple()) try: error_reason = None if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__): try: start = time.time() virtual = getattr(mod, virtual_func)() if isinstance(virtual, tuple): error_reason = virtual[1] virtual = virtual[0] if self.opts.get('virtual_timer', False): end = time.time() - start msg = 'Virtual function took {0} seconds for {1}'.format( end, module_name) log.warning(msg) except Exception as exc: error_reason = ( 'Exception raised when processing __virtual__ function' ' for {0}. Module will not be loaded: {1}'.format( mod.__name__, exc)) log.error(error_reason, exc_info_on_loglevel=logging.DEBUG) virtual = None # Get the module's virtual name virtualname = getattr(mod, '__virtualname__', virtual) if not virtual: # if __virtual__() evaluates to False then the module # wasn't meant for this platform or it's not supposed to # load for some other reason. # Some modules might accidentally return None and are # improperly loaded if virtual is None: log.warning( '%s.__virtual__() is wrongly returning `None`. ' 'It should either return `True`, `False` or a new ' 'name. If you\'re the developer of the module ' '\'%s\', please fix this.', mod.__name__, module_name ) return (False, module_name, error_reason, virtual_aliases) # At this point, __virtual__ did not return a # boolean value, let's check for deprecated usage # or module renames if virtual is not True and module_name != virtual: # The module is renaming itself. Updating the module name # with the new name log.trace('Loaded %s as virtual %s', module_name, virtual) if virtualname != virtual: # The __virtualname__ attribute does not match what's # being returned by the __virtual__() function. This # should be considered an error. log.error( 'The module \'%s\' is showing some bad usage. Its ' '__virtualname__ attribute is set to \'%s\' yet the ' '__virtual__() function is returning \'%s\'. These ' 'values should match!', mod.__name__, virtualname, virtual ) module_name = virtualname # If the __virtual__ function returns True and __virtualname__ # is set then use it elif virtual is True and virtualname != module_name: if virtualname is not True: module_name = virtualname except KeyError: # Key errors come out of the virtual function when passing # in incomplete grains sets, these can be safely ignored # and logged to debug, still, it includes the traceback to # help debugging. log.debug('KeyError when loading %s', module_name, exc_info=True) except Exception: # If the module throws an exception during __virtual__() # then log the information and continue to the next. log.error( 'Failed to read the virtual function for %s: %s', self.tag, module_name, exc_info=True ) return (False, module_name, error_reason, virtual_aliases) return (True, module_name, None, virtual_aliases)
Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1]
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L1930-L2041
null
class LazyLoader(salt.utils.lazy.LazyDict): ''' A pseduo-dictionary which has a set of keys which are the name of the module and function, delimited by a dot. When the value of the key is accessed, the function is then loaded from disk and into memory. .. note:: Iterating over keys will cause all modules to be loaded. :param list module_dirs: A list of directories on disk to search for modules :param dict opts: The salt options dictionary. :param str tag: The tag for the type of module to load :param func mod_type_check: A function which can be used to verify files :param dict pack: A dictionary of function to be packed into modules as they are loaded :param list whitelist: A list of modules to whitelist :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules. :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality. If not true, the module will not load. :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values are function references themselves which are loaded on-demand. # TODO: - move modules_max_memory into here - singletons (per tag) ''' mod_dict_class = salt.utils.odict.OrderedDict def __init__(self, module_dirs, opts=None, tag='module', loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, proxy=None, virtual_funcs=None, ): # pylint: disable=W0231 ''' In pack, if any of the values are None they will be replaced with an empty context-specific dict ''' self.inject_globals = {} self.pack = {} if pack is None else pack if opts is None: opts = {} threadsafety = not opts.get('multiprocessing') self.context_dict = salt.utils.context.ContextDict(threadsafe=threadsafety) self.opts = self.__prep_mod_opts(opts) self.module_dirs = module_dirs self.tag = tag self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME self.mod_type_check = mod_type_check or _mod_type if '__context__' not in self.pack: self.pack['__context__'] = None for k, v in six.iteritems(self.pack): if v is None: # if the value of a pack is None, lets make an empty dict value = self.context_dict.get(k, {}) if isinstance(value, ThreadLocalProxy): value = ThreadLocalProxy.unproxy(value) self.context_dict[k] = value self.pack[k] = salt.utils.context.NamespacedDictWrapper(self.context_dict, k) self.whitelist = whitelist self.virtual_enable = virtual_enable self.initial_load = True # names of modules that we don't have (errors, __virtual__, etc.) self.missing_modules = {} # mapping of name -> error self.loaded_modules = {} # mapping of module_name -> dict_of_functions self.loaded_files = set() # TODO: just remove them from file_mapping? self.static_modules = static_modules if static_modules else [] if virtual_funcs is None: virtual_funcs = [] self.virtual_funcs = virtual_funcs self.disabled = set( self.opts.get( 'disable_{0}{1}'.format( self.tag, '' if self.tag[-1] == 's' else 's' ), [] ) ) # A map of suffix to description for imp self.suffix_map = {} # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [''] for (suffix, mode, kind) in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) self._lock = threading.RLock() self._refresh_file_mapping() super(LazyLoader, self).__init__() # late init the lazy loader # create all of the import namespaces _generate_module('{0}.int'.format(self.loaded_base_name)) _generate_module('{0}.int.{1}'.format(self.loaded_base_name, tag)) _generate_module('{0}.ext'.format(self.loaded_base_name)) _generate_module('{0}.ext.{1}'.format(self.loaded_base_name, tag)) def __getitem__(self, item): ''' Override the __getitem__ in order to decorate the returned function if we need to last-minute inject globals ''' func = super(LazyLoader, self).__getitem__(item) if self.inject_globals: return global_injector_decorator(self.inject_globals)(func) else: return func def __getattr__(self, mod_name): ''' Allow for "direct" attribute access-- this allows jinja templates to access things like `salt.test.ping()` ''' if mod_name in ('__getstate__', '__setstate__'): return object.__getattribute__(self, mod_name) # if we have an attribute named that, lets return it. try: return object.__getattr__(self, mod_name) # pylint: disable=no-member except AttributeError: pass # otherwise we assume its jinja template access if mod_name not in self.loaded_modules and not self.loaded: for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and mod_name in self.loaded_modules: break if mod_name in self.loaded_modules: return self.loaded_modules[mod_name] else: raise AttributeError(mod_name) def missing_fun_string(self, function_name): ''' Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ''' mod_name = function_name.split('.')[0] if mod_name in self.loaded_modules: return '\'{0}\' is not available.'.format(function_name) else: try: reason = self.missing_modules[mod_name] except KeyError: return '\'{0}\' is not available.'.format(function_name) else: if reason is not None: return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason) else: return '\'{0}\' __virtual__ returned False'.format(mod_name) def _refresh_file_mapping(self): ''' refresh the mapping of the FS on disk ''' # map of suffix to description for imp if self.opts.get('cython_enable', True) is True: try: global pyximport pyximport = __import__('pyximport') # pylint: disable=import-error pyximport.install() # add to suffix_map so file_mapping will pick it up self.suffix_map['.pyx'] = tuple() except ImportError: log.info('Cython is enabled in the options but not present ' 'in the system path. Skipping Cython modules.') # Allow for zipimport of modules if self.opts.get('enable_zip_modules', True) is True: self.suffix_map['.zip'] = tuple() # allow for module dirs if USE_IMPORTLIB: self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY) else: self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY) # create mapping of filename (without suffix) to (path, suffix) # The files are added in order of priority, so order *must* be retained. self.file_mapping = salt.utils.odict.OrderedDict() opt_match = [] def _replace_pre_ext(obj): ''' Hack so we can get the optimization level that we replaced (if any) out of the re.sub call below. We use a list here because it is a persistent data structure that we will be able to access after re.sub is called. ''' opt_match.append(obj) return '' for mod_dir in self.module_dirs: try: # Make sure we have a sorted listdir in order to have # expectable override results files = sorted( x for x in os.listdir(mod_dir) if x != '__pycache__' ) except OSError: continue # Next mod_dir if six.PY3: try: pycache_files = [ os.path.join('__pycache__', x) for x in sorted(os.listdir(os.path.join(mod_dir, '__pycache__'))) ] except OSError: pass else: files.extend(pycache_files) for filename in files: try: dirname, basename = os.path.split(filename) if basename.startswith('_'): # skip private modules # log messages omitted for obviousness continue # Next filename f_noext, ext = os.path.splitext(basename) if six.PY3: f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext) try: opt_level = int( opt_match.pop().group(1).rsplit('-', 1)[-1] ) except (AttributeError, IndexError, ValueError): # No regex match or no optimization level matched opt_level = 0 try: opt_index = self.opts['optimization_order'].index(opt_level) except KeyError: log.trace( 'Disallowed optimization level %d for module ' 'name \'%s\', skipping. Add %d to the ' '\'optimization_order\' config option if you ' 'do not want to ignore this optimization ' 'level.', opt_level, f_noext, opt_level ) continue else: # Optimization level not reflected in filename on PY2 opt_index = 0 # make sure it is a suffix we support if ext not in self.suffix_map: continue # Next filename if f_noext in self.disabled: log.trace( 'Skipping %s, it is disabled by configuration', filename ) continue # Next filename fpath = os.path.join(mod_dir, filename) # if its a directory, lets allow us to load that if ext == '': # is there something __init__? subfiles = os.listdir(fpath) for suffix in self.suffix_order: if '' == suffix: continue # Next suffix (__init__ must have a suffix) init_file = '__init__{0}'.format(suffix) if init_file in subfiles: break else: continue # Next filename try: curr_ext = self.file_mapping[f_noext][1] curr_opt_index = self.file_mapping[f_noext][2] except KeyError: pass else: if '' in (curr_ext, ext) and curr_ext != ext: log.error( 'Module/package collision: \'%s\' and \'%s\'', fpath, self.file_mapping[f_noext][0] ) if six.PY3 and ext == '.pyc' and curr_ext == '.pyc': # Check the optimization level if opt_index >= curr_opt_index: # Module name match, but a higher-priority # optimization level was already matched, skipping. continue elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext): # Match found but a higher-priorty match already # exists, so skip this. continue if six.PY3 and not dirname and ext == '.pyc': # On Python 3, we should only load .pyc files from the # __pycache__ subdirectory (i.e. when dirname is not an # empty string). continue # Made it this far - add it self.file_mapping[f_noext] = (fpath, ext, opt_index) except OSError: continue for smod in self.static_modules: f_noext = smod.split('.')[-1] self.file_mapping[f_noext] = (smod, '.o', 0) def clear(self): ''' Clear the dict ''' with self._lock: super(LazyLoader, self).clear() # clear the lazy loader self.loaded_files = set() self.missing_modules = {} self.loaded_modules = {} # if we have been loaded before, lets clear the file mapping since # we obviously want a re-do if hasattr(self, 'opts'): self._refresh_file_mapping() self.initial_load = False def __prep_mod_opts(self, opts): ''' Strip out of the opts any logger instance ''' if '__grains__' not in self.pack: grains = opts.get('grains', {}) if isinstance(grains, ThreadLocalProxy): grains = ThreadLocalProxy.unproxy(grains) self.context_dict['grains'] = grains self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains') if '__pillar__' not in self.pack: pillar = opts.get('pillar', {}) if isinstance(pillar, ThreadLocalProxy): pillar = ThreadLocalProxy.unproxy(pillar) self.context_dict['pillar'] = pillar self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar') mod_opts = {} for key, val in list(opts.items()): if key == 'logger': continue mod_opts[key] = val return mod_opts def _iter_files(self, mod_name): ''' Iterate over all file_mapping files in order of closeness to mod_name ''' # do we have an exact match? if mod_name in self.file_mapping: yield mod_name # do we have a partial match? for k in self.file_mapping: if mod_name in k: yield k # anyone else? Bueller? for k in self.file_mapping: if mod_name not in k: yield k def _reload_submodules(self, mod): submodules = ( getattr(mod, sname) for sname in dir(mod) if isinstance(getattr(mod, sname), mod.__class__) ) # reload only custom "sub"modules for submodule in submodules: # it is a submodule if the name is in a namespace under mod if submodule.__name__.startswith(mod.__name__ + '.'): reload_module(submodule) self._reload_submodules(submodule) def _load_module(self, name): mod = None fpath, suffix = self.file_mapping[name][:2] self.loaded_files.add(name) fpath_dirname = os.path.dirname(fpath) try: sys.path.append(fpath_dirname) if suffix == '.pyx': mod = pyximport.load_module(name, fpath, tempfile.gettempdir()) elif suffix == '.o': top_mod = __import__(fpath, globals(), locals(), []) comps = fpath.split('.') if len(comps) < 2: mod = top_mod else: mod = top_mod for subname in comps[1:]: mod = getattr(mod, subname) elif suffix == '.zip': mod = zipimporter(fpath).load_module(name) else: desc = self.suffix_map[suffix] # if it is a directory, we don't open a file try: mod_namespace = '.'.join(( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name)) except TypeError: mod_namespace = '{0}.{1}.{2}.{3}'.format( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name) if suffix == '': if USE_IMPORTLIB: # pylint: disable=no-member # Package directory, look for __init__ loader_details = [ (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES), (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES), (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), ] file_finder = importlib.machinery.FileFinder( fpath_dirname, *loader_details ) spec = file_finder.find_spec(mod_namespace) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: mod = imp.load_module(mod_namespace, None, fpath, desc) # reload all submodules if necessary if not self.initial_load: self._reload_submodules(mod) else: if USE_IMPORTLIB: # pylint: disable=no-member loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath) spec = importlib.util.spec_from_file_location( mod_namespace, fpath, loader=loader ) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() #mod = importlib.util.module_from_spec(spec) #spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod else: with salt.utils.files.fopen(fpath, desc[1]) as fn_: mod = imp.load_module(mod_namespace, fn_, fpath, desc) except IOError: raise except ImportError as exc: if 'magic number' in six.text_type(exc): error_msg = 'Failed to import {0} {1}. Bad magic number. If migrating from Python2 to Python3, remove all .pyc files and try again.'.format(self.tag, name) log.warning(error_msg) self.missing_modules[name] = error_msg log.debug( 'Failed to import %s %s:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = exc return False except Exception as error: log.error( 'Failed to import %s %s, this is due most likely to a ' 'syntax error:\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False except SystemExit as error: try: fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1] except Exception: pass else: tgt_fn = os.path.join('salt', 'utils', 'process.py') if fn_.endswith(tgt_fn) and '_handle_signals' in caller: # Race conditon, SIGTERM or SIGINT received while loader # was in process of loading a module. Call sys.exit to # ensure that the process is killed. sys.exit(salt.defaults.exitcodes.EX_OK) log.error( 'Failed to import %s %s as the module called exit()\n', self.tag, name, exc_info=True ) self.missing_modules[name] = error return False finally: sys.path.remove(fpath_dirname) if hasattr(mod, '__opts__'): mod.__opts__.update(self.opts) else: mod.__opts__ = self.opts # pack whatever other globals we were asked to for p_name, p_value in six.iteritems(self.pack): _inject_into_mod(mod, p_name, p_value) module_name = mod.__name__.rsplit('.', 1)[-1] # Call a module's initialization method if it exists module_init = getattr(mod, '__init__', None) if inspect.isfunction(module_init): try: module_init(self.opts) except TypeError as e: log.error(e) except Exception: err_string = '__init__ failed' log.debug( 'Error loading %s.%s: %s', self.tag, module_name, err_string, exc_info=True ) self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False # if virtual modules are enabled, we need to look for the # __virtual__() function inside that module and run it. if self.virtual_enable: virtual_funcs_to_process = ['__virtual__'] + self.virtual_funcs for virtual_func in virtual_funcs_to_process: virtual_ret, module_name, virtual_err, virtual_aliases = \ self._process_virtual(mod, module_name, virtual_func) if virtual_err is not None: log.trace( 'Error loading %s.%s: %s', self.tag, module_name, virtual_err ) # if _process_virtual returned a non-True value then we are # supposed to not process this module if virtual_ret is not True and module_name not in self.missing_modules: # If a module has information about why it could not be loaded, record it self.missing_modules[module_name] = virtual_err self.missing_modules[name] = virtual_err return False else: virtual_aliases = () # If this is a proxy minion then MOST modules cannot work. Therefore, require that # any module that does work with salt-proxy-minion define __proxyenabled__ as a list # containing the names of the proxy types that the module supports. # # Render modules and state modules are OK though if 'proxy' in self.opts: if self.tag in ['grains', 'proxy']: if not hasattr(mod, '__proxyenabled__') or \ (self.opts['proxy']['proxytype'] not in mod.__proxyenabled__ and '*' not in mod.__proxyenabled__): err_string = 'not a proxy_minion enabled module' self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False if getattr(mod, '__load__', False) is not False: log.info( 'The functions from module \'%s\' are being loaded from the ' 'provided __load__ attribute', module_name ) # If we had another module by the same virtual name, we should put any # new functions under the existing dictionary. mod_names = [module_name] + list(virtual_aliases) mod_dict = dict(( (x, self.loaded_modules.get(x, self.mod_dict_class())) for x in mod_names )) for attr in getattr(mod, '__load__', dir(mod)): if attr.startswith('_') and attr != '__call__': # private functions are skipped, # except __call__ which is default entrance # for multi-function batch-like state syntax continue func = getattr(mod, attr) if not inspect.isfunction(func) and not isinstance(func, functools.partial): # Not a function!? Skip it!!! continue # Let's get the function name. # If the module has the __func_alias__ attribute, it must be a # dictionary mapping in the form of(key -> value): # <real-func-name> -> <desired-func-name> # # It default's of course to the found callable attribute name # if no alias is defined. funcname = getattr(mod, '__func_alias__', {}).get(attr, attr) for tgt_mod in mod_names: try: full_funcname = '.'.join((tgt_mod, funcname)) except TypeError: full_funcname = '{0}.{1}'.format(tgt_mod, funcname) # Save many references for lookups # Careful not to overwrite existing (higher priority) functions if full_funcname not in self._dict: self._dict[full_funcname] = func if funcname not in mod_dict[tgt_mod]: setattr(mod_dict[tgt_mod], funcname, func) mod_dict[tgt_mod][funcname] = func self._apply_outputter(func, mod) # enforce depends try: Depends.enforce_dependencies(self._dict, self.tag) except RuntimeError as exc: log.info( 'Depends.enforce_dependencies() failed for the following ' 'reason: %s', exc ) for tgt_mod in mod_names: self.loaded_modules[tgt_mod] = mod_dict[tgt_mod] return True def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise KeyError('The key \'{0}\' should contain a \'.\''.format(key)) mod_name, _ = key.split('.', 1) with self._lock: # It is possible that the key is in the dictionary after # acquiring the lock due to another thread loading it. if mod_name in self.missing_modules or key in self._dict: return True # if the modulename isn't in the whitelist, don't bother if self.whitelist and mod_name not in self.whitelist: log.error( 'Failed to load function %s because its module (%s) is ' 'not in the whitelist: %s', key, mod_name, self.whitelist ) raise KeyError(key) def _inner_load(mod_name): for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and key in self._dict: return True return False # try to load the module ret = None reloaded = False # re-scan up to once, IOErrors or a failed load cause re-scans of the # filesystem while True: try: ret = _inner_load(mod_name) if not reloaded and ret is not True: self._refresh_file_mapping() reloaded = True continue break except IOError: if not reloaded: self._refresh_file_mapping() reloaded = True continue return ret def _load_all(self): ''' Load all of them ''' with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True def reload_modules(self): with self._lock: self.loaded_files = set() self._load_all() def _apply_outputter(self, func, mod): ''' Apply the __outputter__ variable to the functions ''' if hasattr(mod, '__outputter__'): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__]
saltstack/salt
salt/modules/smbios.py
get
python
def get(string, clean=True): ''' Get an individual DMI string from SMBIOS info string The string to fetch. DMIdecode supports: - ``bios-vendor`` - ``bios-version`` - ``bios-release-date`` - ``system-manufacturer`` - ``system-product-name`` - ``system-version`` - ``system-serial-number`` - ``system-uuid`` - ``baseboard-manufacturer`` - ``baseboard-product-name`` - ``baseboard-version`` - ``baseboard-serial-number`` - ``baseboard-asset-tag`` - ``chassis-manufacturer`` - ``chassis-type`` - ``chassis-version`` - ``chassis-serial-number`` - ``chassis-asset-tag`` - ``processor-family`` - ``processor-manufacturer`` - ``processor-version`` - ``processor-frequency`` clean | Don't return well-known false information | (invalid UUID's, serial 000000000's, etcetera) | Defaults to ``True`` CLI Example: .. code-block:: bash salt '*' smbios.get system-uuid clean=False ''' val = _dmidecoder('-s {0}'.format(string)).strip() # Cleanup possible comments in strings. val = '\n'.join([v for v in val.split('\n') if not v.startswith('#')]) if val.startswith('/dev/mem') or clean and not _dmi_isclean(string, val): val = None return val
Get an individual DMI string from SMBIOS info string The string to fetch. DMIdecode supports: - ``bios-vendor`` - ``bios-version`` - ``bios-release-date`` - ``system-manufacturer`` - ``system-product-name`` - ``system-version`` - ``system-serial-number`` - ``system-uuid`` - ``baseboard-manufacturer`` - ``baseboard-product-name`` - ``baseboard-version`` - ``baseboard-serial-number`` - ``baseboard-asset-tag`` - ``chassis-manufacturer`` - ``chassis-type`` - ``chassis-version`` - ``chassis-serial-number`` - ``chassis-asset-tag`` - ``processor-family`` - ``processor-manufacturer`` - ``processor-version`` - ``processor-frequency`` clean | Don't return well-known false information | (invalid UUID's, serial 000000000's, etcetera) | Defaults to ``True`` CLI Example: .. code-block:: bash salt '*' smbios.get system-uuid clean=False
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smbios.py#L41-L89
[ "def _dmidecoder(args=None):\n '''\n Call DMIdecode\n '''\n dmidecoder = salt.utils.path.which_bin(['dmidecode', 'smbios'])\n\n if not args:\n out = salt.modules.cmdmod._run_quiet(dmidecoder)\n else:\n out = salt.modules.cmdmod._run_quiet('{0} {1}'.format(dmidecoder, args))\n\n return out\n", "def _dmi_isclean(key, val):\n '''\n Clean out well-known bogus values\n '''\n if not val or re.match('none', val, flags=re.IGNORECASE):\n # log.debug('DMI {0} value {1} seems invalid or empty'.format(key, val))\n return False\n elif 'uuid' in key:\n # Try each version (1-5) of RFC4122 to check if it's actually a UUID\n for uuidver in range(1, 5):\n try:\n uuid.UUID(val, version=uuidver)\n return True\n except ValueError:\n continue\n log.trace('DMI %s value %s is an invalid UUID', key, val.replace('\\n', ' '))\n return False\n elif re.search('serial|part|version', key):\n # 'To be filled by O.E.M.\n # 'Not applicable' etc.\n # 'Not specified' etc.\n # 0000000, 1234667 etc.\n # begone!\n return not re.match(r'^[0]+$', val) \\\n and not re.match(r'[0]?1234567[8]?[9]?[0]?', val) \\\n and not re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)\n elif re.search('asset|manufacturer', key):\n # AssetTag0. Manufacturer04. Begone.\n return not re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE)\n else:\n # map unspecified, undefined, unknown & whatever to None\n return not re.search(r'to be filled', val, flags=re.IGNORECASE) \\\n and not re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)',\n val, flags=re.IGNORECASE)\n" ]
# -*- coding: utf-8 -*- ''' Interface to SMBIOS/DMI (Parsing through dmidecode) External References ------------------- | `Desktop Management Interface (DMI) <http://www.dmtf.org/standards/dmi>`_ | `System Management BIOS <http://www.dmtf.org/standards/smbios>`_ | `DMIdecode <http://www.nongnu.org/dmidecode/>`_ ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging import uuid import re # Import salt libs import salt.utils.path # Solve the Chicken and egg problem where grains need to run before any # of the modules are loaded and are generally available for any usage. import salt.modules.cmdmod from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) def __virtual__(): ''' Only work when dmidecode is installed. ''' return (bool(salt.utils.path.which_bin(['dmidecode', 'smbios'])), 'The smbios execution module failed to load: neither dmidecode nor smbios in the path.') def records(rec_type=None, fields=None, clean=True): ''' Return DMI records from SMBIOS type Return only records of type(s) The SMBIOS specification defines the following DMI types: ==== ====================================== Type Information ==== ====================================== 0 BIOS 1 System 2 Baseboard 3 Chassis 4 Processor 5 Memory Controller 6 Memory Module 7 Cache 8 Port Connector 9 System Slots 10 On Board Devices 11 OEM Strings 12 System Configuration Options 13 BIOS Language 14 Group Associations 15 System Event Log 16 Physical Memory Array 17 Memory Device 18 32-bit Memory Error 19 Memory Array Mapped Address 20 Memory Device Mapped Address 21 Built-in Pointing Device 22 Portable Battery 23 System Reset 24 Hardware Security 25 System Power Controls 26 Voltage Probe 27 Cooling Device 28 Temperature Probe 29 Electrical Current Probe 30 Out-of-band Remote Access 31 Boot Integrity Services 32 System Boot 33 64-bit Memory Error 34 Management Device 35 Management Device Component 36 Management Device Threshold Data 37 Memory Channel 38 IPMI Device 39 Power Supply 40 Additional Information 41 Onboard Devices Extended Information 42 Management Controller Host Interface ==== ====================================== clean | Don't return well-known false information | (invalid UUID's, serial 000000000's, etcetera) | Defaults to ``True`` CLI Example: .. code-block:: bash salt '*' smbios.records clean=False salt '*' smbios.records 14 salt '*' smbios.records 4 core_count,thread_count,current_speed ''' if rec_type is None: smbios = _dmi_parse(_dmidecoder(), clean, fields) else: smbios = _dmi_parse(_dmidecoder('-t {0}'.format(rec_type)), clean, fields) return smbios def _dmi_parse(data, clean=True, fields=None): ''' Structurize DMI records into a nice list Optionally trash bogus entries and filter output ''' dmi = [] # Detect & split Handle records dmi_split = re.compile('(handle [0-9]x[0-9a-f]+[^\n]+)\n', re.MULTILINE+re.IGNORECASE) dmi_raw = iter(re.split(dmi_split, data)[1:]) for handle, dmi_raw in zip(dmi_raw, dmi_raw): handle, htype = [hline.split()[-1] for hline in handle.split(',')][0:2] dmi_raw = dmi_raw.split('\n') # log.debug('%s record contains %s', handle, dmi_raw) log.debug('Parsing handle %s', handle) # The first line of a handle is a description of the type record = { 'handle': handle, 'description': dmi_raw.pop(0).strip(), 'type': int(htype) } if not dmi_raw: # empty record if not clean: dmi.append(record) continue # log.debug('%s record contains %s', record, dmi_raw) dmi_data = _dmi_data(dmi_raw, clean, fields) if dmi_data: record['data'] = dmi_data dmi.append(record) elif not clean: dmi.append(record) return dmi def _dmi_data(dmi_raw, clean, fields): ''' Parse the raw DMIdecode output of a single handle into a nice dict ''' dmi_data = {} key = None key_data = [None, []] for line in dmi_raw: if re.match(r'\t[^\s]+', line): # Finish previous key if key is not None: # log.debug('Evaluating DMI key {0}: {1}'.format(key, key_data)) value, vlist = key_data if vlist: if value is not None: # On the rare occasion # (I counted 1 on all systems we have) # that there's both a value <and> a list # just insert the value on top of the list vlist.insert(0, value) dmi_data[key] = vlist elif value is not None: dmi_data[key] = value # Family: Core i5 # Keyboard Password Status: Not Implemented key, val = line.split(':', 1) key = key.strip().lower().replace(' ', '_') if (clean and key == 'header_and_data') \ or (fields and key not in fields): key = None continue else: key_data = [_dmi_cast(key, val.strip(), clean), []] elif key is None: continue elif re.match(r'\t\t[^\s]+', line): # Installable Languages: 1 # en-US # Characteristics: # PCI is supported # PNP is supported val = _dmi_cast(key, line.strip(), clean) if val is not None: # log.debug('DMI key %s gained list item %s', key, val) key_data[1].append(val) return dmi_data def _dmi_cast(key, val, clean=True): ''' Simple caster thingy for trying to fish out at least ints & lists from strings ''' if clean and not _dmi_isclean(key, val): return elif not re.match(r'serial|part|asset|product', key, flags=re.IGNORECASE): if ',' in val: val = [el.strip() for el in val.split(',')] else: try: val = int(val) except Exception: pass return val def _dmi_isclean(key, val): ''' Clean out well-known bogus values ''' if not val or re.match('none', val, flags=re.IGNORECASE): # log.debug('DMI {0} value {1} seems invalid or empty'.format(key, val)) return False elif 'uuid' in key: # Try each version (1-5) of RFC4122 to check if it's actually a UUID for uuidver in range(1, 5): try: uuid.UUID(val, version=uuidver) return True except ValueError: continue log.trace('DMI %s value %s is an invalid UUID', key, val.replace('\n', ' ')) return False elif re.search('serial|part|version', key): # 'To be filled by O.E.M. # 'Not applicable' etc. # 'Not specified' etc. # 0000000, 1234667 etc. # begone! return not re.match(r'^[0]+$', val) \ and not re.match(r'[0]?1234567[8]?[9]?[0]?', val) \ and not re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE) elif re.search('asset|manufacturer', key): # AssetTag0. Manufacturer04. Begone. return not re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE) else: # map unspecified, undefined, unknown & whatever to None return not re.search(r'to be filled', val, flags=re.IGNORECASE) \ and not re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)', val, flags=re.IGNORECASE) def _dmidecoder(args=None): ''' Call DMIdecode ''' dmidecoder = salt.utils.path.which_bin(['dmidecode', 'smbios']) if not args: out = salt.modules.cmdmod._run_quiet(dmidecoder) else: out = salt.modules.cmdmod._run_quiet('{0} {1}'.format(dmidecoder, args)) return out
saltstack/salt
salt/modules/smbios.py
records
python
def records(rec_type=None, fields=None, clean=True): ''' Return DMI records from SMBIOS type Return only records of type(s) The SMBIOS specification defines the following DMI types: ==== ====================================== Type Information ==== ====================================== 0 BIOS 1 System 2 Baseboard 3 Chassis 4 Processor 5 Memory Controller 6 Memory Module 7 Cache 8 Port Connector 9 System Slots 10 On Board Devices 11 OEM Strings 12 System Configuration Options 13 BIOS Language 14 Group Associations 15 System Event Log 16 Physical Memory Array 17 Memory Device 18 32-bit Memory Error 19 Memory Array Mapped Address 20 Memory Device Mapped Address 21 Built-in Pointing Device 22 Portable Battery 23 System Reset 24 Hardware Security 25 System Power Controls 26 Voltage Probe 27 Cooling Device 28 Temperature Probe 29 Electrical Current Probe 30 Out-of-band Remote Access 31 Boot Integrity Services 32 System Boot 33 64-bit Memory Error 34 Management Device 35 Management Device Component 36 Management Device Threshold Data 37 Memory Channel 38 IPMI Device 39 Power Supply 40 Additional Information 41 Onboard Devices Extended Information 42 Management Controller Host Interface ==== ====================================== clean | Don't return well-known false information | (invalid UUID's, serial 000000000's, etcetera) | Defaults to ``True`` CLI Example: .. code-block:: bash salt '*' smbios.records clean=False salt '*' smbios.records 14 salt '*' smbios.records 4 core_count,thread_count,current_speed ''' if rec_type is None: smbios = _dmi_parse(_dmidecoder(), clean, fields) else: smbios = _dmi_parse(_dmidecoder('-t {0}'.format(rec_type)), clean, fields) return smbios
Return DMI records from SMBIOS type Return only records of type(s) The SMBIOS specification defines the following DMI types: ==== ====================================== Type Information ==== ====================================== 0 BIOS 1 System 2 Baseboard 3 Chassis 4 Processor 5 Memory Controller 6 Memory Module 7 Cache 8 Port Connector 9 System Slots 10 On Board Devices 11 OEM Strings 12 System Configuration Options 13 BIOS Language 14 Group Associations 15 System Event Log 16 Physical Memory Array 17 Memory Device 18 32-bit Memory Error 19 Memory Array Mapped Address 20 Memory Device Mapped Address 21 Built-in Pointing Device 22 Portable Battery 23 System Reset 24 Hardware Security 25 System Power Controls 26 Voltage Probe 27 Cooling Device 28 Temperature Probe 29 Electrical Current Probe 30 Out-of-band Remote Access 31 Boot Integrity Services 32 System Boot 33 64-bit Memory Error 34 Management Device 35 Management Device Component 36 Management Device Threshold Data 37 Memory Channel 38 IPMI Device 39 Power Supply 40 Additional Information 41 Onboard Devices Extended Information 42 Management Controller Host Interface ==== ====================================== clean | Don't return well-known false information | (invalid UUID's, serial 000000000's, etcetera) | Defaults to ``True`` CLI Example: .. code-block:: bash salt '*' smbios.records clean=False salt '*' smbios.records 14 salt '*' smbios.records 4 core_count,thread_count,current_speed
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smbios.py#L92-L167
[ "def _dmidecoder(args=None):\n '''\n Call DMIdecode\n '''\n dmidecoder = salt.utils.path.which_bin(['dmidecode', 'smbios'])\n\n if not args:\n out = salt.modules.cmdmod._run_quiet(dmidecoder)\n else:\n out = salt.modules.cmdmod._run_quiet('{0} {1}'.format(dmidecoder, args))\n\n return out\n", "def _dmi_parse(data, clean=True, fields=None):\n '''\n Structurize DMI records into a nice list\n Optionally trash bogus entries and filter output\n '''\n dmi = []\n\n # Detect & split Handle records\n dmi_split = re.compile('(handle [0-9]x[0-9a-f]+[^\\n]+)\\n', re.MULTILINE+re.IGNORECASE)\n dmi_raw = iter(re.split(dmi_split, data)[1:])\n for handle, dmi_raw in zip(dmi_raw, dmi_raw):\n handle, htype = [hline.split()[-1] for hline in handle.split(',')][0:2]\n dmi_raw = dmi_raw.split('\\n')\n # log.debug('%s record contains %s', handle, dmi_raw)\n log.debug('Parsing handle %s', handle)\n\n # The first line of a handle is a description of the type\n record = {\n 'handle': handle,\n 'description': dmi_raw.pop(0).strip(),\n 'type': int(htype)\n }\n\n if not dmi_raw:\n # empty record\n if not clean:\n dmi.append(record)\n continue\n\n # log.debug('%s record contains %s', record, dmi_raw)\n dmi_data = _dmi_data(dmi_raw, clean, fields)\n if dmi_data:\n record['data'] = dmi_data\n dmi.append(record)\n elif not clean:\n dmi.append(record)\n\n return dmi\n" ]
# -*- coding: utf-8 -*- ''' Interface to SMBIOS/DMI (Parsing through dmidecode) External References ------------------- | `Desktop Management Interface (DMI) <http://www.dmtf.org/standards/dmi>`_ | `System Management BIOS <http://www.dmtf.org/standards/smbios>`_ | `DMIdecode <http://www.nongnu.org/dmidecode/>`_ ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging import uuid import re # Import salt libs import salt.utils.path # Solve the Chicken and egg problem where grains need to run before any # of the modules are loaded and are generally available for any usage. import salt.modules.cmdmod from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) def __virtual__(): ''' Only work when dmidecode is installed. ''' return (bool(salt.utils.path.which_bin(['dmidecode', 'smbios'])), 'The smbios execution module failed to load: neither dmidecode nor smbios in the path.') def get(string, clean=True): ''' Get an individual DMI string from SMBIOS info string The string to fetch. DMIdecode supports: - ``bios-vendor`` - ``bios-version`` - ``bios-release-date`` - ``system-manufacturer`` - ``system-product-name`` - ``system-version`` - ``system-serial-number`` - ``system-uuid`` - ``baseboard-manufacturer`` - ``baseboard-product-name`` - ``baseboard-version`` - ``baseboard-serial-number`` - ``baseboard-asset-tag`` - ``chassis-manufacturer`` - ``chassis-type`` - ``chassis-version`` - ``chassis-serial-number`` - ``chassis-asset-tag`` - ``processor-family`` - ``processor-manufacturer`` - ``processor-version`` - ``processor-frequency`` clean | Don't return well-known false information | (invalid UUID's, serial 000000000's, etcetera) | Defaults to ``True`` CLI Example: .. code-block:: bash salt '*' smbios.get system-uuid clean=False ''' val = _dmidecoder('-s {0}'.format(string)).strip() # Cleanup possible comments in strings. val = '\n'.join([v for v in val.split('\n') if not v.startswith('#')]) if val.startswith('/dev/mem') or clean and not _dmi_isclean(string, val): val = None return val def _dmi_parse(data, clean=True, fields=None): ''' Structurize DMI records into a nice list Optionally trash bogus entries and filter output ''' dmi = [] # Detect & split Handle records dmi_split = re.compile('(handle [0-9]x[0-9a-f]+[^\n]+)\n', re.MULTILINE+re.IGNORECASE) dmi_raw = iter(re.split(dmi_split, data)[1:]) for handle, dmi_raw in zip(dmi_raw, dmi_raw): handle, htype = [hline.split()[-1] for hline in handle.split(',')][0:2] dmi_raw = dmi_raw.split('\n') # log.debug('%s record contains %s', handle, dmi_raw) log.debug('Parsing handle %s', handle) # The first line of a handle is a description of the type record = { 'handle': handle, 'description': dmi_raw.pop(0).strip(), 'type': int(htype) } if not dmi_raw: # empty record if not clean: dmi.append(record) continue # log.debug('%s record contains %s', record, dmi_raw) dmi_data = _dmi_data(dmi_raw, clean, fields) if dmi_data: record['data'] = dmi_data dmi.append(record) elif not clean: dmi.append(record) return dmi def _dmi_data(dmi_raw, clean, fields): ''' Parse the raw DMIdecode output of a single handle into a nice dict ''' dmi_data = {} key = None key_data = [None, []] for line in dmi_raw: if re.match(r'\t[^\s]+', line): # Finish previous key if key is not None: # log.debug('Evaluating DMI key {0}: {1}'.format(key, key_data)) value, vlist = key_data if vlist: if value is not None: # On the rare occasion # (I counted 1 on all systems we have) # that there's both a value <and> a list # just insert the value on top of the list vlist.insert(0, value) dmi_data[key] = vlist elif value is not None: dmi_data[key] = value # Family: Core i5 # Keyboard Password Status: Not Implemented key, val = line.split(':', 1) key = key.strip().lower().replace(' ', '_') if (clean and key == 'header_and_data') \ or (fields and key not in fields): key = None continue else: key_data = [_dmi_cast(key, val.strip(), clean), []] elif key is None: continue elif re.match(r'\t\t[^\s]+', line): # Installable Languages: 1 # en-US # Characteristics: # PCI is supported # PNP is supported val = _dmi_cast(key, line.strip(), clean) if val is not None: # log.debug('DMI key %s gained list item %s', key, val) key_data[1].append(val) return dmi_data def _dmi_cast(key, val, clean=True): ''' Simple caster thingy for trying to fish out at least ints & lists from strings ''' if clean and not _dmi_isclean(key, val): return elif not re.match(r'serial|part|asset|product', key, flags=re.IGNORECASE): if ',' in val: val = [el.strip() for el in val.split(',')] else: try: val = int(val) except Exception: pass return val def _dmi_isclean(key, val): ''' Clean out well-known bogus values ''' if not val or re.match('none', val, flags=re.IGNORECASE): # log.debug('DMI {0} value {1} seems invalid or empty'.format(key, val)) return False elif 'uuid' in key: # Try each version (1-5) of RFC4122 to check if it's actually a UUID for uuidver in range(1, 5): try: uuid.UUID(val, version=uuidver) return True except ValueError: continue log.trace('DMI %s value %s is an invalid UUID', key, val.replace('\n', ' ')) return False elif re.search('serial|part|version', key): # 'To be filled by O.E.M. # 'Not applicable' etc. # 'Not specified' etc. # 0000000, 1234667 etc. # begone! return not re.match(r'^[0]+$', val) \ and not re.match(r'[0]?1234567[8]?[9]?[0]?', val) \ and not re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE) elif re.search('asset|manufacturer', key): # AssetTag0. Manufacturer04. Begone. return not re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE) else: # map unspecified, undefined, unknown & whatever to None return not re.search(r'to be filled', val, flags=re.IGNORECASE) \ and not re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)', val, flags=re.IGNORECASE) def _dmidecoder(args=None): ''' Call DMIdecode ''' dmidecoder = salt.utils.path.which_bin(['dmidecode', 'smbios']) if not args: out = salt.modules.cmdmod._run_quiet(dmidecoder) else: out = salt.modules.cmdmod._run_quiet('{0} {1}'.format(dmidecoder, args)) return out
saltstack/salt
salt/modules/smbios.py
_dmi_parse
python
def _dmi_parse(data, clean=True, fields=None): ''' Structurize DMI records into a nice list Optionally trash bogus entries and filter output ''' dmi = [] # Detect & split Handle records dmi_split = re.compile('(handle [0-9]x[0-9a-f]+[^\n]+)\n', re.MULTILINE+re.IGNORECASE) dmi_raw = iter(re.split(dmi_split, data)[1:]) for handle, dmi_raw in zip(dmi_raw, dmi_raw): handle, htype = [hline.split()[-1] for hline in handle.split(',')][0:2] dmi_raw = dmi_raw.split('\n') # log.debug('%s record contains %s', handle, dmi_raw) log.debug('Parsing handle %s', handle) # The first line of a handle is a description of the type record = { 'handle': handle, 'description': dmi_raw.pop(0).strip(), 'type': int(htype) } if not dmi_raw: # empty record if not clean: dmi.append(record) continue # log.debug('%s record contains %s', record, dmi_raw) dmi_data = _dmi_data(dmi_raw, clean, fields) if dmi_data: record['data'] = dmi_data dmi.append(record) elif not clean: dmi.append(record) return dmi
Structurize DMI records into a nice list Optionally trash bogus entries and filter output
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smbios.py#L170-L207
[ "def _dmi_data(dmi_raw, clean, fields):\n '''\n Parse the raw DMIdecode output of a single handle\n into a nice dict\n '''\n dmi_data = {}\n\n key = None\n key_data = [None, []]\n for line in dmi_raw:\n if re.match(r'\\t[^\\s]+', line):\n # Finish previous key\n if key is not None:\n # log.debug('Evaluating DMI key {0}: {1}'.format(key, key_data))\n value, vlist = key_data\n if vlist:\n if value is not None:\n # On the rare occasion\n # (I counted 1 on all systems we have)\n # that there's both a value <and> a list\n # just insert the value on top of the list\n vlist.insert(0, value)\n dmi_data[key] = vlist\n elif value is not None:\n dmi_data[key] = value\n\n # Family: Core i5\n # Keyboard Password Status: Not Implemented\n key, val = line.split(':', 1)\n key = key.strip().lower().replace(' ', '_')\n if (clean and key == 'header_and_data') \\\n or (fields and key not in fields):\n key = None\n continue\n else:\n key_data = [_dmi_cast(key, val.strip(), clean), []]\n elif key is None:\n continue\n elif re.match(r'\\t\\t[^\\s]+', line):\n # Installable Languages: 1\n # en-US\n # Characteristics:\n # PCI is supported\n # PNP is supported\n val = _dmi_cast(key, line.strip(), clean)\n if val is not None:\n # log.debug('DMI key %s gained list item %s', key, val)\n key_data[1].append(val)\n\n return dmi_data\n" ]
# -*- coding: utf-8 -*- ''' Interface to SMBIOS/DMI (Parsing through dmidecode) External References ------------------- | `Desktop Management Interface (DMI) <http://www.dmtf.org/standards/dmi>`_ | `System Management BIOS <http://www.dmtf.org/standards/smbios>`_ | `DMIdecode <http://www.nongnu.org/dmidecode/>`_ ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging import uuid import re # Import salt libs import salt.utils.path # Solve the Chicken and egg problem where grains need to run before any # of the modules are loaded and are generally available for any usage. import salt.modules.cmdmod from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) def __virtual__(): ''' Only work when dmidecode is installed. ''' return (bool(salt.utils.path.which_bin(['dmidecode', 'smbios'])), 'The smbios execution module failed to load: neither dmidecode nor smbios in the path.') def get(string, clean=True): ''' Get an individual DMI string from SMBIOS info string The string to fetch. DMIdecode supports: - ``bios-vendor`` - ``bios-version`` - ``bios-release-date`` - ``system-manufacturer`` - ``system-product-name`` - ``system-version`` - ``system-serial-number`` - ``system-uuid`` - ``baseboard-manufacturer`` - ``baseboard-product-name`` - ``baseboard-version`` - ``baseboard-serial-number`` - ``baseboard-asset-tag`` - ``chassis-manufacturer`` - ``chassis-type`` - ``chassis-version`` - ``chassis-serial-number`` - ``chassis-asset-tag`` - ``processor-family`` - ``processor-manufacturer`` - ``processor-version`` - ``processor-frequency`` clean | Don't return well-known false information | (invalid UUID's, serial 000000000's, etcetera) | Defaults to ``True`` CLI Example: .. code-block:: bash salt '*' smbios.get system-uuid clean=False ''' val = _dmidecoder('-s {0}'.format(string)).strip() # Cleanup possible comments in strings. val = '\n'.join([v for v in val.split('\n') if not v.startswith('#')]) if val.startswith('/dev/mem') or clean and not _dmi_isclean(string, val): val = None return val def records(rec_type=None, fields=None, clean=True): ''' Return DMI records from SMBIOS type Return only records of type(s) The SMBIOS specification defines the following DMI types: ==== ====================================== Type Information ==== ====================================== 0 BIOS 1 System 2 Baseboard 3 Chassis 4 Processor 5 Memory Controller 6 Memory Module 7 Cache 8 Port Connector 9 System Slots 10 On Board Devices 11 OEM Strings 12 System Configuration Options 13 BIOS Language 14 Group Associations 15 System Event Log 16 Physical Memory Array 17 Memory Device 18 32-bit Memory Error 19 Memory Array Mapped Address 20 Memory Device Mapped Address 21 Built-in Pointing Device 22 Portable Battery 23 System Reset 24 Hardware Security 25 System Power Controls 26 Voltage Probe 27 Cooling Device 28 Temperature Probe 29 Electrical Current Probe 30 Out-of-band Remote Access 31 Boot Integrity Services 32 System Boot 33 64-bit Memory Error 34 Management Device 35 Management Device Component 36 Management Device Threshold Data 37 Memory Channel 38 IPMI Device 39 Power Supply 40 Additional Information 41 Onboard Devices Extended Information 42 Management Controller Host Interface ==== ====================================== clean | Don't return well-known false information | (invalid UUID's, serial 000000000's, etcetera) | Defaults to ``True`` CLI Example: .. code-block:: bash salt '*' smbios.records clean=False salt '*' smbios.records 14 salt '*' smbios.records 4 core_count,thread_count,current_speed ''' if rec_type is None: smbios = _dmi_parse(_dmidecoder(), clean, fields) else: smbios = _dmi_parse(_dmidecoder('-t {0}'.format(rec_type)), clean, fields) return smbios def _dmi_data(dmi_raw, clean, fields): ''' Parse the raw DMIdecode output of a single handle into a nice dict ''' dmi_data = {} key = None key_data = [None, []] for line in dmi_raw: if re.match(r'\t[^\s]+', line): # Finish previous key if key is not None: # log.debug('Evaluating DMI key {0}: {1}'.format(key, key_data)) value, vlist = key_data if vlist: if value is not None: # On the rare occasion # (I counted 1 on all systems we have) # that there's both a value <and> a list # just insert the value on top of the list vlist.insert(0, value) dmi_data[key] = vlist elif value is not None: dmi_data[key] = value # Family: Core i5 # Keyboard Password Status: Not Implemented key, val = line.split(':', 1) key = key.strip().lower().replace(' ', '_') if (clean and key == 'header_and_data') \ or (fields and key not in fields): key = None continue else: key_data = [_dmi_cast(key, val.strip(), clean), []] elif key is None: continue elif re.match(r'\t\t[^\s]+', line): # Installable Languages: 1 # en-US # Characteristics: # PCI is supported # PNP is supported val = _dmi_cast(key, line.strip(), clean) if val is not None: # log.debug('DMI key %s gained list item %s', key, val) key_data[1].append(val) return dmi_data def _dmi_cast(key, val, clean=True): ''' Simple caster thingy for trying to fish out at least ints & lists from strings ''' if clean and not _dmi_isclean(key, val): return elif not re.match(r'serial|part|asset|product', key, flags=re.IGNORECASE): if ',' in val: val = [el.strip() for el in val.split(',')] else: try: val = int(val) except Exception: pass return val def _dmi_isclean(key, val): ''' Clean out well-known bogus values ''' if not val or re.match('none', val, flags=re.IGNORECASE): # log.debug('DMI {0} value {1} seems invalid or empty'.format(key, val)) return False elif 'uuid' in key: # Try each version (1-5) of RFC4122 to check if it's actually a UUID for uuidver in range(1, 5): try: uuid.UUID(val, version=uuidver) return True except ValueError: continue log.trace('DMI %s value %s is an invalid UUID', key, val.replace('\n', ' ')) return False elif re.search('serial|part|version', key): # 'To be filled by O.E.M. # 'Not applicable' etc. # 'Not specified' etc. # 0000000, 1234667 etc. # begone! return not re.match(r'^[0]+$', val) \ and not re.match(r'[0]?1234567[8]?[9]?[0]?', val) \ and not re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE) elif re.search('asset|manufacturer', key): # AssetTag0. Manufacturer04. Begone. return not re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE) else: # map unspecified, undefined, unknown & whatever to None return not re.search(r'to be filled', val, flags=re.IGNORECASE) \ and not re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)', val, flags=re.IGNORECASE) def _dmidecoder(args=None): ''' Call DMIdecode ''' dmidecoder = salt.utils.path.which_bin(['dmidecode', 'smbios']) if not args: out = salt.modules.cmdmod._run_quiet(dmidecoder) else: out = salt.modules.cmdmod._run_quiet('{0} {1}'.format(dmidecoder, args)) return out
saltstack/salt
salt/modules/smbios.py
_dmi_data
python
def _dmi_data(dmi_raw, clean, fields): ''' Parse the raw DMIdecode output of a single handle into a nice dict ''' dmi_data = {} key = None key_data = [None, []] for line in dmi_raw: if re.match(r'\t[^\s]+', line): # Finish previous key if key is not None: # log.debug('Evaluating DMI key {0}: {1}'.format(key, key_data)) value, vlist = key_data if vlist: if value is not None: # On the rare occasion # (I counted 1 on all systems we have) # that there's both a value <and> a list # just insert the value on top of the list vlist.insert(0, value) dmi_data[key] = vlist elif value is not None: dmi_data[key] = value # Family: Core i5 # Keyboard Password Status: Not Implemented key, val = line.split(':', 1) key = key.strip().lower().replace(' ', '_') if (clean and key == 'header_and_data') \ or (fields and key not in fields): key = None continue else: key_data = [_dmi_cast(key, val.strip(), clean), []] elif key is None: continue elif re.match(r'\t\t[^\s]+', line): # Installable Languages: 1 # en-US # Characteristics: # PCI is supported # PNP is supported val = _dmi_cast(key, line.strip(), clean) if val is not None: # log.debug('DMI key %s gained list item %s', key, val) key_data[1].append(val) return dmi_data
Parse the raw DMIdecode output of a single handle into a nice dict
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smbios.py#L210-L259
null
# -*- coding: utf-8 -*- ''' Interface to SMBIOS/DMI (Parsing through dmidecode) External References ------------------- | `Desktop Management Interface (DMI) <http://www.dmtf.org/standards/dmi>`_ | `System Management BIOS <http://www.dmtf.org/standards/smbios>`_ | `DMIdecode <http://www.nongnu.org/dmidecode/>`_ ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging import uuid import re # Import salt libs import salt.utils.path # Solve the Chicken and egg problem where grains need to run before any # of the modules are loaded and are generally available for any usage. import salt.modules.cmdmod from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) def __virtual__(): ''' Only work when dmidecode is installed. ''' return (bool(salt.utils.path.which_bin(['dmidecode', 'smbios'])), 'The smbios execution module failed to load: neither dmidecode nor smbios in the path.') def get(string, clean=True): ''' Get an individual DMI string from SMBIOS info string The string to fetch. DMIdecode supports: - ``bios-vendor`` - ``bios-version`` - ``bios-release-date`` - ``system-manufacturer`` - ``system-product-name`` - ``system-version`` - ``system-serial-number`` - ``system-uuid`` - ``baseboard-manufacturer`` - ``baseboard-product-name`` - ``baseboard-version`` - ``baseboard-serial-number`` - ``baseboard-asset-tag`` - ``chassis-manufacturer`` - ``chassis-type`` - ``chassis-version`` - ``chassis-serial-number`` - ``chassis-asset-tag`` - ``processor-family`` - ``processor-manufacturer`` - ``processor-version`` - ``processor-frequency`` clean | Don't return well-known false information | (invalid UUID's, serial 000000000's, etcetera) | Defaults to ``True`` CLI Example: .. code-block:: bash salt '*' smbios.get system-uuid clean=False ''' val = _dmidecoder('-s {0}'.format(string)).strip() # Cleanup possible comments in strings. val = '\n'.join([v for v in val.split('\n') if not v.startswith('#')]) if val.startswith('/dev/mem') or clean and not _dmi_isclean(string, val): val = None return val def records(rec_type=None, fields=None, clean=True): ''' Return DMI records from SMBIOS type Return only records of type(s) The SMBIOS specification defines the following DMI types: ==== ====================================== Type Information ==== ====================================== 0 BIOS 1 System 2 Baseboard 3 Chassis 4 Processor 5 Memory Controller 6 Memory Module 7 Cache 8 Port Connector 9 System Slots 10 On Board Devices 11 OEM Strings 12 System Configuration Options 13 BIOS Language 14 Group Associations 15 System Event Log 16 Physical Memory Array 17 Memory Device 18 32-bit Memory Error 19 Memory Array Mapped Address 20 Memory Device Mapped Address 21 Built-in Pointing Device 22 Portable Battery 23 System Reset 24 Hardware Security 25 System Power Controls 26 Voltage Probe 27 Cooling Device 28 Temperature Probe 29 Electrical Current Probe 30 Out-of-band Remote Access 31 Boot Integrity Services 32 System Boot 33 64-bit Memory Error 34 Management Device 35 Management Device Component 36 Management Device Threshold Data 37 Memory Channel 38 IPMI Device 39 Power Supply 40 Additional Information 41 Onboard Devices Extended Information 42 Management Controller Host Interface ==== ====================================== clean | Don't return well-known false information | (invalid UUID's, serial 000000000's, etcetera) | Defaults to ``True`` CLI Example: .. code-block:: bash salt '*' smbios.records clean=False salt '*' smbios.records 14 salt '*' smbios.records 4 core_count,thread_count,current_speed ''' if rec_type is None: smbios = _dmi_parse(_dmidecoder(), clean, fields) else: smbios = _dmi_parse(_dmidecoder('-t {0}'.format(rec_type)), clean, fields) return smbios def _dmi_parse(data, clean=True, fields=None): ''' Structurize DMI records into a nice list Optionally trash bogus entries and filter output ''' dmi = [] # Detect & split Handle records dmi_split = re.compile('(handle [0-9]x[0-9a-f]+[^\n]+)\n', re.MULTILINE+re.IGNORECASE) dmi_raw = iter(re.split(dmi_split, data)[1:]) for handle, dmi_raw in zip(dmi_raw, dmi_raw): handle, htype = [hline.split()[-1] for hline in handle.split(',')][0:2] dmi_raw = dmi_raw.split('\n') # log.debug('%s record contains %s', handle, dmi_raw) log.debug('Parsing handle %s', handle) # The first line of a handle is a description of the type record = { 'handle': handle, 'description': dmi_raw.pop(0).strip(), 'type': int(htype) } if not dmi_raw: # empty record if not clean: dmi.append(record) continue # log.debug('%s record contains %s', record, dmi_raw) dmi_data = _dmi_data(dmi_raw, clean, fields) if dmi_data: record['data'] = dmi_data dmi.append(record) elif not clean: dmi.append(record) return dmi def _dmi_cast(key, val, clean=True): ''' Simple caster thingy for trying to fish out at least ints & lists from strings ''' if clean and not _dmi_isclean(key, val): return elif not re.match(r'serial|part|asset|product', key, flags=re.IGNORECASE): if ',' in val: val = [el.strip() for el in val.split(',')] else: try: val = int(val) except Exception: pass return val def _dmi_isclean(key, val): ''' Clean out well-known bogus values ''' if not val or re.match('none', val, flags=re.IGNORECASE): # log.debug('DMI {0} value {1} seems invalid or empty'.format(key, val)) return False elif 'uuid' in key: # Try each version (1-5) of RFC4122 to check if it's actually a UUID for uuidver in range(1, 5): try: uuid.UUID(val, version=uuidver) return True except ValueError: continue log.trace('DMI %s value %s is an invalid UUID', key, val.replace('\n', ' ')) return False elif re.search('serial|part|version', key): # 'To be filled by O.E.M. # 'Not applicable' etc. # 'Not specified' etc. # 0000000, 1234667 etc. # begone! return not re.match(r'^[0]+$', val) \ and not re.match(r'[0]?1234567[8]?[9]?[0]?', val) \ and not re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE) elif re.search('asset|manufacturer', key): # AssetTag0. Manufacturer04. Begone. return not re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE) else: # map unspecified, undefined, unknown & whatever to None return not re.search(r'to be filled', val, flags=re.IGNORECASE) \ and not re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)', val, flags=re.IGNORECASE) def _dmidecoder(args=None): ''' Call DMIdecode ''' dmidecoder = salt.utils.path.which_bin(['dmidecode', 'smbios']) if not args: out = salt.modules.cmdmod._run_quiet(dmidecoder) else: out = salt.modules.cmdmod._run_quiet('{0} {1}'.format(dmidecoder, args)) return out
saltstack/salt
salt/modules/smbios.py
_dmi_cast
python
def _dmi_cast(key, val, clean=True): ''' Simple caster thingy for trying to fish out at least ints & lists from strings ''' if clean and not _dmi_isclean(key, val): return elif not re.match(r'serial|part|asset|product', key, flags=re.IGNORECASE): if ',' in val: val = [el.strip() for el in val.split(',')] else: try: val = int(val) except Exception: pass return val
Simple caster thingy for trying to fish out at least ints & lists from strings
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smbios.py#L262-L277
null
# -*- coding: utf-8 -*- ''' Interface to SMBIOS/DMI (Parsing through dmidecode) External References ------------------- | `Desktop Management Interface (DMI) <http://www.dmtf.org/standards/dmi>`_ | `System Management BIOS <http://www.dmtf.org/standards/smbios>`_ | `DMIdecode <http://www.nongnu.org/dmidecode/>`_ ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging import uuid import re # Import salt libs import salt.utils.path # Solve the Chicken and egg problem where grains need to run before any # of the modules are loaded and are generally available for any usage. import salt.modules.cmdmod from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) def __virtual__(): ''' Only work when dmidecode is installed. ''' return (bool(salt.utils.path.which_bin(['dmidecode', 'smbios'])), 'The smbios execution module failed to load: neither dmidecode nor smbios in the path.') def get(string, clean=True): ''' Get an individual DMI string from SMBIOS info string The string to fetch. DMIdecode supports: - ``bios-vendor`` - ``bios-version`` - ``bios-release-date`` - ``system-manufacturer`` - ``system-product-name`` - ``system-version`` - ``system-serial-number`` - ``system-uuid`` - ``baseboard-manufacturer`` - ``baseboard-product-name`` - ``baseboard-version`` - ``baseboard-serial-number`` - ``baseboard-asset-tag`` - ``chassis-manufacturer`` - ``chassis-type`` - ``chassis-version`` - ``chassis-serial-number`` - ``chassis-asset-tag`` - ``processor-family`` - ``processor-manufacturer`` - ``processor-version`` - ``processor-frequency`` clean | Don't return well-known false information | (invalid UUID's, serial 000000000's, etcetera) | Defaults to ``True`` CLI Example: .. code-block:: bash salt '*' smbios.get system-uuid clean=False ''' val = _dmidecoder('-s {0}'.format(string)).strip() # Cleanup possible comments in strings. val = '\n'.join([v for v in val.split('\n') if not v.startswith('#')]) if val.startswith('/dev/mem') or clean and not _dmi_isclean(string, val): val = None return val def records(rec_type=None, fields=None, clean=True): ''' Return DMI records from SMBIOS type Return only records of type(s) The SMBIOS specification defines the following DMI types: ==== ====================================== Type Information ==== ====================================== 0 BIOS 1 System 2 Baseboard 3 Chassis 4 Processor 5 Memory Controller 6 Memory Module 7 Cache 8 Port Connector 9 System Slots 10 On Board Devices 11 OEM Strings 12 System Configuration Options 13 BIOS Language 14 Group Associations 15 System Event Log 16 Physical Memory Array 17 Memory Device 18 32-bit Memory Error 19 Memory Array Mapped Address 20 Memory Device Mapped Address 21 Built-in Pointing Device 22 Portable Battery 23 System Reset 24 Hardware Security 25 System Power Controls 26 Voltage Probe 27 Cooling Device 28 Temperature Probe 29 Electrical Current Probe 30 Out-of-band Remote Access 31 Boot Integrity Services 32 System Boot 33 64-bit Memory Error 34 Management Device 35 Management Device Component 36 Management Device Threshold Data 37 Memory Channel 38 IPMI Device 39 Power Supply 40 Additional Information 41 Onboard Devices Extended Information 42 Management Controller Host Interface ==== ====================================== clean | Don't return well-known false information | (invalid UUID's, serial 000000000's, etcetera) | Defaults to ``True`` CLI Example: .. code-block:: bash salt '*' smbios.records clean=False salt '*' smbios.records 14 salt '*' smbios.records 4 core_count,thread_count,current_speed ''' if rec_type is None: smbios = _dmi_parse(_dmidecoder(), clean, fields) else: smbios = _dmi_parse(_dmidecoder('-t {0}'.format(rec_type)), clean, fields) return smbios def _dmi_parse(data, clean=True, fields=None): ''' Structurize DMI records into a nice list Optionally trash bogus entries and filter output ''' dmi = [] # Detect & split Handle records dmi_split = re.compile('(handle [0-9]x[0-9a-f]+[^\n]+)\n', re.MULTILINE+re.IGNORECASE) dmi_raw = iter(re.split(dmi_split, data)[1:]) for handle, dmi_raw in zip(dmi_raw, dmi_raw): handle, htype = [hline.split()[-1] for hline in handle.split(',')][0:2] dmi_raw = dmi_raw.split('\n') # log.debug('%s record contains %s', handle, dmi_raw) log.debug('Parsing handle %s', handle) # The first line of a handle is a description of the type record = { 'handle': handle, 'description': dmi_raw.pop(0).strip(), 'type': int(htype) } if not dmi_raw: # empty record if not clean: dmi.append(record) continue # log.debug('%s record contains %s', record, dmi_raw) dmi_data = _dmi_data(dmi_raw, clean, fields) if dmi_data: record['data'] = dmi_data dmi.append(record) elif not clean: dmi.append(record) return dmi def _dmi_data(dmi_raw, clean, fields): ''' Parse the raw DMIdecode output of a single handle into a nice dict ''' dmi_data = {} key = None key_data = [None, []] for line in dmi_raw: if re.match(r'\t[^\s]+', line): # Finish previous key if key is not None: # log.debug('Evaluating DMI key {0}: {1}'.format(key, key_data)) value, vlist = key_data if vlist: if value is not None: # On the rare occasion # (I counted 1 on all systems we have) # that there's both a value <and> a list # just insert the value on top of the list vlist.insert(0, value) dmi_data[key] = vlist elif value is not None: dmi_data[key] = value # Family: Core i5 # Keyboard Password Status: Not Implemented key, val = line.split(':', 1) key = key.strip().lower().replace(' ', '_') if (clean and key == 'header_and_data') \ or (fields and key not in fields): key = None continue else: key_data = [_dmi_cast(key, val.strip(), clean), []] elif key is None: continue elif re.match(r'\t\t[^\s]+', line): # Installable Languages: 1 # en-US # Characteristics: # PCI is supported # PNP is supported val = _dmi_cast(key, line.strip(), clean) if val is not None: # log.debug('DMI key %s gained list item %s', key, val) key_data[1].append(val) return dmi_data def _dmi_isclean(key, val): ''' Clean out well-known bogus values ''' if not val or re.match('none', val, flags=re.IGNORECASE): # log.debug('DMI {0} value {1} seems invalid or empty'.format(key, val)) return False elif 'uuid' in key: # Try each version (1-5) of RFC4122 to check if it's actually a UUID for uuidver in range(1, 5): try: uuid.UUID(val, version=uuidver) return True except ValueError: continue log.trace('DMI %s value %s is an invalid UUID', key, val.replace('\n', ' ')) return False elif re.search('serial|part|version', key): # 'To be filled by O.E.M. # 'Not applicable' etc. # 'Not specified' etc. # 0000000, 1234667 etc. # begone! return not re.match(r'^[0]+$', val) \ and not re.match(r'[0]?1234567[8]?[9]?[0]?', val) \ and not re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE) elif re.search('asset|manufacturer', key): # AssetTag0. Manufacturer04. Begone. return not re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE) else: # map unspecified, undefined, unknown & whatever to None return not re.search(r'to be filled', val, flags=re.IGNORECASE) \ and not re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)', val, flags=re.IGNORECASE) def _dmidecoder(args=None): ''' Call DMIdecode ''' dmidecoder = salt.utils.path.which_bin(['dmidecode', 'smbios']) if not args: out = salt.modules.cmdmod._run_quiet(dmidecoder) else: out = salt.modules.cmdmod._run_quiet('{0} {1}'.format(dmidecoder, args)) return out
saltstack/salt
salt/modules/smbios.py
_dmidecoder
python
def _dmidecoder(args=None): ''' Call DMIdecode ''' dmidecoder = salt.utils.path.which_bin(['dmidecode', 'smbios']) if not args: out = salt.modules.cmdmod._run_quiet(dmidecoder) else: out = salt.modules.cmdmod._run_quiet('{0} {1}'.format(dmidecoder, args)) return out
Call DMIdecode
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smbios.py#L316-L327
[ "def which_bin(exes):\n '''\n Scan over some possible executables and return the first one that is found\n '''\n if not isinstance(exes, Iterable):\n return None\n for exe in exes:\n path = which(exe)\n if not path:\n continue\n return path\n return None\n", "def _run_quiet(cmd,\n cwd=None,\n stdin=None,\n output_encoding=None,\n runas=None,\n shell=DEFAULT_SHELL,\n python_shell=False,\n env=None,\n template=None,\n umask=None,\n timeout=None,\n reset_system_locale=True,\n saltenv='base',\n pillarenv=None,\n pillar_override=None,\n success_retcodes=None,\n success_stdout=None,\n success_stderr=None):\n '''\n Helper for running commands quietly for minion startup\n '''\n return _run(cmd,\n runas=runas,\n cwd=cwd,\n stdin=stdin,\n stderr=subprocess.STDOUT,\n output_encoding=output_encoding,\n output_loglevel='quiet',\n log_callback=None,\n shell=shell,\n python_shell=python_shell,\n env=env,\n template=template,\n umask=umask,\n timeout=timeout,\n reset_system_locale=reset_system_locale,\n saltenv=saltenv,\n pillarenv=pillarenv,\n pillar_override=pillar_override,\n success_retcodes=success_retcodes,\n success_stdout=success_stdout,\n success_stderr=success_stderr)['stdout']\n" ]
# -*- coding: utf-8 -*- ''' Interface to SMBIOS/DMI (Parsing through dmidecode) External References ------------------- | `Desktop Management Interface (DMI) <http://www.dmtf.org/standards/dmi>`_ | `System Management BIOS <http://www.dmtf.org/standards/smbios>`_ | `DMIdecode <http://www.nongnu.org/dmidecode/>`_ ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging import uuid import re # Import salt libs import salt.utils.path # Solve the Chicken and egg problem where grains need to run before any # of the modules are loaded and are generally available for any usage. import salt.modules.cmdmod from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) def __virtual__(): ''' Only work when dmidecode is installed. ''' return (bool(salt.utils.path.which_bin(['dmidecode', 'smbios'])), 'The smbios execution module failed to load: neither dmidecode nor smbios in the path.') def get(string, clean=True): ''' Get an individual DMI string from SMBIOS info string The string to fetch. DMIdecode supports: - ``bios-vendor`` - ``bios-version`` - ``bios-release-date`` - ``system-manufacturer`` - ``system-product-name`` - ``system-version`` - ``system-serial-number`` - ``system-uuid`` - ``baseboard-manufacturer`` - ``baseboard-product-name`` - ``baseboard-version`` - ``baseboard-serial-number`` - ``baseboard-asset-tag`` - ``chassis-manufacturer`` - ``chassis-type`` - ``chassis-version`` - ``chassis-serial-number`` - ``chassis-asset-tag`` - ``processor-family`` - ``processor-manufacturer`` - ``processor-version`` - ``processor-frequency`` clean | Don't return well-known false information | (invalid UUID's, serial 000000000's, etcetera) | Defaults to ``True`` CLI Example: .. code-block:: bash salt '*' smbios.get system-uuid clean=False ''' val = _dmidecoder('-s {0}'.format(string)).strip() # Cleanup possible comments in strings. val = '\n'.join([v for v in val.split('\n') if not v.startswith('#')]) if val.startswith('/dev/mem') or clean and not _dmi_isclean(string, val): val = None return val def records(rec_type=None, fields=None, clean=True): ''' Return DMI records from SMBIOS type Return only records of type(s) The SMBIOS specification defines the following DMI types: ==== ====================================== Type Information ==== ====================================== 0 BIOS 1 System 2 Baseboard 3 Chassis 4 Processor 5 Memory Controller 6 Memory Module 7 Cache 8 Port Connector 9 System Slots 10 On Board Devices 11 OEM Strings 12 System Configuration Options 13 BIOS Language 14 Group Associations 15 System Event Log 16 Physical Memory Array 17 Memory Device 18 32-bit Memory Error 19 Memory Array Mapped Address 20 Memory Device Mapped Address 21 Built-in Pointing Device 22 Portable Battery 23 System Reset 24 Hardware Security 25 System Power Controls 26 Voltage Probe 27 Cooling Device 28 Temperature Probe 29 Electrical Current Probe 30 Out-of-band Remote Access 31 Boot Integrity Services 32 System Boot 33 64-bit Memory Error 34 Management Device 35 Management Device Component 36 Management Device Threshold Data 37 Memory Channel 38 IPMI Device 39 Power Supply 40 Additional Information 41 Onboard Devices Extended Information 42 Management Controller Host Interface ==== ====================================== clean | Don't return well-known false information | (invalid UUID's, serial 000000000's, etcetera) | Defaults to ``True`` CLI Example: .. code-block:: bash salt '*' smbios.records clean=False salt '*' smbios.records 14 salt '*' smbios.records 4 core_count,thread_count,current_speed ''' if rec_type is None: smbios = _dmi_parse(_dmidecoder(), clean, fields) else: smbios = _dmi_parse(_dmidecoder('-t {0}'.format(rec_type)), clean, fields) return smbios def _dmi_parse(data, clean=True, fields=None): ''' Structurize DMI records into a nice list Optionally trash bogus entries and filter output ''' dmi = [] # Detect & split Handle records dmi_split = re.compile('(handle [0-9]x[0-9a-f]+[^\n]+)\n', re.MULTILINE+re.IGNORECASE) dmi_raw = iter(re.split(dmi_split, data)[1:]) for handle, dmi_raw in zip(dmi_raw, dmi_raw): handle, htype = [hline.split()[-1] for hline in handle.split(',')][0:2] dmi_raw = dmi_raw.split('\n') # log.debug('%s record contains %s', handle, dmi_raw) log.debug('Parsing handle %s', handle) # The first line of a handle is a description of the type record = { 'handle': handle, 'description': dmi_raw.pop(0).strip(), 'type': int(htype) } if not dmi_raw: # empty record if not clean: dmi.append(record) continue # log.debug('%s record contains %s', record, dmi_raw) dmi_data = _dmi_data(dmi_raw, clean, fields) if dmi_data: record['data'] = dmi_data dmi.append(record) elif not clean: dmi.append(record) return dmi def _dmi_data(dmi_raw, clean, fields): ''' Parse the raw DMIdecode output of a single handle into a nice dict ''' dmi_data = {} key = None key_data = [None, []] for line in dmi_raw: if re.match(r'\t[^\s]+', line): # Finish previous key if key is not None: # log.debug('Evaluating DMI key {0}: {1}'.format(key, key_data)) value, vlist = key_data if vlist: if value is not None: # On the rare occasion # (I counted 1 on all systems we have) # that there's both a value <and> a list # just insert the value on top of the list vlist.insert(0, value) dmi_data[key] = vlist elif value is not None: dmi_data[key] = value # Family: Core i5 # Keyboard Password Status: Not Implemented key, val = line.split(':', 1) key = key.strip().lower().replace(' ', '_') if (clean and key == 'header_and_data') \ or (fields and key not in fields): key = None continue else: key_data = [_dmi_cast(key, val.strip(), clean), []] elif key is None: continue elif re.match(r'\t\t[^\s]+', line): # Installable Languages: 1 # en-US # Characteristics: # PCI is supported # PNP is supported val = _dmi_cast(key, line.strip(), clean) if val is not None: # log.debug('DMI key %s gained list item %s', key, val) key_data[1].append(val) return dmi_data def _dmi_cast(key, val, clean=True): ''' Simple caster thingy for trying to fish out at least ints & lists from strings ''' if clean and not _dmi_isclean(key, val): return elif not re.match(r'serial|part|asset|product', key, flags=re.IGNORECASE): if ',' in val: val = [el.strip() for el in val.split(',')] else: try: val = int(val) except Exception: pass return val def _dmi_isclean(key, val): ''' Clean out well-known bogus values ''' if not val or re.match('none', val, flags=re.IGNORECASE): # log.debug('DMI {0} value {1} seems invalid or empty'.format(key, val)) return False elif 'uuid' in key: # Try each version (1-5) of RFC4122 to check if it's actually a UUID for uuidver in range(1, 5): try: uuid.UUID(val, version=uuidver) return True except ValueError: continue log.trace('DMI %s value %s is an invalid UUID', key, val.replace('\n', ' ')) return False elif re.search('serial|part|version', key): # 'To be filled by O.E.M. # 'Not applicable' etc. # 'Not specified' etc. # 0000000, 1234667 etc. # begone! return not re.match(r'^[0]+$', val) \ and not re.match(r'[0]?1234567[8]?[9]?[0]?', val) \ and not re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE) elif re.search('asset|manufacturer', key): # AssetTag0. Manufacturer04. Begone. return not re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE) else: # map unspecified, undefined, unknown & whatever to None return not re.search(r'to be filled', val, flags=re.IGNORECASE) \ and not re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)', val, flags=re.IGNORECASE)
saltstack/salt
salt/utils/yamlloader.py
SaltYamlSafeLoader.construct_mapping
python
def construct_mapping(self, node, deep=False): ''' Build the mapping for YAML ''' if not isinstance(node, MappingNode): raise ConstructorError( None, None, 'expected a mapping node, but found {0}'.format(node.id), node.start_mark) self.flatten_mapping(node) context = 'while constructing a mapping' mapping = self.dictclass() for key_node, value_node in node.value: key = self.construct_object(key_node, deep=deep) try: hash(key) except TypeError: raise ConstructorError( context, node.start_mark, "found unacceptable key {0}".format(key_node.value), key_node.start_mark) value = self.construct_object(value_node, deep=deep) if key in mapping: raise ConstructorError( context, node.start_mark, "found conflicting ID '{0}'".format(key), key_node.start_mark) mapping[key] = value return mapping
Build the mapping for YAML
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/yamlloader.py#L72-L105
null
class SaltYamlSafeLoader(yaml.SafeLoader): ''' Create a custom YAML loader that uses the custom constructor. This allows for the YAML loading defaults to be manipulated based on needs within salt to make things like sls file more intuitive. ''' def __init__(self, stream, dictclass=dict): super(SaltYamlSafeLoader, self).__init__(stream) if dictclass is not dict: # then assume ordered dict and use it for both !map and !omap self.add_constructor( 'tag:yaml.org,2002:map', type(self).construct_yaml_map) self.add_constructor( 'tag:yaml.org,2002:omap', type(self).construct_yaml_map) self.add_constructor( 'tag:yaml.org,2002:str', type(self).construct_yaml_str) self.add_constructor( 'tag:yaml.org,2002:python/unicode', type(self).construct_unicode) self.add_constructor( 'tag:yaml.org,2002:timestamp', type(self).construct_scalar) self.dictclass = dictclass def construct_yaml_map(self, node): data = self.dictclass() yield data value = self.construct_mapping(node) data.update(value) def construct_unicode(self, node): return node.value def construct_scalar(self, node): ''' Verify integers and pass them in correctly is they are declared as octal ''' if node.tag == 'tag:yaml.org,2002:int': if node.value == '0': pass elif node.value.startswith('0') and not node.value.startswith(('0b', '0x')): node.value = node.value.lstrip('0') # If value was all zeros, node.value would have been reduced to # an empty string. Change it to '0'. if node.value == '': node.value = '0' return super(SaltYamlSafeLoader, self).construct_scalar(node) def construct_yaml_str(self, node): value = self.construct_scalar(node) return salt.utils.stringutils.to_unicode(value) def flatten_mapping(self, node): merge = [] index = 0 while index < len(node.value): key_node, value_node = node.value[index] if key_node.tag == 'tag:yaml.org,2002:merge': del node.value[index] if isinstance(value_node, MappingNode): self.flatten_mapping(value_node) merge.extend(value_node.value) elif isinstance(value_node, SequenceNode): submerge = [] for subnode in value_node.value: if not isinstance(subnode, MappingNode): raise ConstructorError("while constructing a mapping", node.start_mark, "expected a mapping for merging, but found {0}".format(subnode.id), subnode.start_mark) self.flatten_mapping(subnode) submerge.append(subnode.value) submerge.reverse() for value in submerge: merge.extend(value) else: raise ConstructorError("while constructing a mapping", node.start_mark, "expected a mapping or list of mappings for merging, but found {0}".format(value_node.id), value_node.start_mark) elif key_node.tag == 'tag:yaml.org,2002:value': key_node.tag = 'tag:yaml.org,2002:str' index += 1 else: index += 1 if merge: # Here we need to discard any duplicate entries based on key_node existing_nodes = [name_node.value for name_node, value_node in node.value] mergeable_items = [x for x in merge if x[0].value not in existing_nodes] node.value = mergeable_items + node.value
saltstack/salt
salt/utils/yamlloader.py
SaltYamlSafeLoader.construct_scalar
python
def construct_scalar(self, node): ''' Verify integers and pass them in correctly is they are declared as octal ''' if node.tag == 'tag:yaml.org,2002:int': if node.value == '0': pass elif node.value.startswith('0') and not node.value.startswith(('0b', '0x')): node.value = node.value.lstrip('0') # If value was all zeros, node.value would have been reduced to # an empty string. Change it to '0'. if node.value == '': node.value = '0' return super(SaltYamlSafeLoader, self).construct_scalar(node)
Verify integers and pass them in correctly is they are declared as octal
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/yamlloader.py#L107-L121
null
class SaltYamlSafeLoader(yaml.SafeLoader): ''' Create a custom YAML loader that uses the custom constructor. This allows for the YAML loading defaults to be manipulated based on needs within salt to make things like sls file more intuitive. ''' def __init__(self, stream, dictclass=dict): super(SaltYamlSafeLoader, self).__init__(stream) if dictclass is not dict: # then assume ordered dict and use it for both !map and !omap self.add_constructor( 'tag:yaml.org,2002:map', type(self).construct_yaml_map) self.add_constructor( 'tag:yaml.org,2002:omap', type(self).construct_yaml_map) self.add_constructor( 'tag:yaml.org,2002:str', type(self).construct_yaml_str) self.add_constructor( 'tag:yaml.org,2002:python/unicode', type(self).construct_unicode) self.add_constructor( 'tag:yaml.org,2002:timestamp', type(self).construct_scalar) self.dictclass = dictclass def construct_yaml_map(self, node): data = self.dictclass() yield data value = self.construct_mapping(node) data.update(value) def construct_unicode(self, node): return node.value def construct_mapping(self, node, deep=False): ''' Build the mapping for YAML ''' if not isinstance(node, MappingNode): raise ConstructorError( None, None, 'expected a mapping node, but found {0}'.format(node.id), node.start_mark) self.flatten_mapping(node) context = 'while constructing a mapping' mapping = self.dictclass() for key_node, value_node in node.value: key = self.construct_object(key_node, deep=deep) try: hash(key) except TypeError: raise ConstructorError( context, node.start_mark, "found unacceptable key {0}".format(key_node.value), key_node.start_mark) value = self.construct_object(value_node, deep=deep) if key in mapping: raise ConstructorError( context, node.start_mark, "found conflicting ID '{0}'".format(key), key_node.start_mark) mapping[key] = value return mapping def construct_yaml_str(self, node): value = self.construct_scalar(node) return salt.utils.stringutils.to_unicode(value) def flatten_mapping(self, node): merge = [] index = 0 while index < len(node.value): key_node, value_node = node.value[index] if key_node.tag == 'tag:yaml.org,2002:merge': del node.value[index] if isinstance(value_node, MappingNode): self.flatten_mapping(value_node) merge.extend(value_node.value) elif isinstance(value_node, SequenceNode): submerge = [] for subnode in value_node.value: if not isinstance(subnode, MappingNode): raise ConstructorError("while constructing a mapping", node.start_mark, "expected a mapping for merging, but found {0}".format(subnode.id), subnode.start_mark) self.flatten_mapping(subnode) submerge.append(subnode.value) submerge.reverse() for value in submerge: merge.extend(value) else: raise ConstructorError("while constructing a mapping", node.start_mark, "expected a mapping or list of mappings for merging, but found {0}".format(value_node.id), value_node.start_mark) elif key_node.tag == 'tag:yaml.org,2002:value': key_node.tag = 'tag:yaml.org,2002:str' index += 1 else: index += 1 if merge: # Here we need to discard any duplicate entries based on key_node existing_nodes = [name_node.value for name_node, value_node in node.value] mergeable_items = [x for x in merge if x[0].value not in existing_nodes] node.value = mergeable_items + node.value
saltstack/salt
salt/ext/ipaddress.py
ip_address
python
def ip_address(address): try: return IPv4Address(address) except (AddressValueError, NetmaskValueError): pass try: return IPv6Address(address) except (AddressValueError, NetmaskValueError): pass raise ValueError('%r does not appear to be an IPv4 or IPv6 address' % address)
Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Address or IPv6Address object. Raises: ValueError: if the *address* passed isn't either a v4 or a v6 address
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/ext/ipaddress.py#L93-L120
null
''' Python 2.[67] port of Python 3.4's ipaddress module Almost verbatim copy of the core lib, with compatibility changes Source: https://bitbucket.org/kwi/py2-ipaddress/ ''' # pylint: skip-file # List of compatibility changes: # Python 3 uses only new-style classes. # s/class \(\w\+\):/class \1(object):/ # Use iterator versions of map and range: from itertools import imap as map range = xrange # Except that xrange only supports machine integers, not longs, so... def long_range(start, end): while start < end: yield start start += 1 # This backport uses bytearray instead of bytes, as bytes is the same # as str in Python 2.7. bytes = bytearray # Python 2 does not support exception chaining. # s/ from None$// # When checking for instances of int, also allow Python 2's long. _builtin_isinstance = isinstance def isinstance(val, types): if types is int: types = (int, long) elif type(types) is tuple and int in types: types += (long,) return _builtin_isinstance(val, types) # functools.lru_cache is Python 3.2+ only. # /@functools.lru_cache()/d # int().to_bytes is Python 3.2+ only. # s/\(\w+\)\.to_bytes(/_int_to_bytes(\1, / def _int_to_bytes(self, length, byteorder, signed=False): assert byteorder == 'big' and signed is False if self < 0 or self >= 256**length: raise OverflowError() return bytearray(('%0*x' % (length * 2, self)).decode('hex')) # int.from_bytes is Python 3.2+ only. # s/int\.from_bytes(/_int_from_bytes(/g def _int_from_bytes(what, byteorder, signed=False): assert byteorder == 'big' and signed is False return int(str(bytearray(what)).encode('hex'), 16) # Python 2.6 has no int.bit_length() if hasattr(int, 'bit_length'): _int_bit_length = lambda i: i.bit_length() else: _int_bit_length = lambda i: len(bin(abs(i))) - 2 # ---------------------------------------------------------------------------- # Copyright 2007 Google Inc. # Licensed to PSF under a Contributor Agreement. """A fast, lightweight IPv4/IPv6 manipulation library in Python. This library is used to create/poke/manipulate IPv4 and IPv6 addresses and networks. """ __version__ = '1.0' import functools IPV4LENGTH = 32 IPV6LENGTH = 128 class AddressValueError(ValueError): """A Value Error related to the address.""" class NetmaskValueError(ValueError): """A Value Error related to the netmask.""" def ip_network(address, strict=True): """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP network. Either IPv4 or IPv6 networks may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Network or IPv6Network object. Raises: ValueError: if the string passed isn't either a v4 or a v6 address. Or if the network has host bits set. """ try: return IPv4Network(address, strict) except (AddressValueError, NetmaskValueError): pass try: return IPv6Network(address, strict) except (AddressValueError, NetmaskValueError): pass raise ValueError('%r does not appear to be an IPv4 or IPv6 network' % address) def ip_interface(address): """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Interface or IPv6Interface object. Raises: ValueError: if the string passed isn't either a v4 or a v6 address. Notes: The IPv?Interface classes describe an Address on a particular Network, so they're basically a combination of both the Address and Network classes. """ try: return IPv4Interface(address) except (AddressValueError, NetmaskValueError): pass try: return IPv6Interface(address) except (AddressValueError, NetmaskValueError): pass raise ValueError('%r does not appear to be an IPv4 or IPv6 interface' % address) def v4_int_to_packed(address): """Represent an address as 4 packed bytes in network (big-endian) order. Args: address: An integer representation of an IPv4 IP address. Returns: The integer address packed as 4 bytes in network (big-endian) order. Raises: ValueError: If the integer is negative or too large to be an IPv4 IP address. """ try: return _int_to_bytes(address, 4, 'big') except Exception: raise ValueError("Address negative or too large for IPv4") def v6_int_to_packed(address): """Represent an address as 16 packed bytes in network (big-endian) order. Args: address: An integer representation of an IPv6 IP address. Returns: The integer address packed as 16 bytes in network (big-endian) order. """ try: return _int_to_bytes(address, 16, 'big') except Exception: raise ValueError("Address negative or too large for IPv6") def _split_optional_netmask(address): """Helper to split the netmask and raise AddressValueError if needed""" addr = str(address).split('/') if len(addr) > 2: raise AddressValueError("Only one '/' permitted in %r" % address) return addr def _find_address_range(addresses): """Find a sequence of IPv#Address. Args: addresses: a list of IPv#Address objects. Returns: A tuple containing the first and last IP addresses in the sequence. """ first = last = addresses[0] for ip in addresses[1:]: if ip._ip == last._ip + 1: last = ip else: break return (first, last) def _count_righthand_zero_bits(number, bits): """Count the number of zero bits on the right hand side. Args: number: an integer. bits: maximum number of bits to count. Returns: The number of zero bits on the right hand side of the number. """ if number == 0: return bits for i in range(bits): if (number >> i) & 1: return i # All bits of interest were zero, even if there are more in the number return bits def summarize_address_range(first, last): """Summarize a network range given the first and last IP addresses. Example: >>> list(summarize_address_range(IPv4Address('192.0.2.0'), ... IPv4Address('192.0.2.130'))) ... #doctest: +NORMALIZE_WHITESPACE [IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/31'), IPv4Network('192.0.2.130/32')] Args: first: the first IPv4Address or IPv6Address in the range. last: the last IPv4Address or IPv6Address in the range. Returns: An iterator of the summarized IPv(4|6) network objects. Raise: TypeError: If the first and last objects are not IP addresses. If the first and last objects are not the same version. ValueError: If the last object is not greater than the first. If the version of the first address is not 4 or 6. """ if (not (isinstance(first, _BaseAddress) and isinstance(last, _BaseAddress))): raise TypeError('first and last must be IP addresses, not networks') if first.version != last.version: raise TypeError("%s and %s are not of the same version" % ( first, last)) if first > last: raise ValueError('last IP address must be greater than first') if first.version == 4: ip = IPv4Network elif first.version == 6: ip = IPv6Network else: raise ValueError('unknown IP version') ip_bits = first._max_prefixlen first_int = first._ip last_int = last._ip while first_int <= last_int: nbits = min(_count_righthand_zero_bits(first_int, ip_bits), _int_bit_length(last_int - first_int + 1) - 1) net = ip('%s/%d' % (first, ip_bits - nbits)) yield net first_int += 1 << nbits if first_int - 1 == ip._ALL_ONES: break first = first.__class__(first_int) def _collapse_addresses_recursive(addresses): """Loops through the addresses, collapsing concurrent netblocks. Example: ip1 = IPv4Network('192.0.2.0/26') ip2 = IPv4Network('192.0.2.64/26') ip3 = IPv4Network('192.0.2.128/26') ip4 = IPv4Network('192.0.2.192/26') _collapse_addresses_recursive([ip1, ip2, ip3, ip4]) -> [IPv4Network('192.0.2.0/24')] This shouldn't be called directly; it is called via collapse_addresses([]). Args: addresses: A list of IPv4Network's or IPv6Network's Returns: A list of IPv4Network's or IPv6Network's depending on what we were passed. """ while True: last_addr = None ret_array = [] optimized = False for cur_addr in addresses: if not ret_array: last_addr = cur_addr ret_array.append(cur_addr) elif (cur_addr.network_address >= last_addr.network_address and cur_addr.broadcast_address <= last_addr.broadcast_address): optimized = True elif cur_addr == list(last_addr.supernet().subnets())[1]: ret_array[-1] = last_addr = last_addr.supernet() optimized = True else: last_addr = cur_addr ret_array.append(cur_addr) addresses = ret_array if not optimized: return addresses def collapse_addresses(addresses): """Collapse a list of IP objects. Example: collapse_addresses([IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/25')]) -> [IPv4Network('192.0.2.0/24')] Args: addresses: An iterator of IPv4Network or IPv6Network objects. Returns: An iterator of the collapsed IPv(4|6)Network objects. Raises: TypeError: If passed a list of mixed version objects. """ i = 0 addrs = [] ips = [] nets = [] # split IP addresses and networks for ip in addresses: if isinstance(ip, _BaseAddress): if ips and ips[-1]._version != ip._version: raise TypeError("%s and %s are not of the same version" % ( ip, ips[-1])) ips.append(ip) elif ip._prefixlen == ip._max_prefixlen: if ips and ips[-1]._version != ip._version: raise TypeError("%s and %s are not of the same version" % ( ip, ips[-1])) try: ips.append(ip.ip) except AttributeError: ips.append(ip.network_address) else: if nets and nets[-1]._version != ip._version: raise TypeError("%s and %s are not of the same version" % ( ip, nets[-1])) nets.append(ip) # sort and dedup ips = sorted(set(ips)) nets = sorted(set(nets)) while i < len(ips): (first, last) = _find_address_range(ips[i:]) i = ips.index(last) + 1 addrs.extend(summarize_address_range(first, last)) return iter(_collapse_addresses_recursive(sorted( addrs + nets, key=_BaseNetwork._get_networks_key))) def get_mixed_type_key(obj): """Return a key suitable for sorting between networks and addresses. Address and Network objects are not sortable by default; they're fundamentally different so the expression IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24') doesn't make any sense. There are some times however, where you may wish to have ipaddress sort these for you anyway. If you need to do this, you can use this function as the key= argument to sorted(). Args: obj: either a Network or Address object. Returns: appropriate key. """ if isinstance(obj, _BaseNetwork): return obj._get_networks_key() elif isinstance(obj, _BaseAddress): return obj._get_address_key() return NotImplemented class _TotalOrderingMixin(object): # Helper that derives the other comparison operations from # __lt__ and __eq__ # We avoid functools.total_ordering because it doesn't handle # NotImplemented correctly yet (http://bugs.python.org/issue10042) def __eq__(self, other): raise NotImplementedError def __ne__(self, other): equal = self.__eq__(other) if equal is NotImplemented: return NotImplemented return not equal def __lt__(self, other): raise NotImplementedError def __le__(self, other): less = self.__lt__(other) if less is NotImplemented or not less: return self.__eq__(other) return less def __gt__(self, other): less = self.__lt__(other) if less is NotImplemented: return NotImplemented equal = self.__eq__(other) if equal is NotImplemented: return NotImplemented return not (less or equal) def __ge__(self, other): less = self.__lt__(other) if less is NotImplemented: return NotImplemented return not less class _IPAddressBase(_TotalOrderingMixin): """The mother class.""" @property def exploded(self): """Return the longhand version of the IP address as a string.""" return self._explode_shorthand_ip_string() @property def compressed(self): """Return the shorthand version of the IP address as a string.""" return str(self) @property def reverse_pointer(self): """The name of the reverse DNS pointer for the IP address, e.g.: >>> ipaddress.ip_address("127.0.0.1").reverse_pointer '1.0.0.127.in-addr.arpa' >>> ipaddress.ip_address("2001:db8::1").reverse_pointer '1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa' """ return self._reverse_pointer() @property def version(self): msg = '%200s has no version specified' % (type(self),) raise NotImplementedError(msg) def _check_int_address(self, address): if address < 0: msg = "%d (< 0) is not permitted as an IPv%d address" raise AddressValueError(msg % (address, self._version)) if address > self._ALL_ONES: msg = "%d (>= 2**%d) is not permitted as an IPv%d address" raise AddressValueError(msg % (address, self._max_prefixlen, self._version)) def _check_packed_address(self, address, expected_len): address_len = len(address) if address_len != expected_len: msg = "%r (len %d != %d) is not permitted as an IPv%d address" raise AddressValueError(msg % (address, address_len, expected_len, self._version)) def _ip_int_from_prefix(self, prefixlen): """Turn the prefix length into a bitwise netmask Args: prefixlen: An integer, the prefix length. Returns: An integer. """ return self._ALL_ONES ^ (self._ALL_ONES >> prefixlen) def _prefix_from_ip_int(self, ip_int): """Return prefix length from the bitwise netmask. Args: ip_int: An integer, the netmask in expanded bitwise format Returns: An integer, the prefix length. Raises: ValueError: If the input intermingles zeroes & ones """ trailing_zeroes = _count_righthand_zero_bits(ip_int, self._max_prefixlen) prefixlen = self._max_prefixlen - trailing_zeroes leading_ones = ip_int >> trailing_zeroes all_ones = (1 << prefixlen) - 1 if leading_ones != all_ones: byteslen = self._max_prefixlen // 8 details = _int_to_bytes(ip_int, byteslen, 'big') msg = 'Netmask pattern %r mixes zeroes & ones' raise ValueError(msg % details) return prefixlen def _report_invalid_netmask(self, netmask_str): msg = '%r is not a valid netmask' % netmask_str raise NetmaskValueError(msg) def _prefix_from_prefix_string(self, prefixlen_str): """Return prefix length from a numeric string Args: prefixlen_str: The string to be converted Returns: An integer, the prefix length. Raises: NetmaskValueError: If the input is not a valid netmask """ # int allows a leading +/- as well as surrounding whitespace, # so we ensure that isn't the case if not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str): self._report_invalid_netmask(prefixlen_str) try: prefixlen = int(prefixlen_str) except ValueError: self._report_invalid_netmask(prefixlen_str) if not (0 <= prefixlen <= self._max_prefixlen): self._report_invalid_netmask(prefixlen_str) return prefixlen def _prefix_from_ip_string(self, ip_str): """Turn a netmask/hostmask string into a prefix length Args: ip_str: The netmask/hostmask to be converted Returns: An integer, the prefix length. Raises: NetmaskValueError: If the input is not a valid netmask/hostmask """ # Parse the netmask/hostmask like an IP address. try: ip_int = self._ip_int_from_string(ip_str) except AddressValueError: self._report_invalid_netmask(ip_str) # Try matching a netmask (this would be /1*0*/ as a bitwise regexp). # Note that the two ambiguous cases (all-ones and all-zeroes) are # treated as netmasks. try: return self._prefix_from_ip_int(ip_int) except ValueError: pass # Invert the bits, and try matching a /0+1+/ hostmask instead. ip_int ^= self._ALL_ONES try: return self._prefix_from_ip_int(ip_int) except ValueError: self._report_invalid_netmask(ip_str) class _BaseAddress(_IPAddressBase): """A generic IP object. This IP class contains the version independent methods which are used by single IP addresses. """ def __init__(self, address): if (not isinstance(address, bytes) and '/' in str(address)): raise AddressValueError("Unexpected '/' in %r" % address) def __int__(self): return self._ip def __eq__(self, other): try: return (self._ip == other._ip and self._version == other._version) except AttributeError: return NotImplemented def __lt__(self, other): if self._version != other._version: raise TypeError('%s and %s are not of the same version' % ( self, other)) if not isinstance(other, _BaseAddress): raise TypeError('%s and %s are not of the same type' % ( self, other)) if self._ip != other._ip: return self._ip < other._ip return False # Shorthand for Integer addition and subtraction. This is not # meant to ever support addition/subtraction of addresses. def __add__(self, other): if not isinstance(other, int): return NotImplemented return self.__class__(int(self) + other) def __sub__(self, other): if not isinstance(other, int): return NotImplemented return self.__class__(int(self) - other) def __repr__(self): return '%s(%r)' % (self.__class__.__name__, str(self)) def __str__(self): return str(self._string_from_ip_int(self._ip)) def __hash__(self): return hash(hex(int(self._ip))) def _get_address_key(self): return (self._version, self) class _BaseNetwork(_IPAddressBase): """A generic IP network object. This IP class contains the version independent methods which are used by networks. """ def __init__(self, address): self._cache = {} def __repr__(self): return '%s(%r)' % (self.__class__.__name__, str(self)) def __str__(self): return '%s/%d' % (self.network_address, self.prefixlen) def hosts(self): """Generate Iterator over usable hosts in a network. This is like __iter__ except it doesn't return the network or broadcast addresses. """ network = int(self.network_address) broadcast = int(self.broadcast_address) for x in long_range(network + 1, broadcast): yield self._address_class(x) def __iter__(self): network = int(self.network_address) broadcast = int(self.broadcast_address) for x in long_range(network, broadcast + 1): yield self._address_class(x) def __getitem__(self, n): network = int(self.network_address) broadcast = int(self.broadcast_address) if n >= 0: if network + n > broadcast: raise IndexError return self._address_class(network + n) else: n += 1 if broadcast + n < network: raise IndexError return self._address_class(broadcast + n) def __lt__(self, other): if self._version != other._version: raise TypeError('%s and %s are not of the same version' % ( self, other)) if not isinstance(other, _BaseNetwork): raise TypeError('%s and %s are not of the same type' % ( self, other)) if self.network_address != other.network_address: return self.network_address < other.network_address if self.netmask != other.netmask: return self.netmask < other.netmask return False def __eq__(self, other): try: return (self._version == other._version and self.network_address == other.network_address and int(self.netmask) == int(other.netmask)) except AttributeError: return NotImplemented def __hash__(self): return hash(int(self.network_address) ^ int(self.netmask)) def __contains__(self, other): # always false if one is v4 and the other is v6. if self._version != other._version: return False # dealing with another network. if isinstance(other, _BaseNetwork): return False # dealing with another address else: # address return (int(self.network_address) <= int(other._ip) <= int(self.broadcast_address)) def overlaps(self, other): """Tell if self is partly contained in other.""" return self.network_address in other or ( self.broadcast_address in other or ( other.network_address in self or ( other.broadcast_address in self))) @property def broadcast_address(self): x = self._cache.get('broadcast_address') if x is None: x = self._address_class(int(self.network_address) | int(self.hostmask)) self._cache['broadcast_address'] = x return x @property def hostmask(self): x = self._cache.get('hostmask') if x is None: x = self._address_class(int(self.netmask) ^ self._ALL_ONES) self._cache['hostmask'] = x return x @property def with_prefixlen(self): return '%s/%d' % (self.network_address, self._prefixlen) @property def with_netmask(self): return '%s/%s' % (self.network_address, self.netmask) @property def with_hostmask(self): return '%s/%s' % (self.network_address, self.hostmask) @property def num_addresses(self): """Number of hosts in the current subnet.""" return int(self.broadcast_address) - int(self.network_address) + 1 @property def _address_class(self): # Returning bare address objects (rather than interfaces) allows for # more consistent behaviour across the network address, broadcast # address and individual host addresses. msg = '%200s has no associated address class' % (type(self),) raise NotImplementedError(msg) @property def prefixlen(self): return self._prefixlen def address_exclude(self, other): """Remove an address from a larger block. For example: addr1 = ip_network('192.0.2.0/28') addr2 = ip_network('192.0.2.1/32') addr1.address_exclude(addr2) = [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'), IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')] or IPv6: addr1 = ip_network('2001:db8::1/32') addr2 = ip_network('2001:db8::1/128') addr1.address_exclude(addr2) = [ip_network('2001:db8::1/128'), ip_network('2001:db8::2/127'), ip_network('2001:db8::4/126'), ip_network('2001:db8::8/125'), ... ip_network('2001:db8:8000::/33')] Args: other: An IPv4Network or IPv6Network object of the same type. Returns: An iterator of the IPv(4|6)Network objects which is self minus other. Raises: TypeError: If self and other are of differing address versions, or if other is not a network object. ValueError: If other is not completely contained by self. """ if not self._version == other._version: raise TypeError("%s and %s are not of the same version" % ( self, other)) if not isinstance(other, _BaseNetwork): raise TypeError("%s is not a network object" % other) if not (other.network_address >= self.network_address and other.broadcast_address <= self.broadcast_address): raise ValueError('%s not contained in %s' % (other, self)) if other == self: raise StopIteration # Make sure we're comparing the network of other. other = other.__class__('%s/%s' % (other.network_address, other.prefixlen)) s1, s2 = self.subnets() while s1 != other and s2 != other: if (other.network_address >= s1.network_address and other.broadcast_address <= s1.broadcast_address): yield s2 s1, s2 = s1.subnets() elif (other.network_address >= s2.network_address and other.broadcast_address <= s2.broadcast_address): yield s1 s1, s2 = s2.subnets() else: # If we got here, there's a bug somewhere. raise AssertionError('Error performing exclusion: ' 's1: %s s2: %s other: %s' % (s1, s2, other)) if s1 == other: yield s2 elif s2 == other: yield s1 else: # If we got here, there's a bug somewhere. raise AssertionError('Error performing exclusion: ' 's1: %s s2: %s other: %s' % (s1, s2, other)) def compare_networks(self, other): """Compare two IP objects. This is only concerned about the comparison of the integer representation of the network addresses. This means that the host bits aren't considered at all in this method. If you want to compare host bits, you can easily enough do a 'HostA._ip < HostB._ip' Args: other: An IP object. Returns: If the IP versions of self and other are the same, returns: -1 if self < other: eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25') IPv6Network('2001:db8::1000/124') < IPv6Network('2001:db8::2000/124') 0 if self == other eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24') IPv6Network('2001:db8::1000/124') == IPv6Network('2001:db8::1000/124') 1 if self > other eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25') IPv6Network('2001:db8::2000/124') > IPv6Network('2001:db8::1000/124') Raises: TypeError if the IP versions are different. """ # does this need to raise a ValueError? if self._version != other._version: raise TypeError('%s and %s are not of the same type' % ( self, other)) # self._version == other._version below here: if self.network_address < other.network_address: return -1 if self.network_address > other.network_address: return 1 # self.network_address == other.network_address below here: if self.netmask < other.netmask: return -1 if self.netmask > other.netmask: return 1 return 0 def _get_networks_key(self): """Network-only key function. Returns an object that identifies this address' network and netmask. This function is a suitable "key" argument for sorted() and list.sort(). """ return (self._version, self.network_address, self.netmask) def subnets(self, prefixlen_diff=1, new_prefix=None): """The subnets which join to make the current subnet. In the case that self contains only one IP (self._prefixlen == 32 for IPv4 or self._prefixlen == 128 for IPv6), yield an iterator with just ourself. Args: prefixlen_diff: An integer, the amount the prefix length should be increased by. This should not be set if new_prefix is also set. new_prefix: The desired new prefix length. This must be a larger number (smaller prefix) than the existing prefix. This should not be set if prefixlen_diff is also set. Returns: An iterator of IPv(4|6) objects. Raises: ValueError: The prefixlen_diff is too small or too large. OR prefixlen_diff and new_prefix are both set or new_prefix is a smaller number than the current prefix (smaller number means a larger network) """ if self._prefixlen == self._max_prefixlen: yield self return if new_prefix is not None: if new_prefix < self._prefixlen: raise ValueError('new prefix must be longer') if prefixlen_diff != 1: raise ValueError('cannot set prefixlen_diff and new_prefix') prefixlen_diff = new_prefix - self._prefixlen if prefixlen_diff < 0: raise ValueError('prefix length diff must be > 0') new_prefixlen = self._prefixlen + prefixlen_diff if new_prefixlen > self._max_prefixlen: raise ValueError( 'prefix length diff %d is invalid for netblock %s' % ( new_prefixlen, self)) first = self.__class__('%s/%s' % (self.network_address, self._prefixlen + prefixlen_diff)) yield first current = first while True: broadcast = current.broadcast_address if broadcast == self.broadcast_address: return new_addr = self._address_class(int(broadcast) + 1) current = self.__class__('%s/%s' % (new_addr, new_prefixlen)) yield current def supernet(self, prefixlen_diff=1, new_prefix=None): """The supernet containing the current network. Args: prefixlen_diff: An integer, the amount the prefix length of the network should be decreased by. For example, given a /24 network and a prefixlen_diff of 3, a supernet with a /21 netmask is returned. Returns: An IPv4 network object. Raises: ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have a negative prefix length. OR If prefixlen_diff and new_prefix are both set or new_prefix is a larger number than the current prefix (larger number means a smaller network) """ if self._prefixlen == 0: return self if new_prefix is not None: if new_prefix > self._prefixlen: raise ValueError('new prefix must be shorter') if prefixlen_diff != 1: raise ValueError('cannot set prefixlen_diff and new_prefix') prefixlen_diff = self._prefixlen - new_prefix if self.prefixlen - prefixlen_diff < 0: raise ValueError( 'current prefixlen is %d, cannot have a prefixlen_diff of %d' % (self.prefixlen, prefixlen_diff)) # TODO (pmoody): optimize this. t = self.__class__('%s/%d' % (self.network_address, self.prefixlen - prefixlen_diff), strict=False) return t.__class__('%s/%d' % (t.network_address, t.prefixlen)) @property def is_multicast(self): """Test if the address is reserved for multicast use. Returns: A boolean, True if the address is a multicast address. See RFC 2373 2.7 for details. """ return (self.network_address.is_multicast and self.broadcast_address.is_multicast) @property def is_reserved(self): """Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within one of the reserved IPv6 Network ranges. """ return (self.network_address.is_reserved and self.broadcast_address.is_reserved) @property def is_link_local(self): """Test if the address is reserved for link-local. Returns: A boolean, True if the address is reserved per RFC 4291. """ return (self.network_address.is_link_local and self.broadcast_address.is_link_local) @property def is_private(self): """Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per iana-ipv4-special-registry or iana-ipv6-special-registry. """ return (self.network_address.is_private and self.broadcast_address.is_private) @property def is_global(self): """Test if this address is allocated for public networks. Returns: A boolean, True if the address is not reserved per iana-ipv4-special-registry or iana-ipv6-special-registry. """ return not self.is_private @property def is_unspecified(self): """Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in RFC 2373 2.5.2. """ return (self.network_address.is_unspecified and self.broadcast_address.is_unspecified) @property def is_loopback(self): """Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback address as defined in RFC 2373 2.5.3. """ return (self.network_address.is_loopback and self.broadcast_address.is_loopback) class _BaseV4(object): """Base IPv4 object. The following methods are used by IPv4 objects in both single IP addresses and networks. """ # Equivalent to 255.255.255.255 or 32 bits of 1's. _ALL_ONES = (2**IPV4LENGTH) - 1 _DECIMAL_DIGITS = frozenset('0123456789') # the valid octets for host and netmasks. only useful for IPv4. _valid_mask_octets = frozenset((255, 254, 252, 248, 240, 224, 192, 128, 0)) def __init__(self, address): self._version = 4 self._max_prefixlen = IPV4LENGTH def _explode_shorthand_ip_string(self): return str(self) def _ip_int_from_string(self, ip_str): """Turn the given IP string into an integer for comparison. Args: ip_str: A string, the IP ip_str. Returns: The IP ip_str as an integer. Raises: AddressValueError: if ip_str isn't a valid IPv4 Address. """ if not ip_str: raise AddressValueError('Address cannot be empty') octets = ip_str.split('.') if len(octets) != 4: raise AddressValueError("Expected 4 octets in %r" % ip_str) try: return _int_from_bytes(map(self._parse_octet, octets), 'big') except ValueError as exc: raise AddressValueError("%s in %r" % (exc, ip_str)) def _parse_octet(self, octet_str): """Convert a decimal octet into an integer. Args: octet_str: A string, the number to parse. Returns: The octet as an integer. Raises: ValueError: if the octet isn't strictly a decimal from [0..255]. """ if not octet_str: raise ValueError("Empty octet not permitted") # Whitelist the characters, since int() allows a lot of bizarre stuff. if not self._DECIMAL_DIGITS.issuperset(octet_str): msg = "Only decimal digits permitted in %r" raise ValueError(msg % octet_str) # We do the length check second, since the invalid character error # is likely to be more informative for the user if len(octet_str) > 3: msg = "At most 3 characters permitted in %r" raise ValueError(msg % octet_str) # Convert to integer (we know digits are legal) octet_int = int(octet_str, 10) # Any octets that look like they *might* be written in octal, # and which don't look exactly the same in both octal and # decimal are rejected as ambiguous if octet_int > 7 and octet_str[0] == '0': msg = "Ambiguous (octal/decimal) value in %r not permitted" raise ValueError(msg % octet_str) if octet_int > 255: raise ValueError("Octet %d (> 255) not permitted" % octet_int) return octet_int def _string_from_ip_int(self, ip_int): """Turns a 32-bit integer into dotted decimal notation. Args: ip_int: An integer, the IP address. Returns: The IP address as a string in dotted decimal notation. """ return '.'.join(map(str, _int_to_bytes(ip_int, 4, 'big'))) def _is_valid_netmask(self, netmask): """Verify that the netmask is valid. Args: netmask: A string, either a prefix or dotted decimal netmask. Returns: A boolean, True if the prefix represents a valid IPv4 netmask. """ mask = netmask.split('.') if len(mask) == 4: try: for x in mask: if int(x) not in self._valid_mask_octets: return False except ValueError: # Found something that isn't an integer or isn't valid return False for idx, y in enumerate(mask): if idx > 0 and y > mask[idx - 1]: return False return True try: netmask = int(netmask) except ValueError: return False return 0 <= netmask <= self._max_prefixlen def _is_hostmask(self, ip_str): """Test if the IP string is a hostmask (rather than a netmask). Args: ip_str: A string, the potential hostmask. Returns: A boolean, True if the IP string is a hostmask. """ bits = ip_str.split('.') try: parts = [x for x in map(int, bits) if x in self._valid_mask_octets] except ValueError: return False if len(parts) != len(bits): return False if parts[0] < parts[-1]: return True return False def _reverse_pointer(self): """Return the reverse DNS pointer name for the IPv4 address. This implements the method described in RFC1035 3.5. """ reverse_octets = str(self).split('.')[::-1] return '.'.join(reverse_octets) + '.in-addr.arpa' @property def max_prefixlen(self): return self._max_prefixlen @property def version(self): return self._version class IPv4Address(_BaseV4, _BaseAddress): """Represent and manipulate single IPv4 Addresses.""" def __init__(self, address): """ Args: address: A string or integer representing the IP Additionally, an integer can be passed, so IPv4Address('192.0.2.1') == IPv4Address(3221225985). or, more generally IPv4Address(int(IPv4Address('192.0.2.1'))) == IPv4Address('192.0.2.1') Raises: AddressValueError: If ipaddress isn't a valid IPv4 address. """ _BaseAddress.__init__(self, address) _BaseV4.__init__(self, address) # Efficient constructor from integer. if isinstance(address, int): self._check_int_address(address) self._ip = address return # Constructing from a packed address if isinstance(address, bytes): self._check_packed_address(address, 4) self._ip = _int_from_bytes(address, 'big') return # Assume input argument to be string or any object representation # which converts into a formatted IP string. addr_str = str(address) self._ip = self._ip_int_from_string(addr_str) @property def packed(self): """The binary representation of this address.""" return v4_int_to_packed(self._ip) @property def is_reserved(self): """Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within the reserved IPv4 Network range. """ reserved_network = IPv4Network('240.0.0.0/4') return self in reserved_network @property def is_private(self): """Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per iana-ipv4-special-registry. """ return (self in IPv4Network('0.0.0.0/8') or self in IPv4Network('10.0.0.0/8') or self in IPv4Network('127.0.0.0/8') or self in IPv4Network('169.254.0.0/16') or self in IPv4Network('172.16.0.0/12') or self in IPv4Network('192.0.0.0/29') or self in IPv4Network('192.0.0.170/31') or self in IPv4Network('192.0.2.0/24') or self in IPv4Network('192.168.0.0/16') or self in IPv4Network('198.18.0.0/15') or self in IPv4Network('198.51.100.0/24') or self in IPv4Network('203.0.113.0/24') or self in IPv4Network('240.0.0.0/4') or self in IPv4Network('255.255.255.255/32')) @property def is_multicast(self): """Test if the address is reserved for multicast use. Returns: A boolean, True if the address is multicast. See RFC 3171 for details. """ multicast_network = IPv4Network('224.0.0.0/4') return self in multicast_network @property def is_unspecified(self): """Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in RFC 5735 3. """ unspecified_address = IPv4Address('0.0.0.0') return self == unspecified_address @property def is_loopback(self): """Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback per RFC 3330. """ loopback_network = IPv4Network('127.0.0.0/8') return self in loopback_network @property def is_link_local(self): """Test if the address is reserved for link-local. Returns: A boolean, True if the address is link-local per RFC 3927. """ linklocal_network = IPv4Network('169.254.0.0/16') return self in linklocal_network class IPv4Interface(IPv4Address): def __init__(self, address): if isinstance(address, (bytes, int)): IPv4Address.__init__(self, address) self.network = IPv4Network(self._ip) self._prefixlen = self._max_prefixlen return addr = _split_optional_netmask(address) IPv4Address.__init__(self, addr[0]) self.network = IPv4Network(address, strict=False) self._prefixlen = self.network._prefixlen self.netmask = self.network.netmask self.hostmask = self.network.hostmask def __str__(self): return '%s/%d' % (self._string_from_ip_int(self._ip), self.network.prefixlen) def __eq__(self, other): address_equal = IPv4Address.__eq__(self, other) if not address_equal or address_equal is NotImplemented: return address_equal try: return self.network == other.network except AttributeError: # An interface with an associated network is NOT the # same as an unassociated address. That's why the hash # takes the extra info into account. return False def __lt__(self, other): address_less = IPv4Address.__lt__(self, other) if address_less is NotImplemented: return NotImplemented try: return self.network < other.network except AttributeError: # We *do* allow addresses and interfaces to be sorted. The # unassociated address is considered less than all interfaces. return False def __hash__(self): return self._ip ^ self._prefixlen ^ int(self.network.network_address) @property def ip(self): return IPv4Address(self._ip) @property def with_prefixlen(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self._prefixlen) @property def with_netmask(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self.netmask) @property def with_hostmask(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self.hostmask) class IPv4Network(_BaseV4, _BaseNetwork): """This class represents and manipulates 32-bit IPv4 network + addresses.. Attributes: [examples for IPv4Network('192.0.2.0/27')] .network_address: IPv4Address('192.0.2.0') .hostmask: IPv4Address('0.0.0.31') .broadcast_address: IPv4Address('192.0.2.32') .netmask: IPv4Address('255.255.255.224') .prefixlen: 27 """ # Class to use when creating address objects _address_class = IPv4Address def __init__(self, address, strict=True): """Instantiate a new IPv4 network object. Args: address: A string or integer representing the IP [& network]. '192.0.2.0/24' '192.0.2.0/255.255.255.0' '192.0.0.2/0.0.0.255' are all functionally the same in IPv4. Similarly, '192.0.2.1' '192.0.2.1/255.255.255.255' '192.0.2.1/32' are also functionally equivalent. That is to say, failing to provide a subnetmask will create an object with a mask of /32. If the mask (portion after the / in the argument) is given in dotted quad form, it is treated as a netmask if it starts with a non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it starts with a zero field (e.g. 0.255.255.255 == /8), with the single exception of an all-zero mask which is treated as a netmask == /0. If no mask is given, a default of /32 is used. Additionally, an integer can be passed, so IPv4Network('192.0.2.1') == IPv4Network(3221225985) or, more generally IPv4Interface(int(IPv4Interface('192.0.2.1'))) == IPv4Interface('192.0.2.1') Raises: AddressValueError: If ipaddress isn't a valid IPv4 address. NetmaskValueError: If the netmask isn't valid for an IPv4 address. ValueError: If strict is True and a network address is not supplied. """ _BaseV4.__init__(self, address) _BaseNetwork.__init__(self, address) # Constructing from a packed address if isinstance(address, bytes): self.network_address = IPv4Address(address) self._prefixlen = self._max_prefixlen self.netmask = IPv4Address(self._ALL_ONES) #fixme: address/network test here return # Efficient constructor from integer. if isinstance(address, int): self.network_address = IPv4Address(address) self._prefixlen = self._max_prefixlen self.netmask = IPv4Address(self._ALL_ONES) #fixme: address/network test here. return # Assume input argument to be string or any object representation # which converts into a formatted IP prefix string. addr = _split_optional_netmask(address) self.network_address = IPv4Address(self._ip_int_from_string(addr[0])) if len(addr) == 2: try: # Check for a netmask in prefix length form self._prefixlen = self._prefix_from_prefix_string(addr[1]) except NetmaskValueError: # Check for a netmask or hostmask in dotted-quad form. # This may raise NetmaskValueError. self._prefixlen = self._prefix_from_ip_string(addr[1]) else: self._prefixlen = self._max_prefixlen self.netmask = IPv4Address(self._ip_int_from_prefix(self._prefixlen)) if strict: if (IPv4Address(int(self.network_address) & int(self.netmask)) != self.network_address): raise ValueError('%s has host bits set' % self) self.network_address = IPv4Address(int(self.network_address) & int(self.netmask)) if self._prefixlen == (self._max_prefixlen - 1): self.hosts = self.__iter__ @property def is_global(self): """Test if this address is allocated for public networks. Returns: A boolean, True if the address is not reserved per iana-ipv4-special-registry. """ return (not (self.network_address in IPv4Network('100.64.0.0/10') and self.broadcast_address in IPv4Network('100.64.0.0/10')) and not self.is_private) class _BaseV6(object): """Base IPv6 object. The following methods are used by IPv6 objects in both single IP addresses and networks. """ _ALL_ONES = (2**IPV6LENGTH) - 1 _HEXTET_COUNT = 8 _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef') def __init__(self, address): self._version = 6 self._max_prefixlen = IPV6LENGTH def _ip_int_from_string(self, ip_str): """Turn an IPv6 ip_str into an integer. Args: ip_str: A string, the IPv6 ip_str. Returns: An int, the IPv6 address Raises: AddressValueError: if ip_str isn't a valid IPv6 Address. """ if not ip_str: raise AddressValueError('Address cannot be empty') parts = ip_str.split(':') # An IPv6 address needs at least 2 colons (3 parts). _min_parts = 3 if len(parts) < _min_parts: msg = "At least %d parts expected in %r" % (_min_parts, ip_str) raise AddressValueError(msg) # If the address has an IPv4-style suffix, convert it to hexadecimal. if '.' in parts[-1]: try: ipv4_int = IPv4Address(parts.pop())._ip except AddressValueError as exc: raise AddressValueError("%s in %r" % (exc, ip_str)) parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF)) parts.append('%x' % (ipv4_int & 0xFFFF)) # An IPv6 address can't have more than 8 colons (9 parts). # The extra colon comes from using the "::" notation for a single # leading or trailing zero part. _max_parts = self._HEXTET_COUNT + 1 if len(parts) > _max_parts: msg = "At most %d colons permitted in %r" % (_max_parts-1, ip_str) raise AddressValueError(msg) # Disregarding the endpoints, find '::' with nothing in between. # This indicates that a run of zeroes has been skipped. skip_index = None for i in range(1, len(parts) - 1): if not parts[i]: if skip_index is not None: # Can't have more than one '::' msg = "At most one '::' permitted in %r" % ip_str raise AddressValueError(msg) skip_index = i # parts_hi is the number of parts to copy from above/before the '::' # parts_lo is the number of parts to copy from below/after the '::' if skip_index is not None: # If we found a '::', then check if it also covers the endpoints. parts_hi = skip_index parts_lo = len(parts) - skip_index - 1 if not parts[0]: parts_hi -= 1 if parts_hi: msg = "Leading ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # ^: requires ^:: if not parts[-1]: parts_lo -= 1 if parts_lo: msg = "Trailing ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # :$ requires ::$ parts_skipped = self._HEXTET_COUNT - (parts_hi + parts_lo) if parts_skipped < 1: msg = "Expected at most %d other parts with '::' in %r" raise AddressValueError(msg % (self._HEXTET_COUNT-1, ip_str)) else: # Otherwise, allocate the entire address to parts_hi. The # endpoints could still be empty, but _parse_hextet() will check # for that. if len(parts) != self._HEXTET_COUNT: msg = "Exactly %d parts expected without '::' in %r" raise AddressValueError(msg % (self._HEXTET_COUNT, ip_str)) if not parts[0]: msg = "Leading ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # ^: requires ^:: if not parts[-1]: msg = "Trailing ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # :$ requires ::$ parts_hi = len(parts) parts_lo = 0 parts_skipped = 0 try: # Now, parse the hextets into a 128-bit integer. ip_int = 0 for i in range(parts_hi): ip_int <<= 16 ip_int |= self._parse_hextet(parts[i]) ip_int <<= 16 * parts_skipped for i in range(-parts_lo, 0): ip_int <<= 16 ip_int |= self._parse_hextet(parts[i]) return ip_int except ValueError as exc: raise AddressValueError("%s in %r" % (exc, ip_str)) def _parse_hextet(self, hextet_str): """Convert an IPv6 hextet string into an integer. Args: hextet_str: A string, the number to parse. Returns: The hextet as an integer. Raises: ValueError: if the input isn't strictly a hex number from [0..FFFF]. """ # Whitelist the characters, since int() allows a lot of bizarre stuff. if not self._HEX_DIGITS.issuperset(hextet_str): raise ValueError("Only hex digits permitted in %r" % hextet_str) # We do the length check second, since the invalid character error # is likely to be more informative for the user if len(hextet_str) > 4: msg = "At most 4 characters permitted in %r" raise ValueError(msg % hextet_str) # Length check means we can skip checking the integer value return int(hextet_str, 16) def _compress_hextets(self, hextets): """Compresses a list of hextets. Compresses a list of strings, replacing the longest continuous sequence of "0" in the list with "" and adding empty strings at the beginning or at the end of the string such that subsequently calling ":".join(hextets) will produce the compressed version of the IPv6 address. Args: hextets: A list of strings, the hextets to compress. Returns: A list of strings. """ best_doublecolon_start = -1 best_doublecolon_len = 0 doublecolon_start = -1 doublecolon_len = 0 for index, hextet in enumerate(hextets): if hextet == '0': doublecolon_len += 1 if doublecolon_start == -1: # Start of a sequence of zeros. doublecolon_start = index if doublecolon_len > best_doublecolon_len: # This is the longest sequence of zeros so far. best_doublecolon_len = doublecolon_len best_doublecolon_start = doublecolon_start else: doublecolon_len = 0 doublecolon_start = -1 if best_doublecolon_len > 1: best_doublecolon_end = (best_doublecolon_start + best_doublecolon_len) # For zeros at the end of the address. if best_doublecolon_end == len(hextets): hextets += [''] hextets[best_doublecolon_start:best_doublecolon_end] = [''] # For zeros at the beginning of the address. if best_doublecolon_start == 0: hextets = [''] + hextets return hextets def _string_from_ip_int(self, ip_int=None): """Turns a 128-bit integer into hexadecimal notation. Args: ip_int: An integer, the IP address. Returns: A string, the hexadecimal representation of the address. Raises: ValueError: The address is bigger than 128 bits of all ones. """ if ip_int is None: ip_int = int(self._ip) if ip_int > self._ALL_ONES: raise ValueError('IPv6 address is too large') hex_str = '%032x' % ip_int hextets = ['%x' % int(hex_str[x:x+4], 16) for x in range(0, 32, 4)] hextets = self._compress_hextets(hextets) return ':'.join(hextets) def _explode_shorthand_ip_string(self): """Expand a shortened IPv6 address. Args: ip_str: A string, the IPv6 address. Returns: A string, the expanded IPv6 address. """ if isinstance(self, IPv6Network): ip_str = str(self.network_address) elif isinstance(self, IPv6Interface): ip_str = str(self.ip) else: ip_str = str(self) ip_int = self._ip_int_from_string(ip_str) hex_str = '%032x' % ip_int parts = [hex_str[x:x+4] for x in range(0, 32, 4)] if isinstance(self, (_BaseNetwork, IPv6Interface)): return '%s/%d' % (':'.join(parts), self._prefixlen) return ':'.join(parts) def _reverse_pointer(self): """Return the reverse DNS pointer name for the IPv6 address. This implements the method described in RFC3596 2.5. """ reverse_chars = self.exploded[::-1].replace(':', '') return '.'.join(reverse_chars) + '.ip6.arpa' @property def max_prefixlen(self): return self._max_prefixlen @property def version(self): return self._version class IPv6Address(_BaseV6, _BaseAddress): """Represent and manipulate single IPv6 Addresses.""" def __init__(self, address): """Instantiate a new IPv6 address object. Args: address: A string or integer representing the IP Additionally, an integer can be passed, so IPv6Address('2001:db8::') == IPv6Address(42540766411282592856903984951653826560) or, more generally IPv6Address(int(IPv6Address('2001:db8::'))) == IPv6Address('2001:db8::') Raises: AddressValueError: If address isn't a valid IPv6 address. """ _BaseAddress.__init__(self, address) _BaseV6.__init__(self, address) # Efficient constructor from integer. if isinstance(address, int): self._check_int_address(address) self._ip = address return # Constructing from a packed address if isinstance(address, bytes): self._check_packed_address(address, 16) self._ip = _int_from_bytes(address, 'big') return # Assume input argument to be string or any object representation # which converts into a formatted IP string. addr_str = str(address) self._ip = self._ip_int_from_string(addr_str) @property def packed(self): """The binary representation of this address.""" return v6_int_to_packed(self._ip) @property def is_multicast(self): """Test if the address is reserved for multicast use. Returns: A boolean, True if the address is a multicast address. See RFC 2373 2.7 for details. """ multicast_network = IPv6Network('ff00::/8') return self in multicast_network @property def is_reserved(self): """Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within one of the reserved IPv6 Network ranges. """ reserved_networks = [IPv6Network('::/8'), IPv6Network('100::/8'), IPv6Network('200::/7'), IPv6Network('400::/6'), IPv6Network('800::/5'), IPv6Network('1000::/4'), IPv6Network('4000::/3'), IPv6Network('6000::/3'), IPv6Network('8000::/3'), IPv6Network('A000::/3'), IPv6Network('C000::/3'), IPv6Network('E000::/4'), IPv6Network('F000::/5'), IPv6Network('F800::/6'), IPv6Network('FE00::/9')] return any(self in x for x in reserved_networks) @property def is_link_local(self): """Test if the address is reserved for link-local. Returns: A boolean, True if the address is reserved per RFC 4291. """ linklocal_network = IPv6Network('fe80::/10') return self in linklocal_network @property def is_site_local(self): """Test if the address is reserved for site-local. Note that the site-local address space has been deprecated by RFC 3879. Use is_private to test if this address is in the space of unique local addresses as defined by RFC 4193. Returns: A boolean, True if the address is reserved per RFC 3513 2.5.6. """ sitelocal_network = IPv6Network('fec0::/10') return self in sitelocal_network @property def is_private(self): """Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per iana-ipv6-special-registry. """ return (self in IPv6Network('::1/128') or self in IPv6Network('::/128') or self in IPv6Network('::ffff:0:0/96') or self in IPv6Network('100::/64') or self in IPv6Network('2001::/23') or self in IPv6Network('2001:2::/48') or self in IPv6Network('2001:db8::/32') or self in IPv6Network('2001:10::/28') or self in IPv6Network('fc00::/7') or self in IPv6Network('fe80::/10')) @property def is_global(self): """Test if this address is allocated for public networks. Returns: A boolean, true if the address is not reserved per iana-ipv6-special-registry. """ return not self.is_private @property def is_unspecified(self): """Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in RFC 2373 2.5.2. """ return self._ip == 0 @property def is_loopback(self): """Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback address as defined in RFC 2373 2.5.3. """ return self._ip == 1 @property def ipv4_mapped(self): """Return the IPv4 mapped address. Returns: If the IPv6 address is a v4 mapped address, return the IPv4 mapped address. Return None otherwise. """ if (self._ip >> 32) != 0xFFFF: return None return IPv4Address(self._ip & 0xFFFFFFFF) @property def teredo(self): """Tuple of embedded teredo IPs. Returns: Tuple of the (server, client) IPs or None if the address doesn't appear to be a teredo address (doesn't start with 2001::/32) """ if (self._ip >> 96) != 0x20010000: return None return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF), IPv4Address(~self._ip & 0xFFFFFFFF)) @property def sixtofour(self): """Return the IPv4 6to4 embedded address. Returns: The IPv4 6to4-embedded address if present or None if the address doesn't appear to contain a 6to4 embedded address. """ if (self._ip >> 112) != 0x2002: return None return IPv4Address((self._ip >> 80) & 0xFFFFFFFF) class IPv6Interface(IPv6Address): def __init__(self, address): if isinstance(address, (bytes, int)): IPv6Address.__init__(self, address) self.network = IPv6Network(self._ip) self._prefixlen = self._max_prefixlen return addr = _split_optional_netmask(address) IPv6Address.__init__(self, addr[0]) self.network = IPv6Network(address, strict=False) self.netmask = self.network.netmask self._prefixlen = self.network._prefixlen self.hostmask = self.network.hostmask def __str__(self): return '%s/%d' % (self._string_from_ip_int(self._ip), self.network.prefixlen) def __eq__(self, other): address_equal = IPv6Address.__eq__(self, other) if not address_equal or address_equal is NotImplemented: return address_equal try: return self.network == other.network except AttributeError: # An interface with an associated network is NOT the # same as an unassociated address. That's why the hash # takes the extra info into account. return False def __lt__(self, other): address_less = IPv6Address.__lt__(self, other) if address_less is NotImplemented: return NotImplemented try: return self.network < other.network except AttributeError: # We *do* allow addresses and interfaces to be sorted. The # unassociated address is considered less than all interfaces. return False def __hash__(self): return self._ip ^ self._prefixlen ^ int(self.network.network_address) @property def ip(self): return IPv6Address(self._ip) @property def with_prefixlen(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self._prefixlen) @property def with_netmask(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self.netmask) @property def with_hostmask(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self.hostmask) @property def is_unspecified(self): return self._ip == 0 and self.network.is_unspecified @property def is_loopback(self): return self._ip == 1 and self.network.is_loopback class IPv6Network(_BaseV6, _BaseNetwork): """This class represents and manipulates 128-bit IPv6 networks. Attributes: [examples for IPv6('2001:db8::1000/124')] .network_address: IPv6Address('2001:db8::1000') .hostmask: IPv6Address('::f') .broadcast_address: IPv6Address('2001:db8::100f') .netmask: IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0') .prefixlen: 124 """ # Class to use when creating address objects _address_class = IPv6Address def __init__(self, address, strict=True): """Instantiate a new IPv6 Network object. Args: address: A string or integer representing the IPv6 network or the IP and prefix/netmask. '2001:db8::/128' '2001:db8:0000:0000:0000:0000:0000:0000/128' '2001:db8::' are all functionally the same in IPv6. That is to say, failing to provide a subnetmask will create an object with a mask of /128. Additionally, an integer can be passed, so IPv6Network('2001:db8::') == IPv6Network(42540766411282592856903984951653826560) or, more generally IPv6Network(int(IPv6Network('2001:db8::'))) == IPv6Network('2001:db8::') strict: A boolean. If true, ensure that we have been passed A true network address, eg, 2001:db8::1000/124 and not an IP address on a network, eg, 2001:db8::1/124. Raises: AddressValueError: If address isn't a valid IPv6 address. NetmaskValueError: If the netmask isn't valid for an IPv6 address. ValueError: If strict was True and a network address was not supplied. """ _BaseV6.__init__(self, address) _BaseNetwork.__init__(self, address) # Efficient constructor from integer. if isinstance(address, int): self.network_address = IPv6Address(address) self._prefixlen = self._max_prefixlen self.netmask = IPv6Address(self._ALL_ONES) return # Constructing from a packed address if isinstance(address, bytes): self.network_address = IPv6Address(address) self._prefixlen = self._max_prefixlen self.netmask = IPv6Address(self._ALL_ONES) return # Assume input argument to be string or any object representation # which converts into a formatted IP prefix string. addr = _split_optional_netmask(address) self.network_address = IPv6Address(self._ip_int_from_string(addr[0])) if len(addr) == 2: # This may raise NetmaskValueError self._prefixlen = self._prefix_from_prefix_string(addr[1]) else: self._prefixlen = self._max_prefixlen self.netmask = IPv6Address(self._ip_int_from_prefix(self._prefixlen)) if strict: if (IPv6Address(int(self.network_address) & int(self.netmask)) != self.network_address): raise ValueError('%s has host bits set' % self) self.network_address = IPv6Address(int(self.network_address) & int(self.netmask)) if self._prefixlen == (self._max_prefixlen - 1): self.hosts = self.__iter__ def hosts(self): """Generate Iterator over usable hosts in a network. This is like __iter__ except it doesn't return the Subnet-Router anycast address. """ network = int(self.network_address) broadcast = int(self.broadcast_address) for x in long_range(1, broadcast - network + 1): yield self._address_class(network + x) @property def is_site_local(self): """Test if the address is reserved for site-local. Note that the site-local address space has been deprecated by RFC 3879. Use is_private to test if this address is in the space of unique local addresses as defined by RFC 4193. Returns: A boolean, True if the address is reserved per RFC 3513 2.5.6. """ return (self.network_address.is_site_local and self.broadcast_address.is_site_local)
saltstack/salt
salt/ext/ipaddress.py
ip_network
python
def ip_network(address, strict=True): try: return IPv4Network(address, strict) except (AddressValueError, NetmaskValueError): pass try: return IPv6Network(address, strict) except (AddressValueError, NetmaskValueError): pass raise ValueError('%r does not appear to be an IPv4 or IPv6 network' % address)
Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP network. Either IPv4 or IPv6 networks may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Network or IPv6Network object. Raises: ValueError: if the string passed isn't either a v4 or a v6 address. Or if the network has host bits set.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/ext/ipaddress.py#L123-L150
null
''' Python 2.[67] port of Python 3.4's ipaddress module Almost verbatim copy of the core lib, with compatibility changes Source: https://bitbucket.org/kwi/py2-ipaddress/ ''' # pylint: skip-file # List of compatibility changes: # Python 3 uses only new-style classes. # s/class \(\w\+\):/class \1(object):/ # Use iterator versions of map and range: from itertools import imap as map range = xrange # Except that xrange only supports machine integers, not longs, so... def long_range(start, end): while start < end: yield start start += 1 # This backport uses bytearray instead of bytes, as bytes is the same # as str in Python 2.7. bytes = bytearray # Python 2 does not support exception chaining. # s/ from None$// # When checking for instances of int, also allow Python 2's long. _builtin_isinstance = isinstance def isinstance(val, types): if types is int: types = (int, long) elif type(types) is tuple and int in types: types += (long,) return _builtin_isinstance(val, types) # functools.lru_cache is Python 3.2+ only. # /@functools.lru_cache()/d # int().to_bytes is Python 3.2+ only. # s/\(\w+\)\.to_bytes(/_int_to_bytes(\1, / def _int_to_bytes(self, length, byteorder, signed=False): assert byteorder == 'big' and signed is False if self < 0 or self >= 256**length: raise OverflowError() return bytearray(('%0*x' % (length * 2, self)).decode('hex')) # int.from_bytes is Python 3.2+ only. # s/int\.from_bytes(/_int_from_bytes(/g def _int_from_bytes(what, byteorder, signed=False): assert byteorder == 'big' and signed is False return int(str(bytearray(what)).encode('hex'), 16) # Python 2.6 has no int.bit_length() if hasattr(int, 'bit_length'): _int_bit_length = lambda i: i.bit_length() else: _int_bit_length = lambda i: len(bin(abs(i))) - 2 # ---------------------------------------------------------------------------- # Copyright 2007 Google Inc. # Licensed to PSF under a Contributor Agreement. """A fast, lightweight IPv4/IPv6 manipulation library in Python. This library is used to create/poke/manipulate IPv4 and IPv6 addresses and networks. """ __version__ = '1.0' import functools IPV4LENGTH = 32 IPV6LENGTH = 128 class AddressValueError(ValueError): """A Value Error related to the address.""" class NetmaskValueError(ValueError): """A Value Error related to the netmask.""" def ip_address(address): """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Address or IPv6Address object. Raises: ValueError: if the *address* passed isn't either a v4 or a v6 address """ try: return IPv4Address(address) except (AddressValueError, NetmaskValueError): pass try: return IPv6Address(address) except (AddressValueError, NetmaskValueError): pass raise ValueError('%r does not appear to be an IPv4 or IPv6 address' % address) def ip_interface(address): """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Interface or IPv6Interface object. Raises: ValueError: if the string passed isn't either a v4 or a v6 address. Notes: The IPv?Interface classes describe an Address on a particular Network, so they're basically a combination of both the Address and Network classes. """ try: return IPv4Interface(address) except (AddressValueError, NetmaskValueError): pass try: return IPv6Interface(address) except (AddressValueError, NetmaskValueError): pass raise ValueError('%r does not appear to be an IPv4 or IPv6 interface' % address) def v4_int_to_packed(address): """Represent an address as 4 packed bytes in network (big-endian) order. Args: address: An integer representation of an IPv4 IP address. Returns: The integer address packed as 4 bytes in network (big-endian) order. Raises: ValueError: If the integer is negative or too large to be an IPv4 IP address. """ try: return _int_to_bytes(address, 4, 'big') except Exception: raise ValueError("Address negative or too large for IPv4") def v6_int_to_packed(address): """Represent an address as 16 packed bytes in network (big-endian) order. Args: address: An integer representation of an IPv6 IP address. Returns: The integer address packed as 16 bytes in network (big-endian) order. """ try: return _int_to_bytes(address, 16, 'big') except Exception: raise ValueError("Address negative or too large for IPv6") def _split_optional_netmask(address): """Helper to split the netmask and raise AddressValueError if needed""" addr = str(address).split('/') if len(addr) > 2: raise AddressValueError("Only one '/' permitted in %r" % address) return addr def _find_address_range(addresses): """Find a sequence of IPv#Address. Args: addresses: a list of IPv#Address objects. Returns: A tuple containing the first and last IP addresses in the sequence. """ first = last = addresses[0] for ip in addresses[1:]: if ip._ip == last._ip + 1: last = ip else: break return (first, last) def _count_righthand_zero_bits(number, bits): """Count the number of zero bits on the right hand side. Args: number: an integer. bits: maximum number of bits to count. Returns: The number of zero bits on the right hand side of the number. """ if number == 0: return bits for i in range(bits): if (number >> i) & 1: return i # All bits of interest were zero, even if there are more in the number return bits def summarize_address_range(first, last): """Summarize a network range given the first and last IP addresses. Example: >>> list(summarize_address_range(IPv4Address('192.0.2.0'), ... IPv4Address('192.0.2.130'))) ... #doctest: +NORMALIZE_WHITESPACE [IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/31'), IPv4Network('192.0.2.130/32')] Args: first: the first IPv4Address or IPv6Address in the range. last: the last IPv4Address or IPv6Address in the range. Returns: An iterator of the summarized IPv(4|6) network objects. Raise: TypeError: If the first and last objects are not IP addresses. If the first and last objects are not the same version. ValueError: If the last object is not greater than the first. If the version of the first address is not 4 or 6. """ if (not (isinstance(first, _BaseAddress) and isinstance(last, _BaseAddress))): raise TypeError('first and last must be IP addresses, not networks') if first.version != last.version: raise TypeError("%s and %s are not of the same version" % ( first, last)) if first > last: raise ValueError('last IP address must be greater than first') if first.version == 4: ip = IPv4Network elif first.version == 6: ip = IPv6Network else: raise ValueError('unknown IP version') ip_bits = first._max_prefixlen first_int = first._ip last_int = last._ip while first_int <= last_int: nbits = min(_count_righthand_zero_bits(first_int, ip_bits), _int_bit_length(last_int - first_int + 1) - 1) net = ip('%s/%d' % (first, ip_bits - nbits)) yield net first_int += 1 << nbits if first_int - 1 == ip._ALL_ONES: break first = first.__class__(first_int) def _collapse_addresses_recursive(addresses): """Loops through the addresses, collapsing concurrent netblocks. Example: ip1 = IPv4Network('192.0.2.0/26') ip2 = IPv4Network('192.0.2.64/26') ip3 = IPv4Network('192.0.2.128/26') ip4 = IPv4Network('192.0.2.192/26') _collapse_addresses_recursive([ip1, ip2, ip3, ip4]) -> [IPv4Network('192.0.2.0/24')] This shouldn't be called directly; it is called via collapse_addresses([]). Args: addresses: A list of IPv4Network's or IPv6Network's Returns: A list of IPv4Network's or IPv6Network's depending on what we were passed. """ while True: last_addr = None ret_array = [] optimized = False for cur_addr in addresses: if not ret_array: last_addr = cur_addr ret_array.append(cur_addr) elif (cur_addr.network_address >= last_addr.network_address and cur_addr.broadcast_address <= last_addr.broadcast_address): optimized = True elif cur_addr == list(last_addr.supernet().subnets())[1]: ret_array[-1] = last_addr = last_addr.supernet() optimized = True else: last_addr = cur_addr ret_array.append(cur_addr) addresses = ret_array if not optimized: return addresses def collapse_addresses(addresses): """Collapse a list of IP objects. Example: collapse_addresses([IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/25')]) -> [IPv4Network('192.0.2.0/24')] Args: addresses: An iterator of IPv4Network or IPv6Network objects. Returns: An iterator of the collapsed IPv(4|6)Network objects. Raises: TypeError: If passed a list of mixed version objects. """ i = 0 addrs = [] ips = [] nets = [] # split IP addresses and networks for ip in addresses: if isinstance(ip, _BaseAddress): if ips and ips[-1]._version != ip._version: raise TypeError("%s and %s are not of the same version" % ( ip, ips[-1])) ips.append(ip) elif ip._prefixlen == ip._max_prefixlen: if ips and ips[-1]._version != ip._version: raise TypeError("%s and %s are not of the same version" % ( ip, ips[-1])) try: ips.append(ip.ip) except AttributeError: ips.append(ip.network_address) else: if nets and nets[-1]._version != ip._version: raise TypeError("%s and %s are not of the same version" % ( ip, nets[-1])) nets.append(ip) # sort and dedup ips = sorted(set(ips)) nets = sorted(set(nets)) while i < len(ips): (first, last) = _find_address_range(ips[i:]) i = ips.index(last) + 1 addrs.extend(summarize_address_range(first, last)) return iter(_collapse_addresses_recursive(sorted( addrs + nets, key=_BaseNetwork._get_networks_key))) def get_mixed_type_key(obj): """Return a key suitable for sorting between networks and addresses. Address and Network objects are not sortable by default; they're fundamentally different so the expression IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24') doesn't make any sense. There are some times however, where you may wish to have ipaddress sort these for you anyway. If you need to do this, you can use this function as the key= argument to sorted(). Args: obj: either a Network or Address object. Returns: appropriate key. """ if isinstance(obj, _BaseNetwork): return obj._get_networks_key() elif isinstance(obj, _BaseAddress): return obj._get_address_key() return NotImplemented class _TotalOrderingMixin(object): # Helper that derives the other comparison operations from # __lt__ and __eq__ # We avoid functools.total_ordering because it doesn't handle # NotImplemented correctly yet (http://bugs.python.org/issue10042) def __eq__(self, other): raise NotImplementedError def __ne__(self, other): equal = self.__eq__(other) if equal is NotImplemented: return NotImplemented return not equal def __lt__(self, other): raise NotImplementedError def __le__(self, other): less = self.__lt__(other) if less is NotImplemented or not less: return self.__eq__(other) return less def __gt__(self, other): less = self.__lt__(other) if less is NotImplemented: return NotImplemented equal = self.__eq__(other) if equal is NotImplemented: return NotImplemented return not (less or equal) def __ge__(self, other): less = self.__lt__(other) if less is NotImplemented: return NotImplemented return not less class _IPAddressBase(_TotalOrderingMixin): """The mother class.""" @property def exploded(self): """Return the longhand version of the IP address as a string.""" return self._explode_shorthand_ip_string() @property def compressed(self): """Return the shorthand version of the IP address as a string.""" return str(self) @property def reverse_pointer(self): """The name of the reverse DNS pointer for the IP address, e.g.: >>> ipaddress.ip_address("127.0.0.1").reverse_pointer '1.0.0.127.in-addr.arpa' >>> ipaddress.ip_address("2001:db8::1").reverse_pointer '1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa' """ return self._reverse_pointer() @property def version(self): msg = '%200s has no version specified' % (type(self),) raise NotImplementedError(msg) def _check_int_address(self, address): if address < 0: msg = "%d (< 0) is not permitted as an IPv%d address" raise AddressValueError(msg % (address, self._version)) if address > self._ALL_ONES: msg = "%d (>= 2**%d) is not permitted as an IPv%d address" raise AddressValueError(msg % (address, self._max_prefixlen, self._version)) def _check_packed_address(self, address, expected_len): address_len = len(address) if address_len != expected_len: msg = "%r (len %d != %d) is not permitted as an IPv%d address" raise AddressValueError(msg % (address, address_len, expected_len, self._version)) def _ip_int_from_prefix(self, prefixlen): """Turn the prefix length into a bitwise netmask Args: prefixlen: An integer, the prefix length. Returns: An integer. """ return self._ALL_ONES ^ (self._ALL_ONES >> prefixlen) def _prefix_from_ip_int(self, ip_int): """Return prefix length from the bitwise netmask. Args: ip_int: An integer, the netmask in expanded bitwise format Returns: An integer, the prefix length. Raises: ValueError: If the input intermingles zeroes & ones """ trailing_zeroes = _count_righthand_zero_bits(ip_int, self._max_prefixlen) prefixlen = self._max_prefixlen - trailing_zeroes leading_ones = ip_int >> trailing_zeroes all_ones = (1 << prefixlen) - 1 if leading_ones != all_ones: byteslen = self._max_prefixlen // 8 details = _int_to_bytes(ip_int, byteslen, 'big') msg = 'Netmask pattern %r mixes zeroes & ones' raise ValueError(msg % details) return prefixlen def _report_invalid_netmask(self, netmask_str): msg = '%r is not a valid netmask' % netmask_str raise NetmaskValueError(msg) def _prefix_from_prefix_string(self, prefixlen_str): """Return prefix length from a numeric string Args: prefixlen_str: The string to be converted Returns: An integer, the prefix length. Raises: NetmaskValueError: If the input is not a valid netmask """ # int allows a leading +/- as well as surrounding whitespace, # so we ensure that isn't the case if not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str): self._report_invalid_netmask(prefixlen_str) try: prefixlen = int(prefixlen_str) except ValueError: self._report_invalid_netmask(prefixlen_str) if not (0 <= prefixlen <= self._max_prefixlen): self._report_invalid_netmask(prefixlen_str) return prefixlen def _prefix_from_ip_string(self, ip_str): """Turn a netmask/hostmask string into a prefix length Args: ip_str: The netmask/hostmask to be converted Returns: An integer, the prefix length. Raises: NetmaskValueError: If the input is not a valid netmask/hostmask """ # Parse the netmask/hostmask like an IP address. try: ip_int = self._ip_int_from_string(ip_str) except AddressValueError: self._report_invalid_netmask(ip_str) # Try matching a netmask (this would be /1*0*/ as a bitwise regexp). # Note that the two ambiguous cases (all-ones and all-zeroes) are # treated as netmasks. try: return self._prefix_from_ip_int(ip_int) except ValueError: pass # Invert the bits, and try matching a /0+1+/ hostmask instead. ip_int ^= self._ALL_ONES try: return self._prefix_from_ip_int(ip_int) except ValueError: self._report_invalid_netmask(ip_str) class _BaseAddress(_IPAddressBase): """A generic IP object. This IP class contains the version independent methods which are used by single IP addresses. """ def __init__(self, address): if (not isinstance(address, bytes) and '/' in str(address)): raise AddressValueError("Unexpected '/' in %r" % address) def __int__(self): return self._ip def __eq__(self, other): try: return (self._ip == other._ip and self._version == other._version) except AttributeError: return NotImplemented def __lt__(self, other): if self._version != other._version: raise TypeError('%s and %s are not of the same version' % ( self, other)) if not isinstance(other, _BaseAddress): raise TypeError('%s and %s are not of the same type' % ( self, other)) if self._ip != other._ip: return self._ip < other._ip return False # Shorthand for Integer addition and subtraction. This is not # meant to ever support addition/subtraction of addresses. def __add__(self, other): if not isinstance(other, int): return NotImplemented return self.__class__(int(self) + other) def __sub__(self, other): if not isinstance(other, int): return NotImplemented return self.__class__(int(self) - other) def __repr__(self): return '%s(%r)' % (self.__class__.__name__, str(self)) def __str__(self): return str(self._string_from_ip_int(self._ip)) def __hash__(self): return hash(hex(int(self._ip))) def _get_address_key(self): return (self._version, self) class _BaseNetwork(_IPAddressBase): """A generic IP network object. This IP class contains the version independent methods which are used by networks. """ def __init__(self, address): self._cache = {} def __repr__(self): return '%s(%r)' % (self.__class__.__name__, str(self)) def __str__(self): return '%s/%d' % (self.network_address, self.prefixlen) def hosts(self): """Generate Iterator over usable hosts in a network. This is like __iter__ except it doesn't return the network or broadcast addresses. """ network = int(self.network_address) broadcast = int(self.broadcast_address) for x in long_range(network + 1, broadcast): yield self._address_class(x) def __iter__(self): network = int(self.network_address) broadcast = int(self.broadcast_address) for x in long_range(network, broadcast + 1): yield self._address_class(x) def __getitem__(self, n): network = int(self.network_address) broadcast = int(self.broadcast_address) if n >= 0: if network + n > broadcast: raise IndexError return self._address_class(network + n) else: n += 1 if broadcast + n < network: raise IndexError return self._address_class(broadcast + n) def __lt__(self, other): if self._version != other._version: raise TypeError('%s and %s are not of the same version' % ( self, other)) if not isinstance(other, _BaseNetwork): raise TypeError('%s and %s are not of the same type' % ( self, other)) if self.network_address != other.network_address: return self.network_address < other.network_address if self.netmask != other.netmask: return self.netmask < other.netmask return False def __eq__(self, other): try: return (self._version == other._version and self.network_address == other.network_address and int(self.netmask) == int(other.netmask)) except AttributeError: return NotImplemented def __hash__(self): return hash(int(self.network_address) ^ int(self.netmask)) def __contains__(self, other): # always false if one is v4 and the other is v6. if self._version != other._version: return False # dealing with another network. if isinstance(other, _BaseNetwork): return False # dealing with another address else: # address return (int(self.network_address) <= int(other._ip) <= int(self.broadcast_address)) def overlaps(self, other): """Tell if self is partly contained in other.""" return self.network_address in other or ( self.broadcast_address in other or ( other.network_address in self or ( other.broadcast_address in self))) @property def broadcast_address(self): x = self._cache.get('broadcast_address') if x is None: x = self._address_class(int(self.network_address) | int(self.hostmask)) self._cache['broadcast_address'] = x return x @property def hostmask(self): x = self._cache.get('hostmask') if x is None: x = self._address_class(int(self.netmask) ^ self._ALL_ONES) self._cache['hostmask'] = x return x @property def with_prefixlen(self): return '%s/%d' % (self.network_address, self._prefixlen) @property def with_netmask(self): return '%s/%s' % (self.network_address, self.netmask) @property def with_hostmask(self): return '%s/%s' % (self.network_address, self.hostmask) @property def num_addresses(self): """Number of hosts in the current subnet.""" return int(self.broadcast_address) - int(self.network_address) + 1 @property def _address_class(self): # Returning bare address objects (rather than interfaces) allows for # more consistent behaviour across the network address, broadcast # address and individual host addresses. msg = '%200s has no associated address class' % (type(self),) raise NotImplementedError(msg) @property def prefixlen(self): return self._prefixlen def address_exclude(self, other): """Remove an address from a larger block. For example: addr1 = ip_network('192.0.2.0/28') addr2 = ip_network('192.0.2.1/32') addr1.address_exclude(addr2) = [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'), IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')] or IPv6: addr1 = ip_network('2001:db8::1/32') addr2 = ip_network('2001:db8::1/128') addr1.address_exclude(addr2) = [ip_network('2001:db8::1/128'), ip_network('2001:db8::2/127'), ip_network('2001:db8::4/126'), ip_network('2001:db8::8/125'), ... ip_network('2001:db8:8000::/33')] Args: other: An IPv4Network or IPv6Network object of the same type. Returns: An iterator of the IPv(4|6)Network objects which is self minus other. Raises: TypeError: If self and other are of differing address versions, or if other is not a network object. ValueError: If other is not completely contained by self. """ if not self._version == other._version: raise TypeError("%s and %s are not of the same version" % ( self, other)) if not isinstance(other, _BaseNetwork): raise TypeError("%s is not a network object" % other) if not (other.network_address >= self.network_address and other.broadcast_address <= self.broadcast_address): raise ValueError('%s not contained in %s' % (other, self)) if other == self: raise StopIteration # Make sure we're comparing the network of other. other = other.__class__('%s/%s' % (other.network_address, other.prefixlen)) s1, s2 = self.subnets() while s1 != other and s2 != other: if (other.network_address >= s1.network_address and other.broadcast_address <= s1.broadcast_address): yield s2 s1, s2 = s1.subnets() elif (other.network_address >= s2.network_address and other.broadcast_address <= s2.broadcast_address): yield s1 s1, s2 = s2.subnets() else: # If we got here, there's a bug somewhere. raise AssertionError('Error performing exclusion: ' 's1: %s s2: %s other: %s' % (s1, s2, other)) if s1 == other: yield s2 elif s2 == other: yield s1 else: # If we got here, there's a bug somewhere. raise AssertionError('Error performing exclusion: ' 's1: %s s2: %s other: %s' % (s1, s2, other)) def compare_networks(self, other): """Compare two IP objects. This is only concerned about the comparison of the integer representation of the network addresses. This means that the host bits aren't considered at all in this method. If you want to compare host bits, you can easily enough do a 'HostA._ip < HostB._ip' Args: other: An IP object. Returns: If the IP versions of self and other are the same, returns: -1 if self < other: eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25') IPv6Network('2001:db8::1000/124') < IPv6Network('2001:db8::2000/124') 0 if self == other eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24') IPv6Network('2001:db8::1000/124') == IPv6Network('2001:db8::1000/124') 1 if self > other eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25') IPv6Network('2001:db8::2000/124') > IPv6Network('2001:db8::1000/124') Raises: TypeError if the IP versions are different. """ # does this need to raise a ValueError? if self._version != other._version: raise TypeError('%s and %s are not of the same type' % ( self, other)) # self._version == other._version below here: if self.network_address < other.network_address: return -1 if self.network_address > other.network_address: return 1 # self.network_address == other.network_address below here: if self.netmask < other.netmask: return -1 if self.netmask > other.netmask: return 1 return 0 def _get_networks_key(self): """Network-only key function. Returns an object that identifies this address' network and netmask. This function is a suitable "key" argument for sorted() and list.sort(). """ return (self._version, self.network_address, self.netmask) def subnets(self, prefixlen_diff=1, new_prefix=None): """The subnets which join to make the current subnet. In the case that self contains only one IP (self._prefixlen == 32 for IPv4 or self._prefixlen == 128 for IPv6), yield an iterator with just ourself. Args: prefixlen_diff: An integer, the amount the prefix length should be increased by. This should not be set if new_prefix is also set. new_prefix: The desired new prefix length. This must be a larger number (smaller prefix) than the existing prefix. This should not be set if prefixlen_diff is also set. Returns: An iterator of IPv(4|6) objects. Raises: ValueError: The prefixlen_diff is too small or too large. OR prefixlen_diff and new_prefix are both set or new_prefix is a smaller number than the current prefix (smaller number means a larger network) """ if self._prefixlen == self._max_prefixlen: yield self return if new_prefix is not None: if new_prefix < self._prefixlen: raise ValueError('new prefix must be longer') if prefixlen_diff != 1: raise ValueError('cannot set prefixlen_diff and new_prefix') prefixlen_diff = new_prefix - self._prefixlen if prefixlen_diff < 0: raise ValueError('prefix length diff must be > 0') new_prefixlen = self._prefixlen + prefixlen_diff if new_prefixlen > self._max_prefixlen: raise ValueError( 'prefix length diff %d is invalid for netblock %s' % ( new_prefixlen, self)) first = self.__class__('%s/%s' % (self.network_address, self._prefixlen + prefixlen_diff)) yield first current = first while True: broadcast = current.broadcast_address if broadcast == self.broadcast_address: return new_addr = self._address_class(int(broadcast) + 1) current = self.__class__('%s/%s' % (new_addr, new_prefixlen)) yield current def supernet(self, prefixlen_diff=1, new_prefix=None): """The supernet containing the current network. Args: prefixlen_diff: An integer, the amount the prefix length of the network should be decreased by. For example, given a /24 network and a prefixlen_diff of 3, a supernet with a /21 netmask is returned. Returns: An IPv4 network object. Raises: ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have a negative prefix length. OR If prefixlen_diff and new_prefix are both set or new_prefix is a larger number than the current prefix (larger number means a smaller network) """ if self._prefixlen == 0: return self if new_prefix is not None: if new_prefix > self._prefixlen: raise ValueError('new prefix must be shorter') if prefixlen_diff != 1: raise ValueError('cannot set prefixlen_diff and new_prefix') prefixlen_diff = self._prefixlen - new_prefix if self.prefixlen - prefixlen_diff < 0: raise ValueError( 'current prefixlen is %d, cannot have a prefixlen_diff of %d' % (self.prefixlen, prefixlen_diff)) # TODO (pmoody): optimize this. t = self.__class__('%s/%d' % (self.network_address, self.prefixlen - prefixlen_diff), strict=False) return t.__class__('%s/%d' % (t.network_address, t.prefixlen)) @property def is_multicast(self): """Test if the address is reserved for multicast use. Returns: A boolean, True if the address is a multicast address. See RFC 2373 2.7 for details. """ return (self.network_address.is_multicast and self.broadcast_address.is_multicast) @property def is_reserved(self): """Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within one of the reserved IPv6 Network ranges. """ return (self.network_address.is_reserved and self.broadcast_address.is_reserved) @property def is_link_local(self): """Test if the address is reserved for link-local. Returns: A boolean, True if the address is reserved per RFC 4291. """ return (self.network_address.is_link_local and self.broadcast_address.is_link_local) @property def is_private(self): """Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per iana-ipv4-special-registry or iana-ipv6-special-registry. """ return (self.network_address.is_private and self.broadcast_address.is_private) @property def is_global(self): """Test if this address is allocated for public networks. Returns: A boolean, True if the address is not reserved per iana-ipv4-special-registry or iana-ipv6-special-registry. """ return not self.is_private @property def is_unspecified(self): """Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in RFC 2373 2.5.2. """ return (self.network_address.is_unspecified and self.broadcast_address.is_unspecified) @property def is_loopback(self): """Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback address as defined in RFC 2373 2.5.3. """ return (self.network_address.is_loopback and self.broadcast_address.is_loopback) class _BaseV4(object): """Base IPv4 object. The following methods are used by IPv4 objects in both single IP addresses and networks. """ # Equivalent to 255.255.255.255 or 32 bits of 1's. _ALL_ONES = (2**IPV4LENGTH) - 1 _DECIMAL_DIGITS = frozenset('0123456789') # the valid octets for host and netmasks. only useful for IPv4. _valid_mask_octets = frozenset((255, 254, 252, 248, 240, 224, 192, 128, 0)) def __init__(self, address): self._version = 4 self._max_prefixlen = IPV4LENGTH def _explode_shorthand_ip_string(self): return str(self) def _ip_int_from_string(self, ip_str): """Turn the given IP string into an integer for comparison. Args: ip_str: A string, the IP ip_str. Returns: The IP ip_str as an integer. Raises: AddressValueError: if ip_str isn't a valid IPv4 Address. """ if not ip_str: raise AddressValueError('Address cannot be empty') octets = ip_str.split('.') if len(octets) != 4: raise AddressValueError("Expected 4 octets in %r" % ip_str) try: return _int_from_bytes(map(self._parse_octet, octets), 'big') except ValueError as exc: raise AddressValueError("%s in %r" % (exc, ip_str)) def _parse_octet(self, octet_str): """Convert a decimal octet into an integer. Args: octet_str: A string, the number to parse. Returns: The octet as an integer. Raises: ValueError: if the octet isn't strictly a decimal from [0..255]. """ if not octet_str: raise ValueError("Empty octet not permitted") # Whitelist the characters, since int() allows a lot of bizarre stuff. if not self._DECIMAL_DIGITS.issuperset(octet_str): msg = "Only decimal digits permitted in %r" raise ValueError(msg % octet_str) # We do the length check second, since the invalid character error # is likely to be more informative for the user if len(octet_str) > 3: msg = "At most 3 characters permitted in %r" raise ValueError(msg % octet_str) # Convert to integer (we know digits are legal) octet_int = int(octet_str, 10) # Any octets that look like they *might* be written in octal, # and which don't look exactly the same in both octal and # decimal are rejected as ambiguous if octet_int > 7 and octet_str[0] == '0': msg = "Ambiguous (octal/decimal) value in %r not permitted" raise ValueError(msg % octet_str) if octet_int > 255: raise ValueError("Octet %d (> 255) not permitted" % octet_int) return octet_int def _string_from_ip_int(self, ip_int): """Turns a 32-bit integer into dotted decimal notation. Args: ip_int: An integer, the IP address. Returns: The IP address as a string in dotted decimal notation. """ return '.'.join(map(str, _int_to_bytes(ip_int, 4, 'big'))) def _is_valid_netmask(self, netmask): """Verify that the netmask is valid. Args: netmask: A string, either a prefix or dotted decimal netmask. Returns: A boolean, True if the prefix represents a valid IPv4 netmask. """ mask = netmask.split('.') if len(mask) == 4: try: for x in mask: if int(x) not in self._valid_mask_octets: return False except ValueError: # Found something that isn't an integer or isn't valid return False for idx, y in enumerate(mask): if idx > 0 and y > mask[idx - 1]: return False return True try: netmask = int(netmask) except ValueError: return False return 0 <= netmask <= self._max_prefixlen def _is_hostmask(self, ip_str): """Test if the IP string is a hostmask (rather than a netmask). Args: ip_str: A string, the potential hostmask. Returns: A boolean, True if the IP string is a hostmask. """ bits = ip_str.split('.') try: parts = [x for x in map(int, bits) if x in self._valid_mask_octets] except ValueError: return False if len(parts) != len(bits): return False if parts[0] < parts[-1]: return True return False def _reverse_pointer(self): """Return the reverse DNS pointer name for the IPv4 address. This implements the method described in RFC1035 3.5. """ reverse_octets = str(self).split('.')[::-1] return '.'.join(reverse_octets) + '.in-addr.arpa' @property def max_prefixlen(self): return self._max_prefixlen @property def version(self): return self._version class IPv4Address(_BaseV4, _BaseAddress): """Represent and manipulate single IPv4 Addresses.""" def __init__(self, address): """ Args: address: A string or integer representing the IP Additionally, an integer can be passed, so IPv4Address('192.0.2.1') == IPv4Address(3221225985). or, more generally IPv4Address(int(IPv4Address('192.0.2.1'))) == IPv4Address('192.0.2.1') Raises: AddressValueError: If ipaddress isn't a valid IPv4 address. """ _BaseAddress.__init__(self, address) _BaseV4.__init__(self, address) # Efficient constructor from integer. if isinstance(address, int): self._check_int_address(address) self._ip = address return # Constructing from a packed address if isinstance(address, bytes): self._check_packed_address(address, 4) self._ip = _int_from_bytes(address, 'big') return # Assume input argument to be string or any object representation # which converts into a formatted IP string. addr_str = str(address) self._ip = self._ip_int_from_string(addr_str) @property def packed(self): """The binary representation of this address.""" return v4_int_to_packed(self._ip) @property def is_reserved(self): """Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within the reserved IPv4 Network range. """ reserved_network = IPv4Network('240.0.0.0/4') return self in reserved_network @property def is_private(self): """Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per iana-ipv4-special-registry. """ return (self in IPv4Network('0.0.0.0/8') or self in IPv4Network('10.0.0.0/8') or self in IPv4Network('127.0.0.0/8') or self in IPv4Network('169.254.0.0/16') or self in IPv4Network('172.16.0.0/12') or self in IPv4Network('192.0.0.0/29') or self in IPv4Network('192.0.0.170/31') or self in IPv4Network('192.0.2.0/24') or self in IPv4Network('192.168.0.0/16') or self in IPv4Network('198.18.0.0/15') or self in IPv4Network('198.51.100.0/24') or self in IPv4Network('203.0.113.0/24') or self in IPv4Network('240.0.0.0/4') or self in IPv4Network('255.255.255.255/32')) @property def is_multicast(self): """Test if the address is reserved for multicast use. Returns: A boolean, True if the address is multicast. See RFC 3171 for details. """ multicast_network = IPv4Network('224.0.0.0/4') return self in multicast_network @property def is_unspecified(self): """Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in RFC 5735 3. """ unspecified_address = IPv4Address('0.0.0.0') return self == unspecified_address @property def is_loopback(self): """Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback per RFC 3330. """ loopback_network = IPv4Network('127.0.0.0/8') return self in loopback_network @property def is_link_local(self): """Test if the address is reserved for link-local. Returns: A boolean, True if the address is link-local per RFC 3927. """ linklocal_network = IPv4Network('169.254.0.0/16') return self in linklocal_network class IPv4Interface(IPv4Address): def __init__(self, address): if isinstance(address, (bytes, int)): IPv4Address.__init__(self, address) self.network = IPv4Network(self._ip) self._prefixlen = self._max_prefixlen return addr = _split_optional_netmask(address) IPv4Address.__init__(self, addr[0]) self.network = IPv4Network(address, strict=False) self._prefixlen = self.network._prefixlen self.netmask = self.network.netmask self.hostmask = self.network.hostmask def __str__(self): return '%s/%d' % (self._string_from_ip_int(self._ip), self.network.prefixlen) def __eq__(self, other): address_equal = IPv4Address.__eq__(self, other) if not address_equal or address_equal is NotImplemented: return address_equal try: return self.network == other.network except AttributeError: # An interface with an associated network is NOT the # same as an unassociated address. That's why the hash # takes the extra info into account. return False def __lt__(self, other): address_less = IPv4Address.__lt__(self, other) if address_less is NotImplemented: return NotImplemented try: return self.network < other.network except AttributeError: # We *do* allow addresses and interfaces to be sorted. The # unassociated address is considered less than all interfaces. return False def __hash__(self): return self._ip ^ self._prefixlen ^ int(self.network.network_address) @property def ip(self): return IPv4Address(self._ip) @property def with_prefixlen(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self._prefixlen) @property def with_netmask(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self.netmask) @property def with_hostmask(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self.hostmask) class IPv4Network(_BaseV4, _BaseNetwork): """This class represents and manipulates 32-bit IPv4 network + addresses.. Attributes: [examples for IPv4Network('192.0.2.0/27')] .network_address: IPv4Address('192.0.2.0') .hostmask: IPv4Address('0.0.0.31') .broadcast_address: IPv4Address('192.0.2.32') .netmask: IPv4Address('255.255.255.224') .prefixlen: 27 """ # Class to use when creating address objects _address_class = IPv4Address def __init__(self, address, strict=True): """Instantiate a new IPv4 network object. Args: address: A string or integer representing the IP [& network]. '192.0.2.0/24' '192.0.2.0/255.255.255.0' '192.0.0.2/0.0.0.255' are all functionally the same in IPv4. Similarly, '192.0.2.1' '192.0.2.1/255.255.255.255' '192.0.2.1/32' are also functionally equivalent. That is to say, failing to provide a subnetmask will create an object with a mask of /32. If the mask (portion after the / in the argument) is given in dotted quad form, it is treated as a netmask if it starts with a non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it starts with a zero field (e.g. 0.255.255.255 == /8), with the single exception of an all-zero mask which is treated as a netmask == /0. If no mask is given, a default of /32 is used. Additionally, an integer can be passed, so IPv4Network('192.0.2.1') == IPv4Network(3221225985) or, more generally IPv4Interface(int(IPv4Interface('192.0.2.1'))) == IPv4Interface('192.0.2.1') Raises: AddressValueError: If ipaddress isn't a valid IPv4 address. NetmaskValueError: If the netmask isn't valid for an IPv4 address. ValueError: If strict is True and a network address is not supplied. """ _BaseV4.__init__(self, address) _BaseNetwork.__init__(self, address) # Constructing from a packed address if isinstance(address, bytes): self.network_address = IPv4Address(address) self._prefixlen = self._max_prefixlen self.netmask = IPv4Address(self._ALL_ONES) #fixme: address/network test here return # Efficient constructor from integer. if isinstance(address, int): self.network_address = IPv4Address(address) self._prefixlen = self._max_prefixlen self.netmask = IPv4Address(self._ALL_ONES) #fixme: address/network test here. return # Assume input argument to be string or any object representation # which converts into a formatted IP prefix string. addr = _split_optional_netmask(address) self.network_address = IPv4Address(self._ip_int_from_string(addr[0])) if len(addr) == 2: try: # Check for a netmask in prefix length form self._prefixlen = self._prefix_from_prefix_string(addr[1]) except NetmaskValueError: # Check for a netmask or hostmask in dotted-quad form. # This may raise NetmaskValueError. self._prefixlen = self._prefix_from_ip_string(addr[1]) else: self._prefixlen = self._max_prefixlen self.netmask = IPv4Address(self._ip_int_from_prefix(self._prefixlen)) if strict: if (IPv4Address(int(self.network_address) & int(self.netmask)) != self.network_address): raise ValueError('%s has host bits set' % self) self.network_address = IPv4Address(int(self.network_address) & int(self.netmask)) if self._prefixlen == (self._max_prefixlen - 1): self.hosts = self.__iter__ @property def is_global(self): """Test if this address is allocated for public networks. Returns: A boolean, True if the address is not reserved per iana-ipv4-special-registry. """ return (not (self.network_address in IPv4Network('100.64.0.0/10') and self.broadcast_address in IPv4Network('100.64.0.0/10')) and not self.is_private) class _BaseV6(object): """Base IPv6 object. The following methods are used by IPv6 objects in both single IP addresses and networks. """ _ALL_ONES = (2**IPV6LENGTH) - 1 _HEXTET_COUNT = 8 _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef') def __init__(self, address): self._version = 6 self._max_prefixlen = IPV6LENGTH def _ip_int_from_string(self, ip_str): """Turn an IPv6 ip_str into an integer. Args: ip_str: A string, the IPv6 ip_str. Returns: An int, the IPv6 address Raises: AddressValueError: if ip_str isn't a valid IPv6 Address. """ if not ip_str: raise AddressValueError('Address cannot be empty') parts = ip_str.split(':') # An IPv6 address needs at least 2 colons (3 parts). _min_parts = 3 if len(parts) < _min_parts: msg = "At least %d parts expected in %r" % (_min_parts, ip_str) raise AddressValueError(msg) # If the address has an IPv4-style suffix, convert it to hexadecimal. if '.' in parts[-1]: try: ipv4_int = IPv4Address(parts.pop())._ip except AddressValueError as exc: raise AddressValueError("%s in %r" % (exc, ip_str)) parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF)) parts.append('%x' % (ipv4_int & 0xFFFF)) # An IPv6 address can't have more than 8 colons (9 parts). # The extra colon comes from using the "::" notation for a single # leading or trailing zero part. _max_parts = self._HEXTET_COUNT + 1 if len(parts) > _max_parts: msg = "At most %d colons permitted in %r" % (_max_parts-1, ip_str) raise AddressValueError(msg) # Disregarding the endpoints, find '::' with nothing in between. # This indicates that a run of zeroes has been skipped. skip_index = None for i in range(1, len(parts) - 1): if not parts[i]: if skip_index is not None: # Can't have more than one '::' msg = "At most one '::' permitted in %r" % ip_str raise AddressValueError(msg) skip_index = i # parts_hi is the number of parts to copy from above/before the '::' # parts_lo is the number of parts to copy from below/after the '::' if skip_index is not None: # If we found a '::', then check if it also covers the endpoints. parts_hi = skip_index parts_lo = len(parts) - skip_index - 1 if not parts[0]: parts_hi -= 1 if parts_hi: msg = "Leading ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # ^: requires ^:: if not parts[-1]: parts_lo -= 1 if parts_lo: msg = "Trailing ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # :$ requires ::$ parts_skipped = self._HEXTET_COUNT - (parts_hi + parts_lo) if parts_skipped < 1: msg = "Expected at most %d other parts with '::' in %r" raise AddressValueError(msg % (self._HEXTET_COUNT-1, ip_str)) else: # Otherwise, allocate the entire address to parts_hi. The # endpoints could still be empty, but _parse_hextet() will check # for that. if len(parts) != self._HEXTET_COUNT: msg = "Exactly %d parts expected without '::' in %r" raise AddressValueError(msg % (self._HEXTET_COUNT, ip_str)) if not parts[0]: msg = "Leading ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # ^: requires ^:: if not parts[-1]: msg = "Trailing ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # :$ requires ::$ parts_hi = len(parts) parts_lo = 0 parts_skipped = 0 try: # Now, parse the hextets into a 128-bit integer. ip_int = 0 for i in range(parts_hi): ip_int <<= 16 ip_int |= self._parse_hextet(parts[i]) ip_int <<= 16 * parts_skipped for i in range(-parts_lo, 0): ip_int <<= 16 ip_int |= self._parse_hextet(parts[i]) return ip_int except ValueError as exc: raise AddressValueError("%s in %r" % (exc, ip_str)) def _parse_hextet(self, hextet_str): """Convert an IPv6 hextet string into an integer. Args: hextet_str: A string, the number to parse. Returns: The hextet as an integer. Raises: ValueError: if the input isn't strictly a hex number from [0..FFFF]. """ # Whitelist the characters, since int() allows a lot of bizarre stuff. if not self._HEX_DIGITS.issuperset(hextet_str): raise ValueError("Only hex digits permitted in %r" % hextet_str) # We do the length check second, since the invalid character error # is likely to be more informative for the user if len(hextet_str) > 4: msg = "At most 4 characters permitted in %r" raise ValueError(msg % hextet_str) # Length check means we can skip checking the integer value return int(hextet_str, 16) def _compress_hextets(self, hextets): """Compresses a list of hextets. Compresses a list of strings, replacing the longest continuous sequence of "0" in the list with "" and adding empty strings at the beginning or at the end of the string such that subsequently calling ":".join(hextets) will produce the compressed version of the IPv6 address. Args: hextets: A list of strings, the hextets to compress. Returns: A list of strings. """ best_doublecolon_start = -1 best_doublecolon_len = 0 doublecolon_start = -1 doublecolon_len = 0 for index, hextet in enumerate(hextets): if hextet == '0': doublecolon_len += 1 if doublecolon_start == -1: # Start of a sequence of zeros. doublecolon_start = index if doublecolon_len > best_doublecolon_len: # This is the longest sequence of zeros so far. best_doublecolon_len = doublecolon_len best_doublecolon_start = doublecolon_start else: doublecolon_len = 0 doublecolon_start = -1 if best_doublecolon_len > 1: best_doublecolon_end = (best_doublecolon_start + best_doublecolon_len) # For zeros at the end of the address. if best_doublecolon_end == len(hextets): hextets += [''] hextets[best_doublecolon_start:best_doublecolon_end] = [''] # For zeros at the beginning of the address. if best_doublecolon_start == 0: hextets = [''] + hextets return hextets def _string_from_ip_int(self, ip_int=None): """Turns a 128-bit integer into hexadecimal notation. Args: ip_int: An integer, the IP address. Returns: A string, the hexadecimal representation of the address. Raises: ValueError: The address is bigger than 128 bits of all ones. """ if ip_int is None: ip_int = int(self._ip) if ip_int > self._ALL_ONES: raise ValueError('IPv6 address is too large') hex_str = '%032x' % ip_int hextets = ['%x' % int(hex_str[x:x+4], 16) for x in range(0, 32, 4)] hextets = self._compress_hextets(hextets) return ':'.join(hextets) def _explode_shorthand_ip_string(self): """Expand a shortened IPv6 address. Args: ip_str: A string, the IPv6 address. Returns: A string, the expanded IPv6 address. """ if isinstance(self, IPv6Network): ip_str = str(self.network_address) elif isinstance(self, IPv6Interface): ip_str = str(self.ip) else: ip_str = str(self) ip_int = self._ip_int_from_string(ip_str) hex_str = '%032x' % ip_int parts = [hex_str[x:x+4] for x in range(0, 32, 4)] if isinstance(self, (_BaseNetwork, IPv6Interface)): return '%s/%d' % (':'.join(parts), self._prefixlen) return ':'.join(parts) def _reverse_pointer(self): """Return the reverse DNS pointer name for the IPv6 address. This implements the method described in RFC3596 2.5. """ reverse_chars = self.exploded[::-1].replace(':', '') return '.'.join(reverse_chars) + '.ip6.arpa' @property def max_prefixlen(self): return self._max_prefixlen @property def version(self): return self._version class IPv6Address(_BaseV6, _BaseAddress): """Represent and manipulate single IPv6 Addresses.""" def __init__(self, address): """Instantiate a new IPv6 address object. Args: address: A string or integer representing the IP Additionally, an integer can be passed, so IPv6Address('2001:db8::') == IPv6Address(42540766411282592856903984951653826560) or, more generally IPv6Address(int(IPv6Address('2001:db8::'))) == IPv6Address('2001:db8::') Raises: AddressValueError: If address isn't a valid IPv6 address. """ _BaseAddress.__init__(self, address) _BaseV6.__init__(self, address) # Efficient constructor from integer. if isinstance(address, int): self._check_int_address(address) self._ip = address return # Constructing from a packed address if isinstance(address, bytes): self._check_packed_address(address, 16) self._ip = _int_from_bytes(address, 'big') return # Assume input argument to be string or any object representation # which converts into a formatted IP string. addr_str = str(address) self._ip = self._ip_int_from_string(addr_str) @property def packed(self): """The binary representation of this address.""" return v6_int_to_packed(self._ip) @property def is_multicast(self): """Test if the address is reserved for multicast use. Returns: A boolean, True if the address is a multicast address. See RFC 2373 2.7 for details. """ multicast_network = IPv6Network('ff00::/8') return self in multicast_network @property def is_reserved(self): """Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within one of the reserved IPv6 Network ranges. """ reserved_networks = [IPv6Network('::/8'), IPv6Network('100::/8'), IPv6Network('200::/7'), IPv6Network('400::/6'), IPv6Network('800::/5'), IPv6Network('1000::/4'), IPv6Network('4000::/3'), IPv6Network('6000::/3'), IPv6Network('8000::/3'), IPv6Network('A000::/3'), IPv6Network('C000::/3'), IPv6Network('E000::/4'), IPv6Network('F000::/5'), IPv6Network('F800::/6'), IPv6Network('FE00::/9')] return any(self in x for x in reserved_networks) @property def is_link_local(self): """Test if the address is reserved for link-local. Returns: A boolean, True if the address is reserved per RFC 4291. """ linklocal_network = IPv6Network('fe80::/10') return self in linklocal_network @property def is_site_local(self): """Test if the address is reserved for site-local. Note that the site-local address space has been deprecated by RFC 3879. Use is_private to test if this address is in the space of unique local addresses as defined by RFC 4193. Returns: A boolean, True if the address is reserved per RFC 3513 2.5.6. """ sitelocal_network = IPv6Network('fec0::/10') return self in sitelocal_network @property def is_private(self): """Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per iana-ipv6-special-registry. """ return (self in IPv6Network('::1/128') or self in IPv6Network('::/128') or self in IPv6Network('::ffff:0:0/96') or self in IPv6Network('100::/64') or self in IPv6Network('2001::/23') or self in IPv6Network('2001:2::/48') or self in IPv6Network('2001:db8::/32') or self in IPv6Network('2001:10::/28') or self in IPv6Network('fc00::/7') or self in IPv6Network('fe80::/10')) @property def is_global(self): """Test if this address is allocated for public networks. Returns: A boolean, true if the address is not reserved per iana-ipv6-special-registry. """ return not self.is_private @property def is_unspecified(self): """Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in RFC 2373 2.5.2. """ return self._ip == 0 @property def is_loopback(self): """Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback address as defined in RFC 2373 2.5.3. """ return self._ip == 1 @property def ipv4_mapped(self): """Return the IPv4 mapped address. Returns: If the IPv6 address is a v4 mapped address, return the IPv4 mapped address. Return None otherwise. """ if (self._ip >> 32) != 0xFFFF: return None return IPv4Address(self._ip & 0xFFFFFFFF) @property def teredo(self): """Tuple of embedded teredo IPs. Returns: Tuple of the (server, client) IPs or None if the address doesn't appear to be a teredo address (doesn't start with 2001::/32) """ if (self._ip >> 96) != 0x20010000: return None return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF), IPv4Address(~self._ip & 0xFFFFFFFF)) @property def sixtofour(self): """Return the IPv4 6to4 embedded address. Returns: The IPv4 6to4-embedded address if present or None if the address doesn't appear to contain a 6to4 embedded address. """ if (self._ip >> 112) != 0x2002: return None return IPv4Address((self._ip >> 80) & 0xFFFFFFFF) class IPv6Interface(IPv6Address): def __init__(self, address): if isinstance(address, (bytes, int)): IPv6Address.__init__(self, address) self.network = IPv6Network(self._ip) self._prefixlen = self._max_prefixlen return addr = _split_optional_netmask(address) IPv6Address.__init__(self, addr[0]) self.network = IPv6Network(address, strict=False) self.netmask = self.network.netmask self._prefixlen = self.network._prefixlen self.hostmask = self.network.hostmask def __str__(self): return '%s/%d' % (self._string_from_ip_int(self._ip), self.network.prefixlen) def __eq__(self, other): address_equal = IPv6Address.__eq__(self, other) if not address_equal or address_equal is NotImplemented: return address_equal try: return self.network == other.network except AttributeError: # An interface with an associated network is NOT the # same as an unassociated address. That's why the hash # takes the extra info into account. return False def __lt__(self, other): address_less = IPv6Address.__lt__(self, other) if address_less is NotImplemented: return NotImplemented try: return self.network < other.network except AttributeError: # We *do* allow addresses and interfaces to be sorted. The # unassociated address is considered less than all interfaces. return False def __hash__(self): return self._ip ^ self._prefixlen ^ int(self.network.network_address) @property def ip(self): return IPv6Address(self._ip) @property def with_prefixlen(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self._prefixlen) @property def with_netmask(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self.netmask) @property def with_hostmask(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self.hostmask) @property def is_unspecified(self): return self._ip == 0 and self.network.is_unspecified @property def is_loopback(self): return self._ip == 1 and self.network.is_loopback class IPv6Network(_BaseV6, _BaseNetwork): """This class represents and manipulates 128-bit IPv6 networks. Attributes: [examples for IPv6('2001:db8::1000/124')] .network_address: IPv6Address('2001:db8::1000') .hostmask: IPv6Address('::f') .broadcast_address: IPv6Address('2001:db8::100f') .netmask: IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0') .prefixlen: 124 """ # Class to use when creating address objects _address_class = IPv6Address def __init__(self, address, strict=True): """Instantiate a new IPv6 Network object. Args: address: A string or integer representing the IPv6 network or the IP and prefix/netmask. '2001:db8::/128' '2001:db8:0000:0000:0000:0000:0000:0000/128' '2001:db8::' are all functionally the same in IPv6. That is to say, failing to provide a subnetmask will create an object with a mask of /128. Additionally, an integer can be passed, so IPv6Network('2001:db8::') == IPv6Network(42540766411282592856903984951653826560) or, more generally IPv6Network(int(IPv6Network('2001:db8::'))) == IPv6Network('2001:db8::') strict: A boolean. If true, ensure that we have been passed A true network address, eg, 2001:db8::1000/124 and not an IP address on a network, eg, 2001:db8::1/124. Raises: AddressValueError: If address isn't a valid IPv6 address. NetmaskValueError: If the netmask isn't valid for an IPv6 address. ValueError: If strict was True and a network address was not supplied. """ _BaseV6.__init__(self, address) _BaseNetwork.__init__(self, address) # Efficient constructor from integer. if isinstance(address, int): self.network_address = IPv6Address(address) self._prefixlen = self._max_prefixlen self.netmask = IPv6Address(self._ALL_ONES) return # Constructing from a packed address if isinstance(address, bytes): self.network_address = IPv6Address(address) self._prefixlen = self._max_prefixlen self.netmask = IPv6Address(self._ALL_ONES) return # Assume input argument to be string or any object representation # which converts into a formatted IP prefix string. addr = _split_optional_netmask(address) self.network_address = IPv6Address(self._ip_int_from_string(addr[0])) if len(addr) == 2: # This may raise NetmaskValueError self._prefixlen = self._prefix_from_prefix_string(addr[1]) else: self._prefixlen = self._max_prefixlen self.netmask = IPv6Address(self._ip_int_from_prefix(self._prefixlen)) if strict: if (IPv6Address(int(self.network_address) & int(self.netmask)) != self.network_address): raise ValueError('%s has host bits set' % self) self.network_address = IPv6Address(int(self.network_address) & int(self.netmask)) if self._prefixlen == (self._max_prefixlen - 1): self.hosts = self.__iter__ def hosts(self): """Generate Iterator over usable hosts in a network. This is like __iter__ except it doesn't return the Subnet-Router anycast address. """ network = int(self.network_address) broadcast = int(self.broadcast_address) for x in long_range(1, broadcast - network + 1): yield self._address_class(network + x) @property def is_site_local(self): """Test if the address is reserved for site-local. Note that the site-local address space has been deprecated by RFC 3879. Use is_private to test if this address is in the space of unique local addresses as defined by RFC 4193. Returns: A boolean, True if the address is reserved per RFC 3513 2.5.6. """ return (self.network_address.is_site_local and self.broadcast_address.is_site_local)
saltstack/salt
salt/ext/ipaddress.py
_split_optional_netmask
python
def _split_optional_netmask(address): addr = str(address).split('/') if len(addr) > 2: raise AddressValueError("Only one '/' permitted in %r" % address) return addr
Helper to split the netmask and raise AddressValueError if needed
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/ext/ipaddress.py#L224-L229
null
''' Python 2.[67] port of Python 3.4's ipaddress module Almost verbatim copy of the core lib, with compatibility changes Source: https://bitbucket.org/kwi/py2-ipaddress/ ''' # pylint: skip-file # List of compatibility changes: # Python 3 uses only new-style classes. # s/class \(\w\+\):/class \1(object):/ # Use iterator versions of map and range: from itertools import imap as map range = xrange # Except that xrange only supports machine integers, not longs, so... def long_range(start, end): while start < end: yield start start += 1 # This backport uses bytearray instead of bytes, as bytes is the same # as str in Python 2.7. bytes = bytearray # Python 2 does not support exception chaining. # s/ from None$// # When checking for instances of int, also allow Python 2's long. _builtin_isinstance = isinstance def isinstance(val, types): if types is int: types = (int, long) elif type(types) is tuple and int in types: types += (long,) return _builtin_isinstance(val, types) # functools.lru_cache is Python 3.2+ only. # /@functools.lru_cache()/d # int().to_bytes is Python 3.2+ only. # s/\(\w+\)\.to_bytes(/_int_to_bytes(\1, / def _int_to_bytes(self, length, byteorder, signed=False): assert byteorder == 'big' and signed is False if self < 0 or self >= 256**length: raise OverflowError() return bytearray(('%0*x' % (length * 2, self)).decode('hex')) # int.from_bytes is Python 3.2+ only. # s/int\.from_bytes(/_int_from_bytes(/g def _int_from_bytes(what, byteorder, signed=False): assert byteorder == 'big' and signed is False return int(str(bytearray(what)).encode('hex'), 16) # Python 2.6 has no int.bit_length() if hasattr(int, 'bit_length'): _int_bit_length = lambda i: i.bit_length() else: _int_bit_length = lambda i: len(bin(abs(i))) - 2 # ---------------------------------------------------------------------------- # Copyright 2007 Google Inc. # Licensed to PSF under a Contributor Agreement. """A fast, lightweight IPv4/IPv6 manipulation library in Python. This library is used to create/poke/manipulate IPv4 and IPv6 addresses and networks. """ __version__ = '1.0' import functools IPV4LENGTH = 32 IPV6LENGTH = 128 class AddressValueError(ValueError): """A Value Error related to the address.""" class NetmaskValueError(ValueError): """A Value Error related to the netmask.""" def ip_address(address): """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Address or IPv6Address object. Raises: ValueError: if the *address* passed isn't either a v4 or a v6 address """ try: return IPv4Address(address) except (AddressValueError, NetmaskValueError): pass try: return IPv6Address(address) except (AddressValueError, NetmaskValueError): pass raise ValueError('%r does not appear to be an IPv4 or IPv6 address' % address) def ip_network(address, strict=True): """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP network. Either IPv4 or IPv6 networks may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Network or IPv6Network object. Raises: ValueError: if the string passed isn't either a v4 or a v6 address. Or if the network has host bits set. """ try: return IPv4Network(address, strict) except (AddressValueError, NetmaskValueError): pass try: return IPv6Network(address, strict) except (AddressValueError, NetmaskValueError): pass raise ValueError('%r does not appear to be an IPv4 or IPv6 network' % address) def ip_interface(address): """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Interface or IPv6Interface object. Raises: ValueError: if the string passed isn't either a v4 or a v6 address. Notes: The IPv?Interface classes describe an Address on a particular Network, so they're basically a combination of both the Address and Network classes. """ try: return IPv4Interface(address) except (AddressValueError, NetmaskValueError): pass try: return IPv6Interface(address) except (AddressValueError, NetmaskValueError): pass raise ValueError('%r does not appear to be an IPv4 or IPv6 interface' % address) def v4_int_to_packed(address): """Represent an address as 4 packed bytes in network (big-endian) order. Args: address: An integer representation of an IPv4 IP address. Returns: The integer address packed as 4 bytes in network (big-endian) order. Raises: ValueError: If the integer is negative or too large to be an IPv4 IP address. """ try: return _int_to_bytes(address, 4, 'big') except Exception: raise ValueError("Address negative or too large for IPv4") def v6_int_to_packed(address): """Represent an address as 16 packed bytes in network (big-endian) order. Args: address: An integer representation of an IPv6 IP address. Returns: The integer address packed as 16 bytes in network (big-endian) order. """ try: return _int_to_bytes(address, 16, 'big') except Exception: raise ValueError("Address negative or too large for IPv6") def _find_address_range(addresses): """Find a sequence of IPv#Address. Args: addresses: a list of IPv#Address objects. Returns: A tuple containing the first and last IP addresses in the sequence. """ first = last = addresses[0] for ip in addresses[1:]: if ip._ip == last._ip + 1: last = ip else: break return (first, last) def _count_righthand_zero_bits(number, bits): """Count the number of zero bits on the right hand side. Args: number: an integer. bits: maximum number of bits to count. Returns: The number of zero bits on the right hand side of the number. """ if number == 0: return bits for i in range(bits): if (number >> i) & 1: return i # All bits of interest were zero, even if there are more in the number return bits def summarize_address_range(first, last): """Summarize a network range given the first and last IP addresses. Example: >>> list(summarize_address_range(IPv4Address('192.0.2.0'), ... IPv4Address('192.0.2.130'))) ... #doctest: +NORMALIZE_WHITESPACE [IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/31'), IPv4Network('192.0.2.130/32')] Args: first: the first IPv4Address or IPv6Address in the range. last: the last IPv4Address or IPv6Address in the range. Returns: An iterator of the summarized IPv(4|6) network objects. Raise: TypeError: If the first and last objects are not IP addresses. If the first and last objects are not the same version. ValueError: If the last object is not greater than the first. If the version of the first address is not 4 or 6. """ if (not (isinstance(first, _BaseAddress) and isinstance(last, _BaseAddress))): raise TypeError('first and last must be IP addresses, not networks') if first.version != last.version: raise TypeError("%s and %s are not of the same version" % ( first, last)) if first > last: raise ValueError('last IP address must be greater than first') if first.version == 4: ip = IPv4Network elif first.version == 6: ip = IPv6Network else: raise ValueError('unknown IP version') ip_bits = first._max_prefixlen first_int = first._ip last_int = last._ip while first_int <= last_int: nbits = min(_count_righthand_zero_bits(first_int, ip_bits), _int_bit_length(last_int - first_int + 1) - 1) net = ip('%s/%d' % (first, ip_bits - nbits)) yield net first_int += 1 << nbits if first_int - 1 == ip._ALL_ONES: break first = first.__class__(first_int) def _collapse_addresses_recursive(addresses): """Loops through the addresses, collapsing concurrent netblocks. Example: ip1 = IPv4Network('192.0.2.0/26') ip2 = IPv4Network('192.0.2.64/26') ip3 = IPv4Network('192.0.2.128/26') ip4 = IPv4Network('192.0.2.192/26') _collapse_addresses_recursive([ip1, ip2, ip3, ip4]) -> [IPv4Network('192.0.2.0/24')] This shouldn't be called directly; it is called via collapse_addresses([]). Args: addresses: A list of IPv4Network's or IPv6Network's Returns: A list of IPv4Network's or IPv6Network's depending on what we were passed. """ while True: last_addr = None ret_array = [] optimized = False for cur_addr in addresses: if not ret_array: last_addr = cur_addr ret_array.append(cur_addr) elif (cur_addr.network_address >= last_addr.network_address and cur_addr.broadcast_address <= last_addr.broadcast_address): optimized = True elif cur_addr == list(last_addr.supernet().subnets())[1]: ret_array[-1] = last_addr = last_addr.supernet() optimized = True else: last_addr = cur_addr ret_array.append(cur_addr) addresses = ret_array if not optimized: return addresses def collapse_addresses(addresses): """Collapse a list of IP objects. Example: collapse_addresses([IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/25')]) -> [IPv4Network('192.0.2.0/24')] Args: addresses: An iterator of IPv4Network or IPv6Network objects. Returns: An iterator of the collapsed IPv(4|6)Network objects. Raises: TypeError: If passed a list of mixed version objects. """ i = 0 addrs = [] ips = [] nets = [] # split IP addresses and networks for ip in addresses: if isinstance(ip, _BaseAddress): if ips and ips[-1]._version != ip._version: raise TypeError("%s and %s are not of the same version" % ( ip, ips[-1])) ips.append(ip) elif ip._prefixlen == ip._max_prefixlen: if ips and ips[-1]._version != ip._version: raise TypeError("%s and %s are not of the same version" % ( ip, ips[-1])) try: ips.append(ip.ip) except AttributeError: ips.append(ip.network_address) else: if nets and nets[-1]._version != ip._version: raise TypeError("%s and %s are not of the same version" % ( ip, nets[-1])) nets.append(ip) # sort and dedup ips = sorted(set(ips)) nets = sorted(set(nets)) while i < len(ips): (first, last) = _find_address_range(ips[i:]) i = ips.index(last) + 1 addrs.extend(summarize_address_range(first, last)) return iter(_collapse_addresses_recursive(sorted( addrs + nets, key=_BaseNetwork._get_networks_key))) def get_mixed_type_key(obj): """Return a key suitable for sorting between networks and addresses. Address and Network objects are not sortable by default; they're fundamentally different so the expression IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24') doesn't make any sense. There are some times however, where you may wish to have ipaddress sort these for you anyway. If you need to do this, you can use this function as the key= argument to sorted(). Args: obj: either a Network or Address object. Returns: appropriate key. """ if isinstance(obj, _BaseNetwork): return obj._get_networks_key() elif isinstance(obj, _BaseAddress): return obj._get_address_key() return NotImplemented class _TotalOrderingMixin(object): # Helper that derives the other comparison operations from # __lt__ and __eq__ # We avoid functools.total_ordering because it doesn't handle # NotImplemented correctly yet (http://bugs.python.org/issue10042) def __eq__(self, other): raise NotImplementedError def __ne__(self, other): equal = self.__eq__(other) if equal is NotImplemented: return NotImplemented return not equal def __lt__(self, other): raise NotImplementedError def __le__(self, other): less = self.__lt__(other) if less is NotImplemented or not less: return self.__eq__(other) return less def __gt__(self, other): less = self.__lt__(other) if less is NotImplemented: return NotImplemented equal = self.__eq__(other) if equal is NotImplemented: return NotImplemented return not (less or equal) def __ge__(self, other): less = self.__lt__(other) if less is NotImplemented: return NotImplemented return not less class _IPAddressBase(_TotalOrderingMixin): """The mother class.""" @property def exploded(self): """Return the longhand version of the IP address as a string.""" return self._explode_shorthand_ip_string() @property def compressed(self): """Return the shorthand version of the IP address as a string.""" return str(self) @property def reverse_pointer(self): """The name of the reverse DNS pointer for the IP address, e.g.: >>> ipaddress.ip_address("127.0.0.1").reverse_pointer '1.0.0.127.in-addr.arpa' >>> ipaddress.ip_address("2001:db8::1").reverse_pointer '1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa' """ return self._reverse_pointer() @property def version(self): msg = '%200s has no version specified' % (type(self),) raise NotImplementedError(msg) def _check_int_address(self, address): if address < 0: msg = "%d (< 0) is not permitted as an IPv%d address" raise AddressValueError(msg % (address, self._version)) if address > self._ALL_ONES: msg = "%d (>= 2**%d) is not permitted as an IPv%d address" raise AddressValueError(msg % (address, self._max_prefixlen, self._version)) def _check_packed_address(self, address, expected_len): address_len = len(address) if address_len != expected_len: msg = "%r (len %d != %d) is not permitted as an IPv%d address" raise AddressValueError(msg % (address, address_len, expected_len, self._version)) def _ip_int_from_prefix(self, prefixlen): """Turn the prefix length into a bitwise netmask Args: prefixlen: An integer, the prefix length. Returns: An integer. """ return self._ALL_ONES ^ (self._ALL_ONES >> prefixlen) def _prefix_from_ip_int(self, ip_int): """Return prefix length from the bitwise netmask. Args: ip_int: An integer, the netmask in expanded bitwise format Returns: An integer, the prefix length. Raises: ValueError: If the input intermingles zeroes & ones """ trailing_zeroes = _count_righthand_zero_bits(ip_int, self._max_prefixlen) prefixlen = self._max_prefixlen - trailing_zeroes leading_ones = ip_int >> trailing_zeroes all_ones = (1 << prefixlen) - 1 if leading_ones != all_ones: byteslen = self._max_prefixlen // 8 details = _int_to_bytes(ip_int, byteslen, 'big') msg = 'Netmask pattern %r mixes zeroes & ones' raise ValueError(msg % details) return prefixlen def _report_invalid_netmask(self, netmask_str): msg = '%r is not a valid netmask' % netmask_str raise NetmaskValueError(msg) def _prefix_from_prefix_string(self, prefixlen_str): """Return prefix length from a numeric string Args: prefixlen_str: The string to be converted Returns: An integer, the prefix length. Raises: NetmaskValueError: If the input is not a valid netmask """ # int allows a leading +/- as well as surrounding whitespace, # so we ensure that isn't the case if not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str): self._report_invalid_netmask(prefixlen_str) try: prefixlen = int(prefixlen_str) except ValueError: self._report_invalid_netmask(prefixlen_str) if not (0 <= prefixlen <= self._max_prefixlen): self._report_invalid_netmask(prefixlen_str) return prefixlen def _prefix_from_ip_string(self, ip_str): """Turn a netmask/hostmask string into a prefix length Args: ip_str: The netmask/hostmask to be converted Returns: An integer, the prefix length. Raises: NetmaskValueError: If the input is not a valid netmask/hostmask """ # Parse the netmask/hostmask like an IP address. try: ip_int = self._ip_int_from_string(ip_str) except AddressValueError: self._report_invalid_netmask(ip_str) # Try matching a netmask (this would be /1*0*/ as a bitwise regexp). # Note that the two ambiguous cases (all-ones and all-zeroes) are # treated as netmasks. try: return self._prefix_from_ip_int(ip_int) except ValueError: pass # Invert the bits, and try matching a /0+1+/ hostmask instead. ip_int ^= self._ALL_ONES try: return self._prefix_from_ip_int(ip_int) except ValueError: self._report_invalid_netmask(ip_str) class _BaseAddress(_IPAddressBase): """A generic IP object. This IP class contains the version independent methods which are used by single IP addresses. """ def __init__(self, address): if (not isinstance(address, bytes) and '/' in str(address)): raise AddressValueError("Unexpected '/' in %r" % address) def __int__(self): return self._ip def __eq__(self, other): try: return (self._ip == other._ip and self._version == other._version) except AttributeError: return NotImplemented def __lt__(self, other): if self._version != other._version: raise TypeError('%s and %s are not of the same version' % ( self, other)) if not isinstance(other, _BaseAddress): raise TypeError('%s and %s are not of the same type' % ( self, other)) if self._ip != other._ip: return self._ip < other._ip return False # Shorthand for Integer addition and subtraction. This is not # meant to ever support addition/subtraction of addresses. def __add__(self, other): if not isinstance(other, int): return NotImplemented return self.__class__(int(self) + other) def __sub__(self, other): if not isinstance(other, int): return NotImplemented return self.__class__(int(self) - other) def __repr__(self): return '%s(%r)' % (self.__class__.__name__, str(self)) def __str__(self): return str(self._string_from_ip_int(self._ip)) def __hash__(self): return hash(hex(int(self._ip))) def _get_address_key(self): return (self._version, self) class _BaseNetwork(_IPAddressBase): """A generic IP network object. This IP class contains the version independent methods which are used by networks. """ def __init__(self, address): self._cache = {} def __repr__(self): return '%s(%r)' % (self.__class__.__name__, str(self)) def __str__(self): return '%s/%d' % (self.network_address, self.prefixlen) def hosts(self): """Generate Iterator over usable hosts in a network. This is like __iter__ except it doesn't return the network or broadcast addresses. """ network = int(self.network_address) broadcast = int(self.broadcast_address) for x in long_range(network + 1, broadcast): yield self._address_class(x) def __iter__(self): network = int(self.network_address) broadcast = int(self.broadcast_address) for x in long_range(network, broadcast + 1): yield self._address_class(x) def __getitem__(self, n): network = int(self.network_address) broadcast = int(self.broadcast_address) if n >= 0: if network + n > broadcast: raise IndexError return self._address_class(network + n) else: n += 1 if broadcast + n < network: raise IndexError return self._address_class(broadcast + n) def __lt__(self, other): if self._version != other._version: raise TypeError('%s and %s are not of the same version' % ( self, other)) if not isinstance(other, _BaseNetwork): raise TypeError('%s and %s are not of the same type' % ( self, other)) if self.network_address != other.network_address: return self.network_address < other.network_address if self.netmask != other.netmask: return self.netmask < other.netmask return False def __eq__(self, other): try: return (self._version == other._version and self.network_address == other.network_address and int(self.netmask) == int(other.netmask)) except AttributeError: return NotImplemented def __hash__(self): return hash(int(self.network_address) ^ int(self.netmask)) def __contains__(self, other): # always false if one is v4 and the other is v6. if self._version != other._version: return False # dealing with another network. if isinstance(other, _BaseNetwork): return False # dealing with another address else: # address return (int(self.network_address) <= int(other._ip) <= int(self.broadcast_address)) def overlaps(self, other): """Tell if self is partly contained in other.""" return self.network_address in other or ( self.broadcast_address in other or ( other.network_address in self or ( other.broadcast_address in self))) @property def broadcast_address(self): x = self._cache.get('broadcast_address') if x is None: x = self._address_class(int(self.network_address) | int(self.hostmask)) self._cache['broadcast_address'] = x return x @property def hostmask(self): x = self._cache.get('hostmask') if x is None: x = self._address_class(int(self.netmask) ^ self._ALL_ONES) self._cache['hostmask'] = x return x @property def with_prefixlen(self): return '%s/%d' % (self.network_address, self._prefixlen) @property def with_netmask(self): return '%s/%s' % (self.network_address, self.netmask) @property def with_hostmask(self): return '%s/%s' % (self.network_address, self.hostmask) @property def num_addresses(self): """Number of hosts in the current subnet.""" return int(self.broadcast_address) - int(self.network_address) + 1 @property def _address_class(self): # Returning bare address objects (rather than interfaces) allows for # more consistent behaviour across the network address, broadcast # address and individual host addresses. msg = '%200s has no associated address class' % (type(self),) raise NotImplementedError(msg) @property def prefixlen(self): return self._prefixlen def address_exclude(self, other): """Remove an address from a larger block. For example: addr1 = ip_network('192.0.2.0/28') addr2 = ip_network('192.0.2.1/32') addr1.address_exclude(addr2) = [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'), IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')] or IPv6: addr1 = ip_network('2001:db8::1/32') addr2 = ip_network('2001:db8::1/128') addr1.address_exclude(addr2) = [ip_network('2001:db8::1/128'), ip_network('2001:db8::2/127'), ip_network('2001:db8::4/126'), ip_network('2001:db8::8/125'), ... ip_network('2001:db8:8000::/33')] Args: other: An IPv4Network or IPv6Network object of the same type. Returns: An iterator of the IPv(4|6)Network objects which is self minus other. Raises: TypeError: If self and other are of differing address versions, or if other is not a network object. ValueError: If other is not completely contained by self. """ if not self._version == other._version: raise TypeError("%s and %s are not of the same version" % ( self, other)) if not isinstance(other, _BaseNetwork): raise TypeError("%s is not a network object" % other) if not (other.network_address >= self.network_address and other.broadcast_address <= self.broadcast_address): raise ValueError('%s not contained in %s' % (other, self)) if other == self: raise StopIteration # Make sure we're comparing the network of other. other = other.__class__('%s/%s' % (other.network_address, other.prefixlen)) s1, s2 = self.subnets() while s1 != other and s2 != other: if (other.network_address >= s1.network_address and other.broadcast_address <= s1.broadcast_address): yield s2 s1, s2 = s1.subnets() elif (other.network_address >= s2.network_address and other.broadcast_address <= s2.broadcast_address): yield s1 s1, s2 = s2.subnets() else: # If we got here, there's a bug somewhere. raise AssertionError('Error performing exclusion: ' 's1: %s s2: %s other: %s' % (s1, s2, other)) if s1 == other: yield s2 elif s2 == other: yield s1 else: # If we got here, there's a bug somewhere. raise AssertionError('Error performing exclusion: ' 's1: %s s2: %s other: %s' % (s1, s2, other)) def compare_networks(self, other): """Compare two IP objects. This is only concerned about the comparison of the integer representation of the network addresses. This means that the host bits aren't considered at all in this method. If you want to compare host bits, you can easily enough do a 'HostA._ip < HostB._ip' Args: other: An IP object. Returns: If the IP versions of self and other are the same, returns: -1 if self < other: eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25') IPv6Network('2001:db8::1000/124') < IPv6Network('2001:db8::2000/124') 0 if self == other eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24') IPv6Network('2001:db8::1000/124') == IPv6Network('2001:db8::1000/124') 1 if self > other eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25') IPv6Network('2001:db8::2000/124') > IPv6Network('2001:db8::1000/124') Raises: TypeError if the IP versions are different. """ # does this need to raise a ValueError? if self._version != other._version: raise TypeError('%s and %s are not of the same type' % ( self, other)) # self._version == other._version below here: if self.network_address < other.network_address: return -1 if self.network_address > other.network_address: return 1 # self.network_address == other.network_address below here: if self.netmask < other.netmask: return -1 if self.netmask > other.netmask: return 1 return 0 def _get_networks_key(self): """Network-only key function. Returns an object that identifies this address' network and netmask. This function is a suitable "key" argument for sorted() and list.sort(). """ return (self._version, self.network_address, self.netmask) def subnets(self, prefixlen_diff=1, new_prefix=None): """The subnets which join to make the current subnet. In the case that self contains only one IP (self._prefixlen == 32 for IPv4 or self._prefixlen == 128 for IPv6), yield an iterator with just ourself. Args: prefixlen_diff: An integer, the amount the prefix length should be increased by. This should not be set if new_prefix is also set. new_prefix: The desired new prefix length. This must be a larger number (smaller prefix) than the existing prefix. This should not be set if prefixlen_diff is also set. Returns: An iterator of IPv(4|6) objects. Raises: ValueError: The prefixlen_diff is too small or too large. OR prefixlen_diff and new_prefix are both set or new_prefix is a smaller number than the current prefix (smaller number means a larger network) """ if self._prefixlen == self._max_prefixlen: yield self return if new_prefix is not None: if new_prefix < self._prefixlen: raise ValueError('new prefix must be longer') if prefixlen_diff != 1: raise ValueError('cannot set prefixlen_diff and new_prefix') prefixlen_diff = new_prefix - self._prefixlen if prefixlen_diff < 0: raise ValueError('prefix length diff must be > 0') new_prefixlen = self._prefixlen + prefixlen_diff if new_prefixlen > self._max_prefixlen: raise ValueError( 'prefix length diff %d is invalid for netblock %s' % ( new_prefixlen, self)) first = self.__class__('%s/%s' % (self.network_address, self._prefixlen + prefixlen_diff)) yield first current = first while True: broadcast = current.broadcast_address if broadcast == self.broadcast_address: return new_addr = self._address_class(int(broadcast) + 1) current = self.__class__('%s/%s' % (new_addr, new_prefixlen)) yield current def supernet(self, prefixlen_diff=1, new_prefix=None): """The supernet containing the current network. Args: prefixlen_diff: An integer, the amount the prefix length of the network should be decreased by. For example, given a /24 network and a prefixlen_diff of 3, a supernet with a /21 netmask is returned. Returns: An IPv4 network object. Raises: ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have a negative prefix length. OR If prefixlen_diff and new_prefix are both set or new_prefix is a larger number than the current prefix (larger number means a smaller network) """ if self._prefixlen == 0: return self if new_prefix is not None: if new_prefix > self._prefixlen: raise ValueError('new prefix must be shorter') if prefixlen_diff != 1: raise ValueError('cannot set prefixlen_diff and new_prefix') prefixlen_diff = self._prefixlen - new_prefix if self.prefixlen - prefixlen_diff < 0: raise ValueError( 'current prefixlen is %d, cannot have a prefixlen_diff of %d' % (self.prefixlen, prefixlen_diff)) # TODO (pmoody): optimize this. t = self.__class__('%s/%d' % (self.network_address, self.prefixlen - prefixlen_diff), strict=False) return t.__class__('%s/%d' % (t.network_address, t.prefixlen)) @property def is_multicast(self): """Test if the address is reserved for multicast use. Returns: A boolean, True if the address is a multicast address. See RFC 2373 2.7 for details. """ return (self.network_address.is_multicast and self.broadcast_address.is_multicast) @property def is_reserved(self): """Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within one of the reserved IPv6 Network ranges. """ return (self.network_address.is_reserved and self.broadcast_address.is_reserved) @property def is_link_local(self): """Test if the address is reserved for link-local. Returns: A boolean, True if the address is reserved per RFC 4291. """ return (self.network_address.is_link_local and self.broadcast_address.is_link_local) @property def is_private(self): """Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per iana-ipv4-special-registry or iana-ipv6-special-registry. """ return (self.network_address.is_private and self.broadcast_address.is_private) @property def is_global(self): """Test if this address is allocated for public networks. Returns: A boolean, True if the address is not reserved per iana-ipv4-special-registry or iana-ipv6-special-registry. """ return not self.is_private @property def is_unspecified(self): """Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in RFC 2373 2.5.2. """ return (self.network_address.is_unspecified and self.broadcast_address.is_unspecified) @property def is_loopback(self): """Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback address as defined in RFC 2373 2.5.3. """ return (self.network_address.is_loopback and self.broadcast_address.is_loopback) class _BaseV4(object): """Base IPv4 object. The following methods are used by IPv4 objects in both single IP addresses and networks. """ # Equivalent to 255.255.255.255 or 32 bits of 1's. _ALL_ONES = (2**IPV4LENGTH) - 1 _DECIMAL_DIGITS = frozenset('0123456789') # the valid octets for host and netmasks. only useful for IPv4. _valid_mask_octets = frozenset((255, 254, 252, 248, 240, 224, 192, 128, 0)) def __init__(self, address): self._version = 4 self._max_prefixlen = IPV4LENGTH def _explode_shorthand_ip_string(self): return str(self) def _ip_int_from_string(self, ip_str): """Turn the given IP string into an integer for comparison. Args: ip_str: A string, the IP ip_str. Returns: The IP ip_str as an integer. Raises: AddressValueError: if ip_str isn't a valid IPv4 Address. """ if not ip_str: raise AddressValueError('Address cannot be empty') octets = ip_str.split('.') if len(octets) != 4: raise AddressValueError("Expected 4 octets in %r" % ip_str) try: return _int_from_bytes(map(self._parse_octet, octets), 'big') except ValueError as exc: raise AddressValueError("%s in %r" % (exc, ip_str)) def _parse_octet(self, octet_str): """Convert a decimal octet into an integer. Args: octet_str: A string, the number to parse. Returns: The octet as an integer. Raises: ValueError: if the octet isn't strictly a decimal from [0..255]. """ if not octet_str: raise ValueError("Empty octet not permitted") # Whitelist the characters, since int() allows a lot of bizarre stuff. if not self._DECIMAL_DIGITS.issuperset(octet_str): msg = "Only decimal digits permitted in %r" raise ValueError(msg % octet_str) # We do the length check second, since the invalid character error # is likely to be more informative for the user if len(octet_str) > 3: msg = "At most 3 characters permitted in %r" raise ValueError(msg % octet_str) # Convert to integer (we know digits are legal) octet_int = int(octet_str, 10) # Any octets that look like they *might* be written in octal, # and which don't look exactly the same in both octal and # decimal are rejected as ambiguous if octet_int > 7 and octet_str[0] == '0': msg = "Ambiguous (octal/decimal) value in %r not permitted" raise ValueError(msg % octet_str) if octet_int > 255: raise ValueError("Octet %d (> 255) not permitted" % octet_int) return octet_int def _string_from_ip_int(self, ip_int): """Turns a 32-bit integer into dotted decimal notation. Args: ip_int: An integer, the IP address. Returns: The IP address as a string in dotted decimal notation. """ return '.'.join(map(str, _int_to_bytes(ip_int, 4, 'big'))) def _is_valid_netmask(self, netmask): """Verify that the netmask is valid. Args: netmask: A string, either a prefix or dotted decimal netmask. Returns: A boolean, True if the prefix represents a valid IPv4 netmask. """ mask = netmask.split('.') if len(mask) == 4: try: for x in mask: if int(x) not in self._valid_mask_octets: return False except ValueError: # Found something that isn't an integer or isn't valid return False for idx, y in enumerate(mask): if idx > 0 and y > mask[idx - 1]: return False return True try: netmask = int(netmask) except ValueError: return False return 0 <= netmask <= self._max_prefixlen def _is_hostmask(self, ip_str): """Test if the IP string is a hostmask (rather than a netmask). Args: ip_str: A string, the potential hostmask. Returns: A boolean, True if the IP string is a hostmask. """ bits = ip_str.split('.') try: parts = [x for x in map(int, bits) if x in self._valid_mask_octets] except ValueError: return False if len(parts) != len(bits): return False if parts[0] < parts[-1]: return True return False def _reverse_pointer(self): """Return the reverse DNS pointer name for the IPv4 address. This implements the method described in RFC1035 3.5. """ reverse_octets = str(self).split('.')[::-1] return '.'.join(reverse_octets) + '.in-addr.arpa' @property def max_prefixlen(self): return self._max_prefixlen @property def version(self): return self._version class IPv4Address(_BaseV4, _BaseAddress): """Represent and manipulate single IPv4 Addresses.""" def __init__(self, address): """ Args: address: A string or integer representing the IP Additionally, an integer can be passed, so IPv4Address('192.0.2.1') == IPv4Address(3221225985). or, more generally IPv4Address(int(IPv4Address('192.0.2.1'))) == IPv4Address('192.0.2.1') Raises: AddressValueError: If ipaddress isn't a valid IPv4 address. """ _BaseAddress.__init__(self, address) _BaseV4.__init__(self, address) # Efficient constructor from integer. if isinstance(address, int): self._check_int_address(address) self._ip = address return # Constructing from a packed address if isinstance(address, bytes): self._check_packed_address(address, 4) self._ip = _int_from_bytes(address, 'big') return # Assume input argument to be string or any object representation # which converts into a formatted IP string. addr_str = str(address) self._ip = self._ip_int_from_string(addr_str) @property def packed(self): """The binary representation of this address.""" return v4_int_to_packed(self._ip) @property def is_reserved(self): """Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within the reserved IPv4 Network range. """ reserved_network = IPv4Network('240.0.0.0/4') return self in reserved_network @property def is_private(self): """Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per iana-ipv4-special-registry. """ return (self in IPv4Network('0.0.0.0/8') or self in IPv4Network('10.0.0.0/8') or self in IPv4Network('127.0.0.0/8') or self in IPv4Network('169.254.0.0/16') or self in IPv4Network('172.16.0.0/12') or self in IPv4Network('192.0.0.0/29') or self in IPv4Network('192.0.0.170/31') or self in IPv4Network('192.0.2.0/24') or self in IPv4Network('192.168.0.0/16') or self in IPv4Network('198.18.0.0/15') or self in IPv4Network('198.51.100.0/24') or self in IPv4Network('203.0.113.0/24') or self in IPv4Network('240.0.0.0/4') or self in IPv4Network('255.255.255.255/32')) @property def is_multicast(self): """Test if the address is reserved for multicast use. Returns: A boolean, True if the address is multicast. See RFC 3171 for details. """ multicast_network = IPv4Network('224.0.0.0/4') return self in multicast_network @property def is_unspecified(self): """Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in RFC 5735 3. """ unspecified_address = IPv4Address('0.0.0.0') return self == unspecified_address @property def is_loopback(self): """Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback per RFC 3330. """ loopback_network = IPv4Network('127.0.0.0/8') return self in loopback_network @property def is_link_local(self): """Test if the address is reserved for link-local. Returns: A boolean, True if the address is link-local per RFC 3927. """ linklocal_network = IPv4Network('169.254.0.0/16') return self in linklocal_network class IPv4Interface(IPv4Address): def __init__(self, address): if isinstance(address, (bytes, int)): IPv4Address.__init__(self, address) self.network = IPv4Network(self._ip) self._prefixlen = self._max_prefixlen return addr = _split_optional_netmask(address) IPv4Address.__init__(self, addr[0]) self.network = IPv4Network(address, strict=False) self._prefixlen = self.network._prefixlen self.netmask = self.network.netmask self.hostmask = self.network.hostmask def __str__(self): return '%s/%d' % (self._string_from_ip_int(self._ip), self.network.prefixlen) def __eq__(self, other): address_equal = IPv4Address.__eq__(self, other) if not address_equal or address_equal is NotImplemented: return address_equal try: return self.network == other.network except AttributeError: # An interface with an associated network is NOT the # same as an unassociated address. That's why the hash # takes the extra info into account. return False def __lt__(self, other): address_less = IPv4Address.__lt__(self, other) if address_less is NotImplemented: return NotImplemented try: return self.network < other.network except AttributeError: # We *do* allow addresses and interfaces to be sorted. The # unassociated address is considered less than all interfaces. return False def __hash__(self): return self._ip ^ self._prefixlen ^ int(self.network.network_address) @property def ip(self): return IPv4Address(self._ip) @property def with_prefixlen(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self._prefixlen) @property def with_netmask(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self.netmask) @property def with_hostmask(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self.hostmask) class IPv4Network(_BaseV4, _BaseNetwork): """This class represents and manipulates 32-bit IPv4 network + addresses.. Attributes: [examples for IPv4Network('192.0.2.0/27')] .network_address: IPv4Address('192.0.2.0') .hostmask: IPv4Address('0.0.0.31') .broadcast_address: IPv4Address('192.0.2.32') .netmask: IPv4Address('255.255.255.224') .prefixlen: 27 """ # Class to use when creating address objects _address_class = IPv4Address def __init__(self, address, strict=True): """Instantiate a new IPv4 network object. Args: address: A string or integer representing the IP [& network]. '192.0.2.0/24' '192.0.2.0/255.255.255.0' '192.0.0.2/0.0.0.255' are all functionally the same in IPv4. Similarly, '192.0.2.1' '192.0.2.1/255.255.255.255' '192.0.2.1/32' are also functionally equivalent. That is to say, failing to provide a subnetmask will create an object with a mask of /32. If the mask (portion after the / in the argument) is given in dotted quad form, it is treated as a netmask if it starts with a non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it starts with a zero field (e.g. 0.255.255.255 == /8), with the single exception of an all-zero mask which is treated as a netmask == /0. If no mask is given, a default of /32 is used. Additionally, an integer can be passed, so IPv4Network('192.0.2.1') == IPv4Network(3221225985) or, more generally IPv4Interface(int(IPv4Interface('192.0.2.1'))) == IPv4Interface('192.0.2.1') Raises: AddressValueError: If ipaddress isn't a valid IPv4 address. NetmaskValueError: If the netmask isn't valid for an IPv4 address. ValueError: If strict is True and a network address is not supplied. """ _BaseV4.__init__(self, address) _BaseNetwork.__init__(self, address) # Constructing from a packed address if isinstance(address, bytes): self.network_address = IPv4Address(address) self._prefixlen = self._max_prefixlen self.netmask = IPv4Address(self._ALL_ONES) #fixme: address/network test here return # Efficient constructor from integer. if isinstance(address, int): self.network_address = IPv4Address(address) self._prefixlen = self._max_prefixlen self.netmask = IPv4Address(self._ALL_ONES) #fixme: address/network test here. return # Assume input argument to be string or any object representation # which converts into a formatted IP prefix string. addr = _split_optional_netmask(address) self.network_address = IPv4Address(self._ip_int_from_string(addr[0])) if len(addr) == 2: try: # Check for a netmask in prefix length form self._prefixlen = self._prefix_from_prefix_string(addr[1]) except NetmaskValueError: # Check for a netmask or hostmask in dotted-quad form. # This may raise NetmaskValueError. self._prefixlen = self._prefix_from_ip_string(addr[1]) else: self._prefixlen = self._max_prefixlen self.netmask = IPv4Address(self._ip_int_from_prefix(self._prefixlen)) if strict: if (IPv4Address(int(self.network_address) & int(self.netmask)) != self.network_address): raise ValueError('%s has host bits set' % self) self.network_address = IPv4Address(int(self.network_address) & int(self.netmask)) if self._prefixlen == (self._max_prefixlen - 1): self.hosts = self.__iter__ @property def is_global(self): """Test if this address is allocated for public networks. Returns: A boolean, True if the address is not reserved per iana-ipv4-special-registry. """ return (not (self.network_address in IPv4Network('100.64.0.0/10') and self.broadcast_address in IPv4Network('100.64.0.0/10')) and not self.is_private) class _BaseV6(object): """Base IPv6 object. The following methods are used by IPv6 objects in both single IP addresses and networks. """ _ALL_ONES = (2**IPV6LENGTH) - 1 _HEXTET_COUNT = 8 _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef') def __init__(self, address): self._version = 6 self._max_prefixlen = IPV6LENGTH def _ip_int_from_string(self, ip_str): """Turn an IPv6 ip_str into an integer. Args: ip_str: A string, the IPv6 ip_str. Returns: An int, the IPv6 address Raises: AddressValueError: if ip_str isn't a valid IPv6 Address. """ if not ip_str: raise AddressValueError('Address cannot be empty') parts = ip_str.split(':') # An IPv6 address needs at least 2 colons (3 parts). _min_parts = 3 if len(parts) < _min_parts: msg = "At least %d parts expected in %r" % (_min_parts, ip_str) raise AddressValueError(msg) # If the address has an IPv4-style suffix, convert it to hexadecimal. if '.' in parts[-1]: try: ipv4_int = IPv4Address(parts.pop())._ip except AddressValueError as exc: raise AddressValueError("%s in %r" % (exc, ip_str)) parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF)) parts.append('%x' % (ipv4_int & 0xFFFF)) # An IPv6 address can't have more than 8 colons (9 parts). # The extra colon comes from using the "::" notation for a single # leading or trailing zero part. _max_parts = self._HEXTET_COUNT + 1 if len(parts) > _max_parts: msg = "At most %d colons permitted in %r" % (_max_parts-1, ip_str) raise AddressValueError(msg) # Disregarding the endpoints, find '::' with nothing in between. # This indicates that a run of zeroes has been skipped. skip_index = None for i in range(1, len(parts) - 1): if not parts[i]: if skip_index is not None: # Can't have more than one '::' msg = "At most one '::' permitted in %r" % ip_str raise AddressValueError(msg) skip_index = i # parts_hi is the number of parts to copy from above/before the '::' # parts_lo is the number of parts to copy from below/after the '::' if skip_index is not None: # If we found a '::', then check if it also covers the endpoints. parts_hi = skip_index parts_lo = len(parts) - skip_index - 1 if not parts[0]: parts_hi -= 1 if parts_hi: msg = "Leading ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # ^: requires ^:: if not parts[-1]: parts_lo -= 1 if parts_lo: msg = "Trailing ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # :$ requires ::$ parts_skipped = self._HEXTET_COUNT - (parts_hi + parts_lo) if parts_skipped < 1: msg = "Expected at most %d other parts with '::' in %r" raise AddressValueError(msg % (self._HEXTET_COUNT-1, ip_str)) else: # Otherwise, allocate the entire address to parts_hi. The # endpoints could still be empty, but _parse_hextet() will check # for that. if len(parts) != self._HEXTET_COUNT: msg = "Exactly %d parts expected without '::' in %r" raise AddressValueError(msg % (self._HEXTET_COUNT, ip_str)) if not parts[0]: msg = "Leading ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # ^: requires ^:: if not parts[-1]: msg = "Trailing ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # :$ requires ::$ parts_hi = len(parts) parts_lo = 0 parts_skipped = 0 try: # Now, parse the hextets into a 128-bit integer. ip_int = 0 for i in range(parts_hi): ip_int <<= 16 ip_int |= self._parse_hextet(parts[i]) ip_int <<= 16 * parts_skipped for i in range(-parts_lo, 0): ip_int <<= 16 ip_int |= self._parse_hextet(parts[i]) return ip_int except ValueError as exc: raise AddressValueError("%s in %r" % (exc, ip_str)) def _parse_hextet(self, hextet_str): """Convert an IPv6 hextet string into an integer. Args: hextet_str: A string, the number to parse. Returns: The hextet as an integer. Raises: ValueError: if the input isn't strictly a hex number from [0..FFFF]. """ # Whitelist the characters, since int() allows a lot of bizarre stuff. if not self._HEX_DIGITS.issuperset(hextet_str): raise ValueError("Only hex digits permitted in %r" % hextet_str) # We do the length check second, since the invalid character error # is likely to be more informative for the user if len(hextet_str) > 4: msg = "At most 4 characters permitted in %r" raise ValueError(msg % hextet_str) # Length check means we can skip checking the integer value return int(hextet_str, 16) def _compress_hextets(self, hextets): """Compresses a list of hextets. Compresses a list of strings, replacing the longest continuous sequence of "0" in the list with "" and adding empty strings at the beginning or at the end of the string such that subsequently calling ":".join(hextets) will produce the compressed version of the IPv6 address. Args: hextets: A list of strings, the hextets to compress. Returns: A list of strings. """ best_doublecolon_start = -1 best_doublecolon_len = 0 doublecolon_start = -1 doublecolon_len = 0 for index, hextet in enumerate(hextets): if hextet == '0': doublecolon_len += 1 if doublecolon_start == -1: # Start of a sequence of zeros. doublecolon_start = index if doublecolon_len > best_doublecolon_len: # This is the longest sequence of zeros so far. best_doublecolon_len = doublecolon_len best_doublecolon_start = doublecolon_start else: doublecolon_len = 0 doublecolon_start = -1 if best_doublecolon_len > 1: best_doublecolon_end = (best_doublecolon_start + best_doublecolon_len) # For zeros at the end of the address. if best_doublecolon_end == len(hextets): hextets += [''] hextets[best_doublecolon_start:best_doublecolon_end] = [''] # For zeros at the beginning of the address. if best_doublecolon_start == 0: hextets = [''] + hextets return hextets def _string_from_ip_int(self, ip_int=None): """Turns a 128-bit integer into hexadecimal notation. Args: ip_int: An integer, the IP address. Returns: A string, the hexadecimal representation of the address. Raises: ValueError: The address is bigger than 128 bits of all ones. """ if ip_int is None: ip_int = int(self._ip) if ip_int > self._ALL_ONES: raise ValueError('IPv6 address is too large') hex_str = '%032x' % ip_int hextets = ['%x' % int(hex_str[x:x+4], 16) for x in range(0, 32, 4)] hextets = self._compress_hextets(hextets) return ':'.join(hextets) def _explode_shorthand_ip_string(self): """Expand a shortened IPv6 address. Args: ip_str: A string, the IPv6 address. Returns: A string, the expanded IPv6 address. """ if isinstance(self, IPv6Network): ip_str = str(self.network_address) elif isinstance(self, IPv6Interface): ip_str = str(self.ip) else: ip_str = str(self) ip_int = self._ip_int_from_string(ip_str) hex_str = '%032x' % ip_int parts = [hex_str[x:x+4] for x in range(0, 32, 4)] if isinstance(self, (_BaseNetwork, IPv6Interface)): return '%s/%d' % (':'.join(parts), self._prefixlen) return ':'.join(parts) def _reverse_pointer(self): """Return the reverse DNS pointer name for the IPv6 address. This implements the method described in RFC3596 2.5. """ reverse_chars = self.exploded[::-1].replace(':', '') return '.'.join(reverse_chars) + '.ip6.arpa' @property def max_prefixlen(self): return self._max_prefixlen @property def version(self): return self._version class IPv6Address(_BaseV6, _BaseAddress): """Represent and manipulate single IPv6 Addresses.""" def __init__(self, address): """Instantiate a new IPv6 address object. Args: address: A string or integer representing the IP Additionally, an integer can be passed, so IPv6Address('2001:db8::') == IPv6Address(42540766411282592856903984951653826560) or, more generally IPv6Address(int(IPv6Address('2001:db8::'))) == IPv6Address('2001:db8::') Raises: AddressValueError: If address isn't a valid IPv6 address. """ _BaseAddress.__init__(self, address) _BaseV6.__init__(self, address) # Efficient constructor from integer. if isinstance(address, int): self._check_int_address(address) self._ip = address return # Constructing from a packed address if isinstance(address, bytes): self._check_packed_address(address, 16) self._ip = _int_from_bytes(address, 'big') return # Assume input argument to be string or any object representation # which converts into a formatted IP string. addr_str = str(address) self._ip = self._ip_int_from_string(addr_str) @property def packed(self): """The binary representation of this address.""" return v6_int_to_packed(self._ip) @property def is_multicast(self): """Test if the address is reserved for multicast use. Returns: A boolean, True if the address is a multicast address. See RFC 2373 2.7 for details. """ multicast_network = IPv6Network('ff00::/8') return self in multicast_network @property def is_reserved(self): """Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within one of the reserved IPv6 Network ranges. """ reserved_networks = [IPv6Network('::/8'), IPv6Network('100::/8'), IPv6Network('200::/7'), IPv6Network('400::/6'), IPv6Network('800::/5'), IPv6Network('1000::/4'), IPv6Network('4000::/3'), IPv6Network('6000::/3'), IPv6Network('8000::/3'), IPv6Network('A000::/3'), IPv6Network('C000::/3'), IPv6Network('E000::/4'), IPv6Network('F000::/5'), IPv6Network('F800::/6'), IPv6Network('FE00::/9')] return any(self in x for x in reserved_networks) @property def is_link_local(self): """Test if the address is reserved for link-local. Returns: A boolean, True if the address is reserved per RFC 4291. """ linklocal_network = IPv6Network('fe80::/10') return self in linklocal_network @property def is_site_local(self): """Test if the address is reserved for site-local. Note that the site-local address space has been deprecated by RFC 3879. Use is_private to test if this address is in the space of unique local addresses as defined by RFC 4193. Returns: A boolean, True if the address is reserved per RFC 3513 2.5.6. """ sitelocal_network = IPv6Network('fec0::/10') return self in sitelocal_network @property def is_private(self): """Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per iana-ipv6-special-registry. """ return (self in IPv6Network('::1/128') or self in IPv6Network('::/128') or self in IPv6Network('::ffff:0:0/96') or self in IPv6Network('100::/64') or self in IPv6Network('2001::/23') or self in IPv6Network('2001:2::/48') or self in IPv6Network('2001:db8::/32') or self in IPv6Network('2001:10::/28') or self in IPv6Network('fc00::/7') or self in IPv6Network('fe80::/10')) @property def is_global(self): """Test if this address is allocated for public networks. Returns: A boolean, true if the address is not reserved per iana-ipv6-special-registry. """ return not self.is_private @property def is_unspecified(self): """Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in RFC 2373 2.5.2. """ return self._ip == 0 @property def is_loopback(self): """Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback address as defined in RFC 2373 2.5.3. """ return self._ip == 1 @property def ipv4_mapped(self): """Return the IPv4 mapped address. Returns: If the IPv6 address is a v4 mapped address, return the IPv4 mapped address. Return None otherwise. """ if (self._ip >> 32) != 0xFFFF: return None return IPv4Address(self._ip & 0xFFFFFFFF) @property def teredo(self): """Tuple of embedded teredo IPs. Returns: Tuple of the (server, client) IPs or None if the address doesn't appear to be a teredo address (doesn't start with 2001::/32) """ if (self._ip >> 96) != 0x20010000: return None return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF), IPv4Address(~self._ip & 0xFFFFFFFF)) @property def sixtofour(self): """Return the IPv4 6to4 embedded address. Returns: The IPv4 6to4-embedded address if present or None if the address doesn't appear to contain a 6to4 embedded address. """ if (self._ip >> 112) != 0x2002: return None return IPv4Address((self._ip >> 80) & 0xFFFFFFFF) class IPv6Interface(IPv6Address): def __init__(self, address): if isinstance(address, (bytes, int)): IPv6Address.__init__(self, address) self.network = IPv6Network(self._ip) self._prefixlen = self._max_prefixlen return addr = _split_optional_netmask(address) IPv6Address.__init__(self, addr[0]) self.network = IPv6Network(address, strict=False) self.netmask = self.network.netmask self._prefixlen = self.network._prefixlen self.hostmask = self.network.hostmask def __str__(self): return '%s/%d' % (self._string_from_ip_int(self._ip), self.network.prefixlen) def __eq__(self, other): address_equal = IPv6Address.__eq__(self, other) if not address_equal or address_equal is NotImplemented: return address_equal try: return self.network == other.network except AttributeError: # An interface with an associated network is NOT the # same as an unassociated address. That's why the hash # takes the extra info into account. return False def __lt__(self, other): address_less = IPv6Address.__lt__(self, other) if address_less is NotImplemented: return NotImplemented try: return self.network < other.network except AttributeError: # We *do* allow addresses and interfaces to be sorted. The # unassociated address is considered less than all interfaces. return False def __hash__(self): return self._ip ^ self._prefixlen ^ int(self.network.network_address) @property def ip(self): return IPv6Address(self._ip) @property def with_prefixlen(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self._prefixlen) @property def with_netmask(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self.netmask) @property def with_hostmask(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self.hostmask) @property def is_unspecified(self): return self._ip == 0 and self.network.is_unspecified @property def is_loopback(self): return self._ip == 1 and self.network.is_loopback class IPv6Network(_BaseV6, _BaseNetwork): """This class represents and manipulates 128-bit IPv6 networks. Attributes: [examples for IPv6('2001:db8::1000/124')] .network_address: IPv6Address('2001:db8::1000') .hostmask: IPv6Address('::f') .broadcast_address: IPv6Address('2001:db8::100f') .netmask: IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0') .prefixlen: 124 """ # Class to use when creating address objects _address_class = IPv6Address def __init__(self, address, strict=True): """Instantiate a new IPv6 Network object. Args: address: A string or integer representing the IPv6 network or the IP and prefix/netmask. '2001:db8::/128' '2001:db8:0000:0000:0000:0000:0000:0000/128' '2001:db8::' are all functionally the same in IPv6. That is to say, failing to provide a subnetmask will create an object with a mask of /128. Additionally, an integer can be passed, so IPv6Network('2001:db8::') == IPv6Network(42540766411282592856903984951653826560) or, more generally IPv6Network(int(IPv6Network('2001:db8::'))) == IPv6Network('2001:db8::') strict: A boolean. If true, ensure that we have been passed A true network address, eg, 2001:db8::1000/124 and not an IP address on a network, eg, 2001:db8::1/124. Raises: AddressValueError: If address isn't a valid IPv6 address. NetmaskValueError: If the netmask isn't valid for an IPv6 address. ValueError: If strict was True and a network address was not supplied. """ _BaseV6.__init__(self, address) _BaseNetwork.__init__(self, address) # Efficient constructor from integer. if isinstance(address, int): self.network_address = IPv6Address(address) self._prefixlen = self._max_prefixlen self.netmask = IPv6Address(self._ALL_ONES) return # Constructing from a packed address if isinstance(address, bytes): self.network_address = IPv6Address(address) self._prefixlen = self._max_prefixlen self.netmask = IPv6Address(self._ALL_ONES) return # Assume input argument to be string or any object representation # which converts into a formatted IP prefix string. addr = _split_optional_netmask(address) self.network_address = IPv6Address(self._ip_int_from_string(addr[0])) if len(addr) == 2: # This may raise NetmaskValueError self._prefixlen = self._prefix_from_prefix_string(addr[1]) else: self._prefixlen = self._max_prefixlen self.netmask = IPv6Address(self._ip_int_from_prefix(self._prefixlen)) if strict: if (IPv6Address(int(self.network_address) & int(self.netmask)) != self.network_address): raise ValueError('%s has host bits set' % self) self.network_address = IPv6Address(int(self.network_address) & int(self.netmask)) if self._prefixlen == (self._max_prefixlen - 1): self.hosts = self.__iter__ def hosts(self): """Generate Iterator over usable hosts in a network. This is like __iter__ except it doesn't return the Subnet-Router anycast address. """ network = int(self.network_address) broadcast = int(self.broadcast_address) for x in long_range(1, broadcast - network + 1): yield self._address_class(network + x) @property def is_site_local(self): """Test if the address is reserved for site-local. Note that the site-local address space has been deprecated by RFC 3879. Use is_private to test if this address is in the space of unique local addresses as defined by RFC 4193. Returns: A boolean, True if the address is reserved per RFC 3513 2.5.6. """ return (self.network_address.is_site_local and self.broadcast_address.is_site_local)
saltstack/salt
salt/ext/ipaddress.py
_count_righthand_zero_bits
python
def _count_righthand_zero_bits(number, bits): if number == 0: return bits for i in range(bits): if (number >> i) & 1: return i # All bits of interest were zero, even if there are more in the number return bits
Count the number of zero bits on the right hand side. Args: number: an integer. bits: maximum number of bits to count. Returns: The number of zero bits on the right hand side of the number.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/ext/ipaddress.py#L251-L268
null
''' Python 2.[67] port of Python 3.4's ipaddress module Almost verbatim copy of the core lib, with compatibility changes Source: https://bitbucket.org/kwi/py2-ipaddress/ ''' # pylint: skip-file # List of compatibility changes: # Python 3 uses only new-style classes. # s/class \(\w\+\):/class \1(object):/ # Use iterator versions of map and range: from itertools import imap as map range = xrange # Except that xrange only supports machine integers, not longs, so... def long_range(start, end): while start < end: yield start start += 1 # This backport uses bytearray instead of bytes, as bytes is the same # as str in Python 2.7. bytes = bytearray # Python 2 does not support exception chaining. # s/ from None$// # When checking for instances of int, also allow Python 2's long. _builtin_isinstance = isinstance def isinstance(val, types): if types is int: types = (int, long) elif type(types) is tuple and int in types: types += (long,) return _builtin_isinstance(val, types) # functools.lru_cache is Python 3.2+ only. # /@functools.lru_cache()/d # int().to_bytes is Python 3.2+ only. # s/\(\w+\)\.to_bytes(/_int_to_bytes(\1, / def _int_to_bytes(self, length, byteorder, signed=False): assert byteorder == 'big' and signed is False if self < 0 or self >= 256**length: raise OverflowError() return bytearray(('%0*x' % (length * 2, self)).decode('hex')) # int.from_bytes is Python 3.2+ only. # s/int\.from_bytes(/_int_from_bytes(/g def _int_from_bytes(what, byteorder, signed=False): assert byteorder == 'big' and signed is False return int(str(bytearray(what)).encode('hex'), 16) # Python 2.6 has no int.bit_length() if hasattr(int, 'bit_length'): _int_bit_length = lambda i: i.bit_length() else: _int_bit_length = lambda i: len(bin(abs(i))) - 2 # ---------------------------------------------------------------------------- # Copyright 2007 Google Inc. # Licensed to PSF under a Contributor Agreement. """A fast, lightweight IPv4/IPv6 manipulation library in Python. This library is used to create/poke/manipulate IPv4 and IPv6 addresses and networks. """ __version__ = '1.0' import functools IPV4LENGTH = 32 IPV6LENGTH = 128 class AddressValueError(ValueError): """A Value Error related to the address.""" class NetmaskValueError(ValueError): """A Value Error related to the netmask.""" def ip_address(address): """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Address or IPv6Address object. Raises: ValueError: if the *address* passed isn't either a v4 or a v6 address """ try: return IPv4Address(address) except (AddressValueError, NetmaskValueError): pass try: return IPv6Address(address) except (AddressValueError, NetmaskValueError): pass raise ValueError('%r does not appear to be an IPv4 or IPv6 address' % address) def ip_network(address, strict=True): """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP network. Either IPv4 or IPv6 networks may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Network or IPv6Network object. Raises: ValueError: if the string passed isn't either a v4 or a v6 address. Or if the network has host bits set. """ try: return IPv4Network(address, strict) except (AddressValueError, NetmaskValueError): pass try: return IPv6Network(address, strict) except (AddressValueError, NetmaskValueError): pass raise ValueError('%r does not appear to be an IPv4 or IPv6 network' % address) def ip_interface(address): """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Interface or IPv6Interface object. Raises: ValueError: if the string passed isn't either a v4 or a v6 address. Notes: The IPv?Interface classes describe an Address on a particular Network, so they're basically a combination of both the Address and Network classes. """ try: return IPv4Interface(address) except (AddressValueError, NetmaskValueError): pass try: return IPv6Interface(address) except (AddressValueError, NetmaskValueError): pass raise ValueError('%r does not appear to be an IPv4 or IPv6 interface' % address) def v4_int_to_packed(address): """Represent an address as 4 packed bytes in network (big-endian) order. Args: address: An integer representation of an IPv4 IP address. Returns: The integer address packed as 4 bytes in network (big-endian) order. Raises: ValueError: If the integer is negative or too large to be an IPv4 IP address. """ try: return _int_to_bytes(address, 4, 'big') except Exception: raise ValueError("Address negative or too large for IPv4") def v6_int_to_packed(address): """Represent an address as 16 packed bytes in network (big-endian) order. Args: address: An integer representation of an IPv6 IP address. Returns: The integer address packed as 16 bytes in network (big-endian) order. """ try: return _int_to_bytes(address, 16, 'big') except Exception: raise ValueError("Address negative or too large for IPv6") def _split_optional_netmask(address): """Helper to split the netmask and raise AddressValueError if needed""" addr = str(address).split('/') if len(addr) > 2: raise AddressValueError("Only one '/' permitted in %r" % address) return addr def _find_address_range(addresses): """Find a sequence of IPv#Address. Args: addresses: a list of IPv#Address objects. Returns: A tuple containing the first and last IP addresses in the sequence. """ first = last = addresses[0] for ip in addresses[1:]: if ip._ip == last._ip + 1: last = ip else: break return (first, last) def summarize_address_range(first, last): """Summarize a network range given the first and last IP addresses. Example: >>> list(summarize_address_range(IPv4Address('192.0.2.0'), ... IPv4Address('192.0.2.130'))) ... #doctest: +NORMALIZE_WHITESPACE [IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/31'), IPv4Network('192.0.2.130/32')] Args: first: the first IPv4Address or IPv6Address in the range. last: the last IPv4Address or IPv6Address in the range. Returns: An iterator of the summarized IPv(4|6) network objects. Raise: TypeError: If the first and last objects are not IP addresses. If the first and last objects are not the same version. ValueError: If the last object is not greater than the first. If the version of the first address is not 4 or 6. """ if (not (isinstance(first, _BaseAddress) and isinstance(last, _BaseAddress))): raise TypeError('first and last must be IP addresses, not networks') if first.version != last.version: raise TypeError("%s and %s are not of the same version" % ( first, last)) if first > last: raise ValueError('last IP address must be greater than first') if first.version == 4: ip = IPv4Network elif first.version == 6: ip = IPv6Network else: raise ValueError('unknown IP version') ip_bits = first._max_prefixlen first_int = first._ip last_int = last._ip while first_int <= last_int: nbits = min(_count_righthand_zero_bits(first_int, ip_bits), _int_bit_length(last_int - first_int + 1) - 1) net = ip('%s/%d' % (first, ip_bits - nbits)) yield net first_int += 1 << nbits if first_int - 1 == ip._ALL_ONES: break first = first.__class__(first_int) def _collapse_addresses_recursive(addresses): """Loops through the addresses, collapsing concurrent netblocks. Example: ip1 = IPv4Network('192.0.2.0/26') ip2 = IPv4Network('192.0.2.64/26') ip3 = IPv4Network('192.0.2.128/26') ip4 = IPv4Network('192.0.2.192/26') _collapse_addresses_recursive([ip1, ip2, ip3, ip4]) -> [IPv4Network('192.0.2.0/24')] This shouldn't be called directly; it is called via collapse_addresses([]). Args: addresses: A list of IPv4Network's or IPv6Network's Returns: A list of IPv4Network's or IPv6Network's depending on what we were passed. """ while True: last_addr = None ret_array = [] optimized = False for cur_addr in addresses: if not ret_array: last_addr = cur_addr ret_array.append(cur_addr) elif (cur_addr.network_address >= last_addr.network_address and cur_addr.broadcast_address <= last_addr.broadcast_address): optimized = True elif cur_addr == list(last_addr.supernet().subnets())[1]: ret_array[-1] = last_addr = last_addr.supernet() optimized = True else: last_addr = cur_addr ret_array.append(cur_addr) addresses = ret_array if not optimized: return addresses def collapse_addresses(addresses): """Collapse a list of IP objects. Example: collapse_addresses([IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/25')]) -> [IPv4Network('192.0.2.0/24')] Args: addresses: An iterator of IPv4Network or IPv6Network objects. Returns: An iterator of the collapsed IPv(4|6)Network objects. Raises: TypeError: If passed a list of mixed version objects. """ i = 0 addrs = [] ips = [] nets = [] # split IP addresses and networks for ip in addresses: if isinstance(ip, _BaseAddress): if ips and ips[-1]._version != ip._version: raise TypeError("%s and %s are not of the same version" % ( ip, ips[-1])) ips.append(ip) elif ip._prefixlen == ip._max_prefixlen: if ips and ips[-1]._version != ip._version: raise TypeError("%s and %s are not of the same version" % ( ip, ips[-1])) try: ips.append(ip.ip) except AttributeError: ips.append(ip.network_address) else: if nets and nets[-1]._version != ip._version: raise TypeError("%s and %s are not of the same version" % ( ip, nets[-1])) nets.append(ip) # sort and dedup ips = sorted(set(ips)) nets = sorted(set(nets)) while i < len(ips): (first, last) = _find_address_range(ips[i:]) i = ips.index(last) + 1 addrs.extend(summarize_address_range(first, last)) return iter(_collapse_addresses_recursive(sorted( addrs + nets, key=_BaseNetwork._get_networks_key))) def get_mixed_type_key(obj): """Return a key suitable for sorting between networks and addresses. Address and Network objects are not sortable by default; they're fundamentally different so the expression IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24') doesn't make any sense. There are some times however, where you may wish to have ipaddress sort these for you anyway. If you need to do this, you can use this function as the key= argument to sorted(). Args: obj: either a Network or Address object. Returns: appropriate key. """ if isinstance(obj, _BaseNetwork): return obj._get_networks_key() elif isinstance(obj, _BaseAddress): return obj._get_address_key() return NotImplemented class _TotalOrderingMixin(object): # Helper that derives the other comparison operations from # __lt__ and __eq__ # We avoid functools.total_ordering because it doesn't handle # NotImplemented correctly yet (http://bugs.python.org/issue10042) def __eq__(self, other): raise NotImplementedError def __ne__(self, other): equal = self.__eq__(other) if equal is NotImplemented: return NotImplemented return not equal def __lt__(self, other): raise NotImplementedError def __le__(self, other): less = self.__lt__(other) if less is NotImplemented or not less: return self.__eq__(other) return less def __gt__(self, other): less = self.__lt__(other) if less is NotImplemented: return NotImplemented equal = self.__eq__(other) if equal is NotImplemented: return NotImplemented return not (less or equal) def __ge__(self, other): less = self.__lt__(other) if less is NotImplemented: return NotImplemented return not less class _IPAddressBase(_TotalOrderingMixin): """The mother class.""" @property def exploded(self): """Return the longhand version of the IP address as a string.""" return self._explode_shorthand_ip_string() @property def compressed(self): """Return the shorthand version of the IP address as a string.""" return str(self) @property def reverse_pointer(self): """The name of the reverse DNS pointer for the IP address, e.g.: >>> ipaddress.ip_address("127.0.0.1").reverse_pointer '1.0.0.127.in-addr.arpa' >>> ipaddress.ip_address("2001:db8::1").reverse_pointer '1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa' """ return self._reverse_pointer() @property def version(self): msg = '%200s has no version specified' % (type(self),) raise NotImplementedError(msg) def _check_int_address(self, address): if address < 0: msg = "%d (< 0) is not permitted as an IPv%d address" raise AddressValueError(msg % (address, self._version)) if address > self._ALL_ONES: msg = "%d (>= 2**%d) is not permitted as an IPv%d address" raise AddressValueError(msg % (address, self._max_prefixlen, self._version)) def _check_packed_address(self, address, expected_len): address_len = len(address) if address_len != expected_len: msg = "%r (len %d != %d) is not permitted as an IPv%d address" raise AddressValueError(msg % (address, address_len, expected_len, self._version)) def _ip_int_from_prefix(self, prefixlen): """Turn the prefix length into a bitwise netmask Args: prefixlen: An integer, the prefix length. Returns: An integer. """ return self._ALL_ONES ^ (self._ALL_ONES >> prefixlen) def _prefix_from_ip_int(self, ip_int): """Return prefix length from the bitwise netmask. Args: ip_int: An integer, the netmask in expanded bitwise format Returns: An integer, the prefix length. Raises: ValueError: If the input intermingles zeroes & ones """ trailing_zeroes = _count_righthand_zero_bits(ip_int, self._max_prefixlen) prefixlen = self._max_prefixlen - trailing_zeroes leading_ones = ip_int >> trailing_zeroes all_ones = (1 << prefixlen) - 1 if leading_ones != all_ones: byteslen = self._max_prefixlen // 8 details = _int_to_bytes(ip_int, byteslen, 'big') msg = 'Netmask pattern %r mixes zeroes & ones' raise ValueError(msg % details) return prefixlen def _report_invalid_netmask(self, netmask_str): msg = '%r is not a valid netmask' % netmask_str raise NetmaskValueError(msg) def _prefix_from_prefix_string(self, prefixlen_str): """Return prefix length from a numeric string Args: prefixlen_str: The string to be converted Returns: An integer, the prefix length. Raises: NetmaskValueError: If the input is not a valid netmask """ # int allows a leading +/- as well as surrounding whitespace, # so we ensure that isn't the case if not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str): self._report_invalid_netmask(prefixlen_str) try: prefixlen = int(prefixlen_str) except ValueError: self._report_invalid_netmask(prefixlen_str) if not (0 <= prefixlen <= self._max_prefixlen): self._report_invalid_netmask(prefixlen_str) return prefixlen def _prefix_from_ip_string(self, ip_str): """Turn a netmask/hostmask string into a prefix length Args: ip_str: The netmask/hostmask to be converted Returns: An integer, the prefix length. Raises: NetmaskValueError: If the input is not a valid netmask/hostmask """ # Parse the netmask/hostmask like an IP address. try: ip_int = self._ip_int_from_string(ip_str) except AddressValueError: self._report_invalid_netmask(ip_str) # Try matching a netmask (this would be /1*0*/ as a bitwise regexp). # Note that the two ambiguous cases (all-ones and all-zeroes) are # treated as netmasks. try: return self._prefix_from_ip_int(ip_int) except ValueError: pass # Invert the bits, and try matching a /0+1+/ hostmask instead. ip_int ^= self._ALL_ONES try: return self._prefix_from_ip_int(ip_int) except ValueError: self._report_invalid_netmask(ip_str) class _BaseAddress(_IPAddressBase): """A generic IP object. This IP class contains the version independent methods which are used by single IP addresses. """ def __init__(self, address): if (not isinstance(address, bytes) and '/' in str(address)): raise AddressValueError("Unexpected '/' in %r" % address) def __int__(self): return self._ip def __eq__(self, other): try: return (self._ip == other._ip and self._version == other._version) except AttributeError: return NotImplemented def __lt__(self, other): if self._version != other._version: raise TypeError('%s and %s are not of the same version' % ( self, other)) if not isinstance(other, _BaseAddress): raise TypeError('%s and %s are not of the same type' % ( self, other)) if self._ip != other._ip: return self._ip < other._ip return False # Shorthand for Integer addition and subtraction. This is not # meant to ever support addition/subtraction of addresses. def __add__(self, other): if not isinstance(other, int): return NotImplemented return self.__class__(int(self) + other) def __sub__(self, other): if not isinstance(other, int): return NotImplemented return self.__class__(int(self) - other) def __repr__(self): return '%s(%r)' % (self.__class__.__name__, str(self)) def __str__(self): return str(self._string_from_ip_int(self._ip)) def __hash__(self): return hash(hex(int(self._ip))) def _get_address_key(self): return (self._version, self) class _BaseNetwork(_IPAddressBase): """A generic IP network object. This IP class contains the version independent methods which are used by networks. """ def __init__(self, address): self._cache = {} def __repr__(self): return '%s(%r)' % (self.__class__.__name__, str(self)) def __str__(self): return '%s/%d' % (self.network_address, self.prefixlen) def hosts(self): """Generate Iterator over usable hosts in a network. This is like __iter__ except it doesn't return the network or broadcast addresses. """ network = int(self.network_address) broadcast = int(self.broadcast_address) for x in long_range(network + 1, broadcast): yield self._address_class(x) def __iter__(self): network = int(self.network_address) broadcast = int(self.broadcast_address) for x in long_range(network, broadcast + 1): yield self._address_class(x) def __getitem__(self, n): network = int(self.network_address) broadcast = int(self.broadcast_address) if n >= 0: if network + n > broadcast: raise IndexError return self._address_class(network + n) else: n += 1 if broadcast + n < network: raise IndexError return self._address_class(broadcast + n) def __lt__(self, other): if self._version != other._version: raise TypeError('%s and %s are not of the same version' % ( self, other)) if not isinstance(other, _BaseNetwork): raise TypeError('%s and %s are not of the same type' % ( self, other)) if self.network_address != other.network_address: return self.network_address < other.network_address if self.netmask != other.netmask: return self.netmask < other.netmask return False def __eq__(self, other): try: return (self._version == other._version and self.network_address == other.network_address and int(self.netmask) == int(other.netmask)) except AttributeError: return NotImplemented def __hash__(self): return hash(int(self.network_address) ^ int(self.netmask)) def __contains__(self, other): # always false if one is v4 and the other is v6. if self._version != other._version: return False # dealing with another network. if isinstance(other, _BaseNetwork): return False # dealing with another address else: # address return (int(self.network_address) <= int(other._ip) <= int(self.broadcast_address)) def overlaps(self, other): """Tell if self is partly contained in other.""" return self.network_address in other or ( self.broadcast_address in other or ( other.network_address in self or ( other.broadcast_address in self))) @property def broadcast_address(self): x = self._cache.get('broadcast_address') if x is None: x = self._address_class(int(self.network_address) | int(self.hostmask)) self._cache['broadcast_address'] = x return x @property def hostmask(self): x = self._cache.get('hostmask') if x is None: x = self._address_class(int(self.netmask) ^ self._ALL_ONES) self._cache['hostmask'] = x return x @property def with_prefixlen(self): return '%s/%d' % (self.network_address, self._prefixlen) @property def with_netmask(self): return '%s/%s' % (self.network_address, self.netmask) @property def with_hostmask(self): return '%s/%s' % (self.network_address, self.hostmask) @property def num_addresses(self): """Number of hosts in the current subnet.""" return int(self.broadcast_address) - int(self.network_address) + 1 @property def _address_class(self): # Returning bare address objects (rather than interfaces) allows for # more consistent behaviour across the network address, broadcast # address and individual host addresses. msg = '%200s has no associated address class' % (type(self),) raise NotImplementedError(msg) @property def prefixlen(self): return self._prefixlen def address_exclude(self, other): """Remove an address from a larger block. For example: addr1 = ip_network('192.0.2.0/28') addr2 = ip_network('192.0.2.1/32') addr1.address_exclude(addr2) = [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'), IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')] or IPv6: addr1 = ip_network('2001:db8::1/32') addr2 = ip_network('2001:db8::1/128') addr1.address_exclude(addr2) = [ip_network('2001:db8::1/128'), ip_network('2001:db8::2/127'), ip_network('2001:db8::4/126'), ip_network('2001:db8::8/125'), ... ip_network('2001:db8:8000::/33')] Args: other: An IPv4Network or IPv6Network object of the same type. Returns: An iterator of the IPv(4|6)Network objects which is self minus other. Raises: TypeError: If self and other are of differing address versions, or if other is not a network object. ValueError: If other is not completely contained by self. """ if not self._version == other._version: raise TypeError("%s and %s are not of the same version" % ( self, other)) if not isinstance(other, _BaseNetwork): raise TypeError("%s is not a network object" % other) if not (other.network_address >= self.network_address and other.broadcast_address <= self.broadcast_address): raise ValueError('%s not contained in %s' % (other, self)) if other == self: raise StopIteration # Make sure we're comparing the network of other. other = other.__class__('%s/%s' % (other.network_address, other.prefixlen)) s1, s2 = self.subnets() while s1 != other and s2 != other: if (other.network_address >= s1.network_address and other.broadcast_address <= s1.broadcast_address): yield s2 s1, s2 = s1.subnets() elif (other.network_address >= s2.network_address and other.broadcast_address <= s2.broadcast_address): yield s1 s1, s2 = s2.subnets() else: # If we got here, there's a bug somewhere. raise AssertionError('Error performing exclusion: ' 's1: %s s2: %s other: %s' % (s1, s2, other)) if s1 == other: yield s2 elif s2 == other: yield s1 else: # If we got here, there's a bug somewhere. raise AssertionError('Error performing exclusion: ' 's1: %s s2: %s other: %s' % (s1, s2, other)) def compare_networks(self, other): """Compare two IP objects. This is only concerned about the comparison of the integer representation of the network addresses. This means that the host bits aren't considered at all in this method. If you want to compare host bits, you can easily enough do a 'HostA._ip < HostB._ip' Args: other: An IP object. Returns: If the IP versions of self and other are the same, returns: -1 if self < other: eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25') IPv6Network('2001:db8::1000/124') < IPv6Network('2001:db8::2000/124') 0 if self == other eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24') IPv6Network('2001:db8::1000/124') == IPv6Network('2001:db8::1000/124') 1 if self > other eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25') IPv6Network('2001:db8::2000/124') > IPv6Network('2001:db8::1000/124') Raises: TypeError if the IP versions are different. """ # does this need to raise a ValueError? if self._version != other._version: raise TypeError('%s and %s are not of the same type' % ( self, other)) # self._version == other._version below here: if self.network_address < other.network_address: return -1 if self.network_address > other.network_address: return 1 # self.network_address == other.network_address below here: if self.netmask < other.netmask: return -1 if self.netmask > other.netmask: return 1 return 0 def _get_networks_key(self): """Network-only key function. Returns an object that identifies this address' network and netmask. This function is a suitable "key" argument for sorted() and list.sort(). """ return (self._version, self.network_address, self.netmask) def subnets(self, prefixlen_diff=1, new_prefix=None): """The subnets which join to make the current subnet. In the case that self contains only one IP (self._prefixlen == 32 for IPv4 or self._prefixlen == 128 for IPv6), yield an iterator with just ourself. Args: prefixlen_diff: An integer, the amount the prefix length should be increased by. This should not be set if new_prefix is also set. new_prefix: The desired new prefix length. This must be a larger number (smaller prefix) than the existing prefix. This should not be set if prefixlen_diff is also set. Returns: An iterator of IPv(4|6) objects. Raises: ValueError: The prefixlen_diff is too small or too large. OR prefixlen_diff and new_prefix are both set or new_prefix is a smaller number than the current prefix (smaller number means a larger network) """ if self._prefixlen == self._max_prefixlen: yield self return if new_prefix is not None: if new_prefix < self._prefixlen: raise ValueError('new prefix must be longer') if prefixlen_diff != 1: raise ValueError('cannot set prefixlen_diff and new_prefix') prefixlen_diff = new_prefix - self._prefixlen if prefixlen_diff < 0: raise ValueError('prefix length diff must be > 0') new_prefixlen = self._prefixlen + prefixlen_diff if new_prefixlen > self._max_prefixlen: raise ValueError( 'prefix length diff %d is invalid for netblock %s' % ( new_prefixlen, self)) first = self.__class__('%s/%s' % (self.network_address, self._prefixlen + prefixlen_diff)) yield first current = first while True: broadcast = current.broadcast_address if broadcast == self.broadcast_address: return new_addr = self._address_class(int(broadcast) + 1) current = self.__class__('%s/%s' % (new_addr, new_prefixlen)) yield current def supernet(self, prefixlen_diff=1, new_prefix=None): """The supernet containing the current network. Args: prefixlen_diff: An integer, the amount the prefix length of the network should be decreased by. For example, given a /24 network and a prefixlen_diff of 3, a supernet with a /21 netmask is returned. Returns: An IPv4 network object. Raises: ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have a negative prefix length. OR If prefixlen_diff and new_prefix are both set or new_prefix is a larger number than the current prefix (larger number means a smaller network) """ if self._prefixlen == 0: return self if new_prefix is not None: if new_prefix > self._prefixlen: raise ValueError('new prefix must be shorter') if prefixlen_diff != 1: raise ValueError('cannot set prefixlen_diff and new_prefix') prefixlen_diff = self._prefixlen - new_prefix if self.prefixlen - prefixlen_diff < 0: raise ValueError( 'current prefixlen is %d, cannot have a prefixlen_diff of %d' % (self.prefixlen, prefixlen_diff)) # TODO (pmoody): optimize this. t = self.__class__('%s/%d' % (self.network_address, self.prefixlen - prefixlen_diff), strict=False) return t.__class__('%s/%d' % (t.network_address, t.prefixlen)) @property def is_multicast(self): """Test if the address is reserved for multicast use. Returns: A boolean, True if the address is a multicast address. See RFC 2373 2.7 for details. """ return (self.network_address.is_multicast and self.broadcast_address.is_multicast) @property def is_reserved(self): """Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within one of the reserved IPv6 Network ranges. """ return (self.network_address.is_reserved and self.broadcast_address.is_reserved) @property def is_link_local(self): """Test if the address is reserved for link-local. Returns: A boolean, True if the address is reserved per RFC 4291. """ return (self.network_address.is_link_local and self.broadcast_address.is_link_local) @property def is_private(self): """Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per iana-ipv4-special-registry or iana-ipv6-special-registry. """ return (self.network_address.is_private and self.broadcast_address.is_private) @property def is_global(self): """Test if this address is allocated for public networks. Returns: A boolean, True if the address is not reserved per iana-ipv4-special-registry or iana-ipv6-special-registry. """ return not self.is_private @property def is_unspecified(self): """Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in RFC 2373 2.5.2. """ return (self.network_address.is_unspecified and self.broadcast_address.is_unspecified) @property def is_loopback(self): """Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback address as defined in RFC 2373 2.5.3. """ return (self.network_address.is_loopback and self.broadcast_address.is_loopback) class _BaseV4(object): """Base IPv4 object. The following methods are used by IPv4 objects in both single IP addresses and networks. """ # Equivalent to 255.255.255.255 or 32 bits of 1's. _ALL_ONES = (2**IPV4LENGTH) - 1 _DECIMAL_DIGITS = frozenset('0123456789') # the valid octets for host and netmasks. only useful for IPv4. _valid_mask_octets = frozenset((255, 254, 252, 248, 240, 224, 192, 128, 0)) def __init__(self, address): self._version = 4 self._max_prefixlen = IPV4LENGTH def _explode_shorthand_ip_string(self): return str(self) def _ip_int_from_string(self, ip_str): """Turn the given IP string into an integer for comparison. Args: ip_str: A string, the IP ip_str. Returns: The IP ip_str as an integer. Raises: AddressValueError: if ip_str isn't a valid IPv4 Address. """ if not ip_str: raise AddressValueError('Address cannot be empty') octets = ip_str.split('.') if len(octets) != 4: raise AddressValueError("Expected 4 octets in %r" % ip_str) try: return _int_from_bytes(map(self._parse_octet, octets), 'big') except ValueError as exc: raise AddressValueError("%s in %r" % (exc, ip_str)) def _parse_octet(self, octet_str): """Convert a decimal octet into an integer. Args: octet_str: A string, the number to parse. Returns: The octet as an integer. Raises: ValueError: if the octet isn't strictly a decimal from [0..255]. """ if not octet_str: raise ValueError("Empty octet not permitted") # Whitelist the characters, since int() allows a lot of bizarre stuff. if not self._DECIMAL_DIGITS.issuperset(octet_str): msg = "Only decimal digits permitted in %r" raise ValueError(msg % octet_str) # We do the length check second, since the invalid character error # is likely to be more informative for the user if len(octet_str) > 3: msg = "At most 3 characters permitted in %r" raise ValueError(msg % octet_str) # Convert to integer (we know digits are legal) octet_int = int(octet_str, 10) # Any octets that look like they *might* be written in octal, # and which don't look exactly the same in both octal and # decimal are rejected as ambiguous if octet_int > 7 and octet_str[0] == '0': msg = "Ambiguous (octal/decimal) value in %r not permitted" raise ValueError(msg % octet_str) if octet_int > 255: raise ValueError("Octet %d (> 255) not permitted" % octet_int) return octet_int def _string_from_ip_int(self, ip_int): """Turns a 32-bit integer into dotted decimal notation. Args: ip_int: An integer, the IP address. Returns: The IP address as a string in dotted decimal notation. """ return '.'.join(map(str, _int_to_bytes(ip_int, 4, 'big'))) def _is_valid_netmask(self, netmask): """Verify that the netmask is valid. Args: netmask: A string, either a prefix or dotted decimal netmask. Returns: A boolean, True if the prefix represents a valid IPv4 netmask. """ mask = netmask.split('.') if len(mask) == 4: try: for x in mask: if int(x) not in self._valid_mask_octets: return False except ValueError: # Found something that isn't an integer or isn't valid return False for idx, y in enumerate(mask): if idx > 0 and y > mask[idx - 1]: return False return True try: netmask = int(netmask) except ValueError: return False return 0 <= netmask <= self._max_prefixlen def _is_hostmask(self, ip_str): """Test if the IP string is a hostmask (rather than a netmask). Args: ip_str: A string, the potential hostmask. Returns: A boolean, True if the IP string is a hostmask. """ bits = ip_str.split('.') try: parts = [x for x in map(int, bits) if x in self._valid_mask_octets] except ValueError: return False if len(parts) != len(bits): return False if parts[0] < parts[-1]: return True return False def _reverse_pointer(self): """Return the reverse DNS pointer name for the IPv4 address. This implements the method described in RFC1035 3.5. """ reverse_octets = str(self).split('.')[::-1] return '.'.join(reverse_octets) + '.in-addr.arpa' @property def max_prefixlen(self): return self._max_prefixlen @property def version(self): return self._version class IPv4Address(_BaseV4, _BaseAddress): """Represent and manipulate single IPv4 Addresses.""" def __init__(self, address): """ Args: address: A string or integer representing the IP Additionally, an integer can be passed, so IPv4Address('192.0.2.1') == IPv4Address(3221225985). or, more generally IPv4Address(int(IPv4Address('192.0.2.1'))) == IPv4Address('192.0.2.1') Raises: AddressValueError: If ipaddress isn't a valid IPv4 address. """ _BaseAddress.__init__(self, address) _BaseV4.__init__(self, address) # Efficient constructor from integer. if isinstance(address, int): self._check_int_address(address) self._ip = address return # Constructing from a packed address if isinstance(address, bytes): self._check_packed_address(address, 4) self._ip = _int_from_bytes(address, 'big') return # Assume input argument to be string or any object representation # which converts into a formatted IP string. addr_str = str(address) self._ip = self._ip_int_from_string(addr_str) @property def packed(self): """The binary representation of this address.""" return v4_int_to_packed(self._ip) @property def is_reserved(self): """Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within the reserved IPv4 Network range. """ reserved_network = IPv4Network('240.0.0.0/4') return self in reserved_network @property def is_private(self): """Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per iana-ipv4-special-registry. """ return (self in IPv4Network('0.0.0.0/8') or self in IPv4Network('10.0.0.0/8') or self in IPv4Network('127.0.0.0/8') or self in IPv4Network('169.254.0.0/16') or self in IPv4Network('172.16.0.0/12') or self in IPv4Network('192.0.0.0/29') or self in IPv4Network('192.0.0.170/31') or self in IPv4Network('192.0.2.0/24') or self in IPv4Network('192.168.0.0/16') or self in IPv4Network('198.18.0.0/15') or self in IPv4Network('198.51.100.0/24') or self in IPv4Network('203.0.113.0/24') or self in IPv4Network('240.0.0.0/4') or self in IPv4Network('255.255.255.255/32')) @property def is_multicast(self): """Test if the address is reserved for multicast use. Returns: A boolean, True if the address is multicast. See RFC 3171 for details. """ multicast_network = IPv4Network('224.0.0.0/4') return self in multicast_network @property def is_unspecified(self): """Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in RFC 5735 3. """ unspecified_address = IPv4Address('0.0.0.0') return self == unspecified_address @property def is_loopback(self): """Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback per RFC 3330. """ loopback_network = IPv4Network('127.0.0.0/8') return self in loopback_network @property def is_link_local(self): """Test if the address is reserved for link-local. Returns: A boolean, True if the address is link-local per RFC 3927. """ linklocal_network = IPv4Network('169.254.0.0/16') return self in linklocal_network class IPv4Interface(IPv4Address): def __init__(self, address): if isinstance(address, (bytes, int)): IPv4Address.__init__(self, address) self.network = IPv4Network(self._ip) self._prefixlen = self._max_prefixlen return addr = _split_optional_netmask(address) IPv4Address.__init__(self, addr[0]) self.network = IPv4Network(address, strict=False) self._prefixlen = self.network._prefixlen self.netmask = self.network.netmask self.hostmask = self.network.hostmask def __str__(self): return '%s/%d' % (self._string_from_ip_int(self._ip), self.network.prefixlen) def __eq__(self, other): address_equal = IPv4Address.__eq__(self, other) if not address_equal or address_equal is NotImplemented: return address_equal try: return self.network == other.network except AttributeError: # An interface with an associated network is NOT the # same as an unassociated address. That's why the hash # takes the extra info into account. return False def __lt__(self, other): address_less = IPv4Address.__lt__(self, other) if address_less is NotImplemented: return NotImplemented try: return self.network < other.network except AttributeError: # We *do* allow addresses and interfaces to be sorted. The # unassociated address is considered less than all interfaces. return False def __hash__(self): return self._ip ^ self._prefixlen ^ int(self.network.network_address) @property def ip(self): return IPv4Address(self._ip) @property def with_prefixlen(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self._prefixlen) @property def with_netmask(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self.netmask) @property def with_hostmask(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self.hostmask) class IPv4Network(_BaseV4, _BaseNetwork): """This class represents and manipulates 32-bit IPv4 network + addresses.. Attributes: [examples for IPv4Network('192.0.2.0/27')] .network_address: IPv4Address('192.0.2.0') .hostmask: IPv4Address('0.0.0.31') .broadcast_address: IPv4Address('192.0.2.32') .netmask: IPv4Address('255.255.255.224') .prefixlen: 27 """ # Class to use when creating address objects _address_class = IPv4Address def __init__(self, address, strict=True): """Instantiate a new IPv4 network object. Args: address: A string or integer representing the IP [& network]. '192.0.2.0/24' '192.0.2.0/255.255.255.0' '192.0.0.2/0.0.0.255' are all functionally the same in IPv4. Similarly, '192.0.2.1' '192.0.2.1/255.255.255.255' '192.0.2.1/32' are also functionally equivalent. That is to say, failing to provide a subnetmask will create an object with a mask of /32. If the mask (portion after the / in the argument) is given in dotted quad form, it is treated as a netmask if it starts with a non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it starts with a zero field (e.g. 0.255.255.255 == /8), with the single exception of an all-zero mask which is treated as a netmask == /0. If no mask is given, a default of /32 is used. Additionally, an integer can be passed, so IPv4Network('192.0.2.1') == IPv4Network(3221225985) or, more generally IPv4Interface(int(IPv4Interface('192.0.2.1'))) == IPv4Interface('192.0.2.1') Raises: AddressValueError: If ipaddress isn't a valid IPv4 address. NetmaskValueError: If the netmask isn't valid for an IPv4 address. ValueError: If strict is True and a network address is not supplied. """ _BaseV4.__init__(self, address) _BaseNetwork.__init__(self, address) # Constructing from a packed address if isinstance(address, bytes): self.network_address = IPv4Address(address) self._prefixlen = self._max_prefixlen self.netmask = IPv4Address(self._ALL_ONES) #fixme: address/network test here return # Efficient constructor from integer. if isinstance(address, int): self.network_address = IPv4Address(address) self._prefixlen = self._max_prefixlen self.netmask = IPv4Address(self._ALL_ONES) #fixme: address/network test here. return # Assume input argument to be string or any object representation # which converts into a formatted IP prefix string. addr = _split_optional_netmask(address) self.network_address = IPv4Address(self._ip_int_from_string(addr[0])) if len(addr) == 2: try: # Check for a netmask in prefix length form self._prefixlen = self._prefix_from_prefix_string(addr[1]) except NetmaskValueError: # Check for a netmask or hostmask in dotted-quad form. # This may raise NetmaskValueError. self._prefixlen = self._prefix_from_ip_string(addr[1]) else: self._prefixlen = self._max_prefixlen self.netmask = IPv4Address(self._ip_int_from_prefix(self._prefixlen)) if strict: if (IPv4Address(int(self.network_address) & int(self.netmask)) != self.network_address): raise ValueError('%s has host bits set' % self) self.network_address = IPv4Address(int(self.network_address) & int(self.netmask)) if self._prefixlen == (self._max_prefixlen - 1): self.hosts = self.__iter__ @property def is_global(self): """Test if this address is allocated for public networks. Returns: A boolean, True if the address is not reserved per iana-ipv4-special-registry. """ return (not (self.network_address in IPv4Network('100.64.0.0/10') and self.broadcast_address in IPv4Network('100.64.0.0/10')) and not self.is_private) class _BaseV6(object): """Base IPv6 object. The following methods are used by IPv6 objects in both single IP addresses and networks. """ _ALL_ONES = (2**IPV6LENGTH) - 1 _HEXTET_COUNT = 8 _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef') def __init__(self, address): self._version = 6 self._max_prefixlen = IPV6LENGTH def _ip_int_from_string(self, ip_str): """Turn an IPv6 ip_str into an integer. Args: ip_str: A string, the IPv6 ip_str. Returns: An int, the IPv6 address Raises: AddressValueError: if ip_str isn't a valid IPv6 Address. """ if not ip_str: raise AddressValueError('Address cannot be empty') parts = ip_str.split(':') # An IPv6 address needs at least 2 colons (3 parts). _min_parts = 3 if len(parts) < _min_parts: msg = "At least %d parts expected in %r" % (_min_parts, ip_str) raise AddressValueError(msg) # If the address has an IPv4-style suffix, convert it to hexadecimal. if '.' in parts[-1]: try: ipv4_int = IPv4Address(parts.pop())._ip except AddressValueError as exc: raise AddressValueError("%s in %r" % (exc, ip_str)) parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF)) parts.append('%x' % (ipv4_int & 0xFFFF)) # An IPv6 address can't have more than 8 colons (9 parts). # The extra colon comes from using the "::" notation for a single # leading or trailing zero part. _max_parts = self._HEXTET_COUNT + 1 if len(parts) > _max_parts: msg = "At most %d colons permitted in %r" % (_max_parts-1, ip_str) raise AddressValueError(msg) # Disregarding the endpoints, find '::' with nothing in between. # This indicates that a run of zeroes has been skipped. skip_index = None for i in range(1, len(parts) - 1): if not parts[i]: if skip_index is not None: # Can't have more than one '::' msg = "At most one '::' permitted in %r" % ip_str raise AddressValueError(msg) skip_index = i # parts_hi is the number of parts to copy from above/before the '::' # parts_lo is the number of parts to copy from below/after the '::' if skip_index is not None: # If we found a '::', then check if it also covers the endpoints. parts_hi = skip_index parts_lo = len(parts) - skip_index - 1 if not parts[0]: parts_hi -= 1 if parts_hi: msg = "Leading ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # ^: requires ^:: if not parts[-1]: parts_lo -= 1 if parts_lo: msg = "Trailing ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # :$ requires ::$ parts_skipped = self._HEXTET_COUNT - (parts_hi + parts_lo) if parts_skipped < 1: msg = "Expected at most %d other parts with '::' in %r" raise AddressValueError(msg % (self._HEXTET_COUNT-1, ip_str)) else: # Otherwise, allocate the entire address to parts_hi. The # endpoints could still be empty, but _parse_hextet() will check # for that. if len(parts) != self._HEXTET_COUNT: msg = "Exactly %d parts expected without '::' in %r" raise AddressValueError(msg % (self._HEXTET_COUNT, ip_str)) if not parts[0]: msg = "Leading ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # ^: requires ^:: if not parts[-1]: msg = "Trailing ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # :$ requires ::$ parts_hi = len(parts) parts_lo = 0 parts_skipped = 0 try: # Now, parse the hextets into a 128-bit integer. ip_int = 0 for i in range(parts_hi): ip_int <<= 16 ip_int |= self._parse_hextet(parts[i]) ip_int <<= 16 * parts_skipped for i in range(-parts_lo, 0): ip_int <<= 16 ip_int |= self._parse_hextet(parts[i]) return ip_int except ValueError as exc: raise AddressValueError("%s in %r" % (exc, ip_str)) def _parse_hextet(self, hextet_str): """Convert an IPv6 hextet string into an integer. Args: hextet_str: A string, the number to parse. Returns: The hextet as an integer. Raises: ValueError: if the input isn't strictly a hex number from [0..FFFF]. """ # Whitelist the characters, since int() allows a lot of bizarre stuff. if not self._HEX_DIGITS.issuperset(hextet_str): raise ValueError("Only hex digits permitted in %r" % hextet_str) # We do the length check second, since the invalid character error # is likely to be more informative for the user if len(hextet_str) > 4: msg = "At most 4 characters permitted in %r" raise ValueError(msg % hextet_str) # Length check means we can skip checking the integer value return int(hextet_str, 16) def _compress_hextets(self, hextets): """Compresses a list of hextets. Compresses a list of strings, replacing the longest continuous sequence of "0" in the list with "" and adding empty strings at the beginning or at the end of the string such that subsequently calling ":".join(hextets) will produce the compressed version of the IPv6 address. Args: hextets: A list of strings, the hextets to compress. Returns: A list of strings. """ best_doublecolon_start = -1 best_doublecolon_len = 0 doublecolon_start = -1 doublecolon_len = 0 for index, hextet in enumerate(hextets): if hextet == '0': doublecolon_len += 1 if doublecolon_start == -1: # Start of a sequence of zeros. doublecolon_start = index if doublecolon_len > best_doublecolon_len: # This is the longest sequence of zeros so far. best_doublecolon_len = doublecolon_len best_doublecolon_start = doublecolon_start else: doublecolon_len = 0 doublecolon_start = -1 if best_doublecolon_len > 1: best_doublecolon_end = (best_doublecolon_start + best_doublecolon_len) # For zeros at the end of the address. if best_doublecolon_end == len(hextets): hextets += [''] hextets[best_doublecolon_start:best_doublecolon_end] = [''] # For zeros at the beginning of the address. if best_doublecolon_start == 0: hextets = [''] + hextets return hextets def _string_from_ip_int(self, ip_int=None): """Turns a 128-bit integer into hexadecimal notation. Args: ip_int: An integer, the IP address. Returns: A string, the hexadecimal representation of the address. Raises: ValueError: The address is bigger than 128 bits of all ones. """ if ip_int is None: ip_int = int(self._ip) if ip_int > self._ALL_ONES: raise ValueError('IPv6 address is too large') hex_str = '%032x' % ip_int hextets = ['%x' % int(hex_str[x:x+4], 16) for x in range(0, 32, 4)] hextets = self._compress_hextets(hextets) return ':'.join(hextets) def _explode_shorthand_ip_string(self): """Expand a shortened IPv6 address. Args: ip_str: A string, the IPv6 address. Returns: A string, the expanded IPv6 address. """ if isinstance(self, IPv6Network): ip_str = str(self.network_address) elif isinstance(self, IPv6Interface): ip_str = str(self.ip) else: ip_str = str(self) ip_int = self._ip_int_from_string(ip_str) hex_str = '%032x' % ip_int parts = [hex_str[x:x+4] for x in range(0, 32, 4)] if isinstance(self, (_BaseNetwork, IPv6Interface)): return '%s/%d' % (':'.join(parts), self._prefixlen) return ':'.join(parts) def _reverse_pointer(self): """Return the reverse DNS pointer name for the IPv6 address. This implements the method described in RFC3596 2.5. """ reverse_chars = self.exploded[::-1].replace(':', '') return '.'.join(reverse_chars) + '.ip6.arpa' @property def max_prefixlen(self): return self._max_prefixlen @property def version(self): return self._version class IPv6Address(_BaseV6, _BaseAddress): """Represent and manipulate single IPv6 Addresses.""" def __init__(self, address): """Instantiate a new IPv6 address object. Args: address: A string or integer representing the IP Additionally, an integer can be passed, so IPv6Address('2001:db8::') == IPv6Address(42540766411282592856903984951653826560) or, more generally IPv6Address(int(IPv6Address('2001:db8::'))) == IPv6Address('2001:db8::') Raises: AddressValueError: If address isn't a valid IPv6 address. """ _BaseAddress.__init__(self, address) _BaseV6.__init__(self, address) # Efficient constructor from integer. if isinstance(address, int): self._check_int_address(address) self._ip = address return # Constructing from a packed address if isinstance(address, bytes): self._check_packed_address(address, 16) self._ip = _int_from_bytes(address, 'big') return # Assume input argument to be string or any object representation # which converts into a formatted IP string. addr_str = str(address) self._ip = self._ip_int_from_string(addr_str) @property def packed(self): """The binary representation of this address.""" return v6_int_to_packed(self._ip) @property def is_multicast(self): """Test if the address is reserved for multicast use. Returns: A boolean, True if the address is a multicast address. See RFC 2373 2.7 for details. """ multicast_network = IPv6Network('ff00::/8') return self in multicast_network @property def is_reserved(self): """Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within one of the reserved IPv6 Network ranges. """ reserved_networks = [IPv6Network('::/8'), IPv6Network('100::/8'), IPv6Network('200::/7'), IPv6Network('400::/6'), IPv6Network('800::/5'), IPv6Network('1000::/4'), IPv6Network('4000::/3'), IPv6Network('6000::/3'), IPv6Network('8000::/3'), IPv6Network('A000::/3'), IPv6Network('C000::/3'), IPv6Network('E000::/4'), IPv6Network('F000::/5'), IPv6Network('F800::/6'), IPv6Network('FE00::/9')] return any(self in x for x in reserved_networks) @property def is_link_local(self): """Test if the address is reserved for link-local. Returns: A boolean, True if the address is reserved per RFC 4291. """ linklocal_network = IPv6Network('fe80::/10') return self in linklocal_network @property def is_site_local(self): """Test if the address is reserved for site-local. Note that the site-local address space has been deprecated by RFC 3879. Use is_private to test if this address is in the space of unique local addresses as defined by RFC 4193. Returns: A boolean, True if the address is reserved per RFC 3513 2.5.6. """ sitelocal_network = IPv6Network('fec0::/10') return self in sitelocal_network @property def is_private(self): """Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per iana-ipv6-special-registry. """ return (self in IPv6Network('::1/128') or self in IPv6Network('::/128') or self in IPv6Network('::ffff:0:0/96') or self in IPv6Network('100::/64') or self in IPv6Network('2001::/23') or self in IPv6Network('2001:2::/48') or self in IPv6Network('2001:db8::/32') or self in IPv6Network('2001:10::/28') or self in IPv6Network('fc00::/7') or self in IPv6Network('fe80::/10')) @property def is_global(self): """Test if this address is allocated for public networks. Returns: A boolean, true if the address is not reserved per iana-ipv6-special-registry. """ return not self.is_private @property def is_unspecified(self): """Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in RFC 2373 2.5.2. """ return self._ip == 0 @property def is_loopback(self): """Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback address as defined in RFC 2373 2.5.3. """ return self._ip == 1 @property def ipv4_mapped(self): """Return the IPv4 mapped address. Returns: If the IPv6 address is a v4 mapped address, return the IPv4 mapped address. Return None otherwise. """ if (self._ip >> 32) != 0xFFFF: return None return IPv4Address(self._ip & 0xFFFFFFFF) @property def teredo(self): """Tuple of embedded teredo IPs. Returns: Tuple of the (server, client) IPs or None if the address doesn't appear to be a teredo address (doesn't start with 2001::/32) """ if (self._ip >> 96) != 0x20010000: return None return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF), IPv4Address(~self._ip & 0xFFFFFFFF)) @property def sixtofour(self): """Return the IPv4 6to4 embedded address. Returns: The IPv4 6to4-embedded address if present or None if the address doesn't appear to contain a 6to4 embedded address. """ if (self._ip >> 112) != 0x2002: return None return IPv4Address((self._ip >> 80) & 0xFFFFFFFF) class IPv6Interface(IPv6Address): def __init__(self, address): if isinstance(address, (bytes, int)): IPv6Address.__init__(self, address) self.network = IPv6Network(self._ip) self._prefixlen = self._max_prefixlen return addr = _split_optional_netmask(address) IPv6Address.__init__(self, addr[0]) self.network = IPv6Network(address, strict=False) self.netmask = self.network.netmask self._prefixlen = self.network._prefixlen self.hostmask = self.network.hostmask def __str__(self): return '%s/%d' % (self._string_from_ip_int(self._ip), self.network.prefixlen) def __eq__(self, other): address_equal = IPv6Address.__eq__(self, other) if not address_equal or address_equal is NotImplemented: return address_equal try: return self.network == other.network except AttributeError: # An interface with an associated network is NOT the # same as an unassociated address. That's why the hash # takes the extra info into account. return False def __lt__(self, other): address_less = IPv6Address.__lt__(self, other) if address_less is NotImplemented: return NotImplemented try: return self.network < other.network except AttributeError: # We *do* allow addresses and interfaces to be sorted. The # unassociated address is considered less than all interfaces. return False def __hash__(self): return self._ip ^ self._prefixlen ^ int(self.network.network_address) @property def ip(self): return IPv6Address(self._ip) @property def with_prefixlen(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self._prefixlen) @property def with_netmask(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self.netmask) @property def with_hostmask(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self.hostmask) @property def is_unspecified(self): return self._ip == 0 and self.network.is_unspecified @property def is_loopback(self): return self._ip == 1 and self.network.is_loopback class IPv6Network(_BaseV6, _BaseNetwork): """This class represents and manipulates 128-bit IPv6 networks. Attributes: [examples for IPv6('2001:db8::1000/124')] .network_address: IPv6Address('2001:db8::1000') .hostmask: IPv6Address('::f') .broadcast_address: IPv6Address('2001:db8::100f') .netmask: IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0') .prefixlen: 124 """ # Class to use when creating address objects _address_class = IPv6Address def __init__(self, address, strict=True): """Instantiate a new IPv6 Network object. Args: address: A string or integer representing the IPv6 network or the IP and prefix/netmask. '2001:db8::/128' '2001:db8:0000:0000:0000:0000:0000:0000/128' '2001:db8::' are all functionally the same in IPv6. That is to say, failing to provide a subnetmask will create an object with a mask of /128. Additionally, an integer can be passed, so IPv6Network('2001:db8::') == IPv6Network(42540766411282592856903984951653826560) or, more generally IPv6Network(int(IPv6Network('2001:db8::'))) == IPv6Network('2001:db8::') strict: A boolean. If true, ensure that we have been passed A true network address, eg, 2001:db8::1000/124 and not an IP address on a network, eg, 2001:db8::1/124. Raises: AddressValueError: If address isn't a valid IPv6 address. NetmaskValueError: If the netmask isn't valid for an IPv6 address. ValueError: If strict was True and a network address was not supplied. """ _BaseV6.__init__(self, address) _BaseNetwork.__init__(self, address) # Efficient constructor from integer. if isinstance(address, int): self.network_address = IPv6Address(address) self._prefixlen = self._max_prefixlen self.netmask = IPv6Address(self._ALL_ONES) return # Constructing from a packed address if isinstance(address, bytes): self.network_address = IPv6Address(address) self._prefixlen = self._max_prefixlen self.netmask = IPv6Address(self._ALL_ONES) return # Assume input argument to be string or any object representation # which converts into a formatted IP prefix string. addr = _split_optional_netmask(address) self.network_address = IPv6Address(self._ip_int_from_string(addr[0])) if len(addr) == 2: # This may raise NetmaskValueError self._prefixlen = self._prefix_from_prefix_string(addr[1]) else: self._prefixlen = self._max_prefixlen self.netmask = IPv6Address(self._ip_int_from_prefix(self._prefixlen)) if strict: if (IPv6Address(int(self.network_address) & int(self.netmask)) != self.network_address): raise ValueError('%s has host bits set' % self) self.network_address = IPv6Address(int(self.network_address) & int(self.netmask)) if self._prefixlen == (self._max_prefixlen - 1): self.hosts = self.__iter__ def hosts(self): """Generate Iterator over usable hosts in a network. This is like __iter__ except it doesn't return the Subnet-Router anycast address. """ network = int(self.network_address) broadcast = int(self.broadcast_address) for x in long_range(1, broadcast - network + 1): yield self._address_class(network + x) @property def is_site_local(self): """Test if the address is reserved for site-local. Note that the site-local address space has been deprecated by RFC 3879. Use is_private to test if this address is in the space of unique local addresses as defined by RFC 4193. Returns: A boolean, True if the address is reserved per RFC 3513 2.5.6. """ return (self.network_address.is_site_local and self.broadcast_address.is_site_local)
saltstack/salt
salt/ext/ipaddress.py
_collapse_addresses_recursive
python
def _collapse_addresses_recursive(addresses): while True: last_addr = None ret_array = [] optimized = False for cur_addr in addresses: if not ret_array: last_addr = cur_addr ret_array.append(cur_addr) elif (cur_addr.network_address >= last_addr.network_address and cur_addr.broadcast_address <= last_addr.broadcast_address): optimized = True elif cur_addr == list(last_addr.supernet().subnets())[1]: ret_array[-1] = last_addr = last_addr.supernet() optimized = True else: last_addr = cur_addr ret_array.append(cur_addr) addresses = ret_array if not optimized: return addresses
Loops through the addresses, collapsing concurrent netblocks. Example: ip1 = IPv4Network('192.0.2.0/26') ip2 = IPv4Network('192.0.2.64/26') ip3 = IPv4Network('192.0.2.128/26') ip4 = IPv4Network('192.0.2.192/26') _collapse_addresses_recursive([ip1, ip2, ip3, ip4]) -> [IPv4Network('192.0.2.0/24')] This shouldn't be called directly; it is called via collapse_addresses([]). Args: addresses: A list of IPv4Network's or IPv6Network's Returns: A list of IPv4Network's or IPv6Network's depending on what we were passed.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/ext/ipaddress.py#L327-L372
null
''' Python 2.[67] port of Python 3.4's ipaddress module Almost verbatim copy of the core lib, with compatibility changes Source: https://bitbucket.org/kwi/py2-ipaddress/ ''' # pylint: skip-file # List of compatibility changes: # Python 3 uses only new-style classes. # s/class \(\w\+\):/class \1(object):/ # Use iterator versions of map and range: from itertools import imap as map range = xrange # Except that xrange only supports machine integers, not longs, so... def long_range(start, end): while start < end: yield start start += 1 # This backport uses bytearray instead of bytes, as bytes is the same # as str in Python 2.7. bytes = bytearray # Python 2 does not support exception chaining. # s/ from None$// # When checking for instances of int, also allow Python 2's long. _builtin_isinstance = isinstance def isinstance(val, types): if types is int: types = (int, long) elif type(types) is tuple and int in types: types += (long,) return _builtin_isinstance(val, types) # functools.lru_cache is Python 3.2+ only. # /@functools.lru_cache()/d # int().to_bytes is Python 3.2+ only. # s/\(\w+\)\.to_bytes(/_int_to_bytes(\1, / def _int_to_bytes(self, length, byteorder, signed=False): assert byteorder == 'big' and signed is False if self < 0 or self >= 256**length: raise OverflowError() return bytearray(('%0*x' % (length * 2, self)).decode('hex')) # int.from_bytes is Python 3.2+ only. # s/int\.from_bytes(/_int_from_bytes(/g def _int_from_bytes(what, byteorder, signed=False): assert byteorder == 'big' and signed is False return int(str(bytearray(what)).encode('hex'), 16) # Python 2.6 has no int.bit_length() if hasattr(int, 'bit_length'): _int_bit_length = lambda i: i.bit_length() else: _int_bit_length = lambda i: len(bin(abs(i))) - 2 # ---------------------------------------------------------------------------- # Copyright 2007 Google Inc. # Licensed to PSF under a Contributor Agreement. """A fast, lightweight IPv4/IPv6 manipulation library in Python. This library is used to create/poke/manipulate IPv4 and IPv6 addresses and networks. """ __version__ = '1.0' import functools IPV4LENGTH = 32 IPV6LENGTH = 128 class AddressValueError(ValueError): """A Value Error related to the address.""" class NetmaskValueError(ValueError): """A Value Error related to the netmask.""" def ip_address(address): """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Address or IPv6Address object. Raises: ValueError: if the *address* passed isn't either a v4 or a v6 address """ try: return IPv4Address(address) except (AddressValueError, NetmaskValueError): pass try: return IPv6Address(address) except (AddressValueError, NetmaskValueError): pass raise ValueError('%r does not appear to be an IPv4 or IPv6 address' % address) def ip_network(address, strict=True): """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP network. Either IPv4 or IPv6 networks may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Network or IPv6Network object. Raises: ValueError: if the string passed isn't either a v4 or a v6 address. Or if the network has host bits set. """ try: return IPv4Network(address, strict) except (AddressValueError, NetmaskValueError): pass try: return IPv6Network(address, strict) except (AddressValueError, NetmaskValueError): pass raise ValueError('%r does not appear to be an IPv4 or IPv6 network' % address) def ip_interface(address): """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Interface or IPv6Interface object. Raises: ValueError: if the string passed isn't either a v4 or a v6 address. Notes: The IPv?Interface classes describe an Address on a particular Network, so they're basically a combination of both the Address and Network classes. """ try: return IPv4Interface(address) except (AddressValueError, NetmaskValueError): pass try: return IPv6Interface(address) except (AddressValueError, NetmaskValueError): pass raise ValueError('%r does not appear to be an IPv4 or IPv6 interface' % address) def v4_int_to_packed(address): """Represent an address as 4 packed bytes in network (big-endian) order. Args: address: An integer representation of an IPv4 IP address. Returns: The integer address packed as 4 bytes in network (big-endian) order. Raises: ValueError: If the integer is negative or too large to be an IPv4 IP address. """ try: return _int_to_bytes(address, 4, 'big') except Exception: raise ValueError("Address negative or too large for IPv4") def v6_int_to_packed(address): """Represent an address as 16 packed bytes in network (big-endian) order. Args: address: An integer representation of an IPv6 IP address. Returns: The integer address packed as 16 bytes in network (big-endian) order. """ try: return _int_to_bytes(address, 16, 'big') except Exception: raise ValueError("Address negative or too large for IPv6") def _split_optional_netmask(address): """Helper to split the netmask and raise AddressValueError if needed""" addr = str(address).split('/') if len(addr) > 2: raise AddressValueError("Only one '/' permitted in %r" % address) return addr def _find_address_range(addresses): """Find a sequence of IPv#Address. Args: addresses: a list of IPv#Address objects. Returns: A tuple containing the first and last IP addresses in the sequence. """ first = last = addresses[0] for ip in addresses[1:]: if ip._ip == last._ip + 1: last = ip else: break return (first, last) def _count_righthand_zero_bits(number, bits): """Count the number of zero bits on the right hand side. Args: number: an integer. bits: maximum number of bits to count. Returns: The number of zero bits on the right hand side of the number. """ if number == 0: return bits for i in range(bits): if (number >> i) & 1: return i # All bits of interest were zero, even if there are more in the number return bits def summarize_address_range(first, last): """Summarize a network range given the first and last IP addresses. Example: >>> list(summarize_address_range(IPv4Address('192.0.2.0'), ... IPv4Address('192.0.2.130'))) ... #doctest: +NORMALIZE_WHITESPACE [IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/31'), IPv4Network('192.0.2.130/32')] Args: first: the first IPv4Address or IPv6Address in the range. last: the last IPv4Address or IPv6Address in the range. Returns: An iterator of the summarized IPv(4|6) network objects. Raise: TypeError: If the first and last objects are not IP addresses. If the first and last objects are not the same version. ValueError: If the last object is not greater than the first. If the version of the first address is not 4 or 6. """ if (not (isinstance(first, _BaseAddress) and isinstance(last, _BaseAddress))): raise TypeError('first and last must be IP addresses, not networks') if first.version != last.version: raise TypeError("%s and %s are not of the same version" % ( first, last)) if first > last: raise ValueError('last IP address must be greater than first') if first.version == 4: ip = IPv4Network elif first.version == 6: ip = IPv6Network else: raise ValueError('unknown IP version') ip_bits = first._max_prefixlen first_int = first._ip last_int = last._ip while first_int <= last_int: nbits = min(_count_righthand_zero_bits(first_int, ip_bits), _int_bit_length(last_int - first_int + 1) - 1) net = ip('%s/%d' % (first, ip_bits - nbits)) yield net first_int += 1 << nbits if first_int - 1 == ip._ALL_ONES: break first = first.__class__(first_int) def collapse_addresses(addresses): """Collapse a list of IP objects. Example: collapse_addresses([IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/25')]) -> [IPv4Network('192.0.2.0/24')] Args: addresses: An iterator of IPv4Network or IPv6Network objects. Returns: An iterator of the collapsed IPv(4|6)Network objects. Raises: TypeError: If passed a list of mixed version objects. """ i = 0 addrs = [] ips = [] nets = [] # split IP addresses and networks for ip in addresses: if isinstance(ip, _BaseAddress): if ips and ips[-1]._version != ip._version: raise TypeError("%s and %s are not of the same version" % ( ip, ips[-1])) ips.append(ip) elif ip._prefixlen == ip._max_prefixlen: if ips and ips[-1]._version != ip._version: raise TypeError("%s and %s are not of the same version" % ( ip, ips[-1])) try: ips.append(ip.ip) except AttributeError: ips.append(ip.network_address) else: if nets and nets[-1]._version != ip._version: raise TypeError("%s and %s are not of the same version" % ( ip, nets[-1])) nets.append(ip) # sort and dedup ips = sorted(set(ips)) nets = sorted(set(nets)) while i < len(ips): (first, last) = _find_address_range(ips[i:]) i = ips.index(last) + 1 addrs.extend(summarize_address_range(first, last)) return iter(_collapse_addresses_recursive(sorted( addrs + nets, key=_BaseNetwork._get_networks_key))) def get_mixed_type_key(obj): """Return a key suitable for sorting between networks and addresses. Address and Network objects are not sortable by default; they're fundamentally different so the expression IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24') doesn't make any sense. There are some times however, where you may wish to have ipaddress sort these for you anyway. If you need to do this, you can use this function as the key= argument to sorted(). Args: obj: either a Network or Address object. Returns: appropriate key. """ if isinstance(obj, _BaseNetwork): return obj._get_networks_key() elif isinstance(obj, _BaseAddress): return obj._get_address_key() return NotImplemented class _TotalOrderingMixin(object): # Helper that derives the other comparison operations from # __lt__ and __eq__ # We avoid functools.total_ordering because it doesn't handle # NotImplemented correctly yet (http://bugs.python.org/issue10042) def __eq__(self, other): raise NotImplementedError def __ne__(self, other): equal = self.__eq__(other) if equal is NotImplemented: return NotImplemented return not equal def __lt__(self, other): raise NotImplementedError def __le__(self, other): less = self.__lt__(other) if less is NotImplemented or not less: return self.__eq__(other) return less def __gt__(self, other): less = self.__lt__(other) if less is NotImplemented: return NotImplemented equal = self.__eq__(other) if equal is NotImplemented: return NotImplemented return not (less or equal) def __ge__(self, other): less = self.__lt__(other) if less is NotImplemented: return NotImplemented return not less class _IPAddressBase(_TotalOrderingMixin): """The mother class.""" @property def exploded(self): """Return the longhand version of the IP address as a string.""" return self._explode_shorthand_ip_string() @property def compressed(self): """Return the shorthand version of the IP address as a string.""" return str(self) @property def reverse_pointer(self): """The name of the reverse DNS pointer for the IP address, e.g.: >>> ipaddress.ip_address("127.0.0.1").reverse_pointer '1.0.0.127.in-addr.arpa' >>> ipaddress.ip_address("2001:db8::1").reverse_pointer '1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa' """ return self._reverse_pointer() @property def version(self): msg = '%200s has no version specified' % (type(self),) raise NotImplementedError(msg) def _check_int_address(self, address): if address < 0: msg = "%d (< 0) is not permitted as an IPv%d address" raise AddressValueError(msg % (address, self._version)) if address > self._ALL_ONES: msg = "%d (>= 2**%d) is not permitted as an IPv%d address" raise AddressValueError(msg % (address, self._max_prefixlen, self._version)) def _check_packed_address(self, address, expected_len): address_len = len(address) if address_len != expected_len: msg = "%r (len %d != %d) is not permitted as an IPv%d address" raise AddressValueError(msg % (address, address_len, expected_len, self._version)) def _ip_int_from_prefix(self, prefixlen): """Turn the prefix length into a bitwise netmask Args: prefixlen: An integer, the prefix length. Returns: An integer. """ return self._ALL_ONES ^ (self._ALL_ONES >> prefixlen) def _prefix_from_ip_int(self, ip_int): """Return prefix length from the bitwise netmask. Args: ip_int: An integer, the netmask in expanded bitwise format Returns: An integer, the prefix length. Raises: ValueError: If the input intermingles zeroes & ones """ trailing_zeroes = _count_righthand_zero_bits(ip_int, self._max_prefixlen) prefixlen = self._max_prefixlen - trailing_zeroes leading_ones = ip_int >> trailing_zeroes all_ones = (1 << prefixlen) - 1 if leading_ones != all_ones: byteslen = self._max_prefixlen // 8 details = _int_to_bytes(ip_int, byteslen, 'big') msg = 'Netmask pattern %r mixes zeroes & ones' raise ValueError(msg % details) return prefixlen def _report_invalid_netmask(self, netmask_str): msg = '%r is not a valid netmask' % netmask_str raise NetmaskValueError(msg) def _prefix_from_prefix_string(self, prefixlen_str): """Return prefix length from a numeric string Args: prefixlen_str: The string to be converted Returns: An integer, the prefix length. Raises: NetmaskValueError: If the input is not a valid netmask """ # int allows a leading +/- as well as surrounding whitespace, # so we ensure that isn't the case if not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str): self._report_invalid_netmask(prefixlen_str) try: prefixlen = int(prefixlen_str) except ValueError: self._report_invalid_netmask(prefixlen_str) if not (0 <= prefixlen <= self._max_prefixlen): self._report_invalid_netmask(prefixlen_str) return prefixlen def _prefix_from_ip_string(self, ip_str): """Turn a netmask/hostmask string into a prefix length Args: ip_str: The netmask/hostmask to be converted Returns: An integer, the prefix length. Raises: NetmaskValueError: If the input is not a valid netmask/hostmask """ # Parse the netmask/hostmask like an IP address. try: ip_int = self._ip_int_from_string(ip_str) except AddressValueError: self._report_invalid_netmask(ip_str) # Try matching a netmask (this would be /1*0*/ as a bitwise regexp). # Note that the two ambiguous cases (all-ones and all-zeroes) are # treated as netmasks. try: return self._prefix_from_ip_int(ip_int) except ValueError: pass # Invert the bits, and try matching a /0+1+/ hostmask instead. ip_int ^= self._ALL_ONES try: return self._prefix_from_ip_int(ip_int) except ValueError: self._report_invalid_netmask(ip_str) class _BaseAddress(_IPAddressBase): """A generic IP object. This IP class contains the version independent methods which are used by single IP addresses. """ def __init__(self, address): if (not isinstance(address, bytes) and '/' in str(address)): raise AddressValueError("Unexpected '/' in %r" % address) def __int__(self): return self._ip def __eq__(self, other): try: return (self._ip == other._ip and self._version == other._version) except AttributeError: return NotImplemented def __lt__(self, other): if self._version != other._version: raise TypeError('%s and %s are not of the same version' % ( self, other)) if not isinstance(other, _BaseAddress): raise TypeError('%s and %s are not of the same type' % ( self, other)) if self._ip != other._ip: return self._ip < other._ip return False # Shorthand for Integer addition and subtraction. This is not # meant to ever support addition/subtraction of addresses. def __add__(self, other): if not isinstance(other, int): return NotImplemented return self.__class__(int(self) + other) def __sub__(self, other): if not isinstance(other, int): return NotImplemented return self.__class__(int(self) - other) def __repr__(self): return '%s(%r)' % (self.__class__.__name__, str(self)) def __str__(self): return str(self._string_from_ip_int(self._ip)) def __hash__(self): return hash(hex(int(self._ip))) def _get_address_key(self): return (self._version, self) class _BaseNetwork(_IPAddressBase): """A generic IP network object. This IP class contains the version independent methods which are used by networks. """ def __init__(self, address): self._cache = {} def __repr__(self): return '%s(%r)' % (self.__class__.__name__, str(self)) def __str__(self): return '%s/%d' % (self.network_address, self.prefixlen) def hosts(self): """Generate Iterator over usable hosts in a network. This is like __iter__ except it doesn't return the network or broadcast addresses. """ network = int(self.network_address) broadcast = int(self.broadcast_address) for x in long_range(network + 1, broadcast): yield self._address_class(x) def __iter__(self): network = int(self.network_address) broadcast = int(self.broadcast_address) for x in long_range(network, broadcast + 1): yield self._address_class(x) def __getitem__(self, n): network = int(self.network_address) broadcast = int(self.broadcast_address) if n >= 0: if network + n > broadcast: raise IndexError return self._address_class(network + n) else: n += 1 if broadcast + n < network: raise IndexError return self._address_class(broadcast + n) def __lt__(self, other): if self._version != other._version: raise TypeError('%s and %s are not of the same version' % ( self, other)) if not isinstance(other, _BaseNetwork): raise TypeError('%s and %s are not of the same type' % ( self, other)) if self.network_address != other.network_address: return self.network_address < other.network_address if self.netmask != other.netmask: return self.netmask < other.netmask return False def __eq__(self, other): try: return (self._version == other._version and self.network_address == other.network_address and int(self.netmask) == int(other.netmask)) except AttributeError: return NotImplemented def __hash__(self): return hash(int(self.network_address) ^ int(self.netmask)) def __contains__(self, other): # always false if one is v4 and the other is v6. if self._version != other._version: return False # dealing with another network. if isinstance(other, _BaseNetwork): return False # dealing with another address else: # address return (int(self.network_address) <= int(other._ip) <= int(self.broadcast_address)) def overlaps(self, other): """Tell if self is partly contained in other.""" return self.network_address in other or ( self.broadcast_address in other or ( other.network_address in self or ( other.broadcast_address in self))) @property def broadcast_address(self): x = self._cache.get('broadcast_address') if x is None: x = self._address_class(int(self.network_address) | int(self.hostmask)) self._cache['broadcast_address'] = x return x @property def hostmask(self): x = self._cache.get('hostmask') if x is None: x = self._address_class(int(self.netmask) ^ self._ALL_ONES) self._cache['hostmask'] = x return x @property def with_prefixlen(self): return '%s/%d' % (self.network_address, self._prefixlen) @property def with_netmask(self): return '%s/%s' % (self.network_address, self.netmask) @property def with_hostmask(self): return '%s/%s' % (self.network_address, self.hostmask) @property def num_addresses(self): """Number of hosts in the current subnet.""" return int(self.broadcast_address) - int(self.network_address) + 1 @property def _address_class(self): # Returning bare address objects (rather than interfaces) allows for # more consistent behaviour across the network address, broadcast # address and individual host addresses. msg = '%200s has no associated address class' % (type(self),) raise NotImplementedError(msg) @property def prefixlen(self): return self._prefixlen def address_exclude(self, other): """Remove an address from a larger block. For example: addr1 = ip_network('192.0.2.0/28') addr2 = ip_network('192.0.2.1/32') addr1.address_exclude(addr2) = [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'), IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')] or IPv6: addr1 = ip_network('2001:db8::1/32') addr2 = ip_network('2001:db8::1/128') addr1.address_exclude(addr2) = [ip_network('2001:db8::1/128'), ip_network('2001:db8::2/127'), ip_network('2001:db8::4/126'), ip_network('2001:db8::8/125'), ... ip_network('2001:db8:8000::/33')] Args: other: An IPv4Network or IPv6Network object of the same type. Returns: An iterator of the IPv(4|6)Network objects which is self minus other. Raises: TypeError: If self and other are of differing address versions, or if other is not a network object. ValueError: If other is not completely contained by self. """ if not self._version == other._version: raise TypeError("%s and %s are not of the same version" % ( self, other)) if not isinstance(other, _BaseNetwork): raise TypeError("%s is not a network object" % other) if not (other.network_address >= self.network_address and other.broadcast_address <= self.broadcast_address): raise ValueError('%s not contained in %s' % (other, self)) if other == self: raise StopIteration # Make sure we're comparing the network of other. other = other.__class__('%s/%s' % (other.network_address, other.prefixlen)) s1, s2 = self.subnets() while s1 != other and s2 != other: if (other.network_address >= s1.network_address and other.broadcast_address <= s1.broadcast_address): yield s2 s1, s2 = s1.subnets() elif (other.network_address >= s2.network_address and other.broadcast_address <= s2.broadcast_address): yield s1 s1, s2 = s2.subnets() else: # If we got here, there's a bug somewhere. raise AssertionError('Error performing exclusion: ' 's1: %s s2: %s other: %s' % (s1, s2, other)) if s1 == other: yield s2 elif s2 == other: yield s1 else: # If we got here, there's a bug somewhere. raise AssertionError('Error performing exclusion: ' 's1: %s s2: %s other: %s' % (s1, s2, other)) def compare_networks(self, other): """Compare two IP objects. This is only concerned about the comparison of the integer representation of the network addresses. This means that the host bits aren't considered at all in this method. If you want to compare host bits, you can easily enough do a 'HostA._ip < HostB._ip' Args: other: An IP object. Returns: If the IP versions of self and other are the same, returns: -1 if self < other: eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25') IPv6Network('2001:db8::1000/124') < IPv6Network('2001:db8::2000/124') 0 if self == other eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24') IPv6Network('2001:db8::1000/124') == IPv6Network('2001:db8::1000/124') 1 if self > other eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25') IPv6Network('2001:db8::2000/124') > IPv6Network('2001:db8::1000/124') Raises: TypeError if the IP versions are different. """ # does this need to raise a ValueError? if self._version != other._version: raise TypeError('%s and %s are not of the same type' % ( self, other)) # self._version == other._version below here: if self.network_address < other.network_address: return -1 if self.network_address > other.network_address: return 1 # self.network_address == other.network_address below here: if self.netmask < other.netmask: return -1 if self.netmask > other.netmask: return 1 return 0 def _get_networks_key(self): """Network-only key function. Returns an object that identifies this address' network and netmask. This function is a suitable "key" argument for sorted() and list.sort(). """ return (self._version, self.network_address, self.netmask) def subnets(self, prefixlen_diff=1, new_prefix=None): """The subnets which join to make the current subnet. In the case that self contains only one IP (self._prefixlen == 32 for IPv4 or self._prefixlen == 128 for IPv6), yield an iterator with just ourself. Args: prefixlen_diff: An integer, the amount the prefix length should be increased by. This should not be set if new_prefix is also set. new_prefix: The desired new prefix length. This must be a larger number (smaller prefix) than the existing prefix. This should not be set if prefixlen_diff is also set. Returns: An iterator of IPv(4|6) objects. Raises: ValueError: The prefixlen_diff is too small or too large. OR prefixlen_diff and new_prefix are both set or new_prefix is a smaller number than the current prefix (smaller number means a larger network) """ if self._prefixlen == self._max_prefixlen: yield self return if new_prefix is not None: if new_prefix < self._prefixlen: raise ValueError('new prefix must be longer') if prefixlen_diff != 1: raise ValueError('cannot set prefixlen_diff and new_prefix') prefixlen_diff = new_prefix - self._prefixlen if prefixlen_diff < 0: raise ValueError('prefix length diff must be > 0') new_prefixlen = self._prefixlen + prefixlen_diff if new_prefixlen > self._max_prefixlen: raise ValueError( 'prefix length diff %d is invalid for netblock %s' % ( new_prefixlen, self)) first = self.__class__('%s/%s' % (self.network_address, self._prefixlen + prefixlen_diff)) yield first current = first while True: broadcast = current.broadcast_address if broadcast == self.broadcast_address: return new_addr = self._address_class(int(broadcast) + 1) current = self.__class__('%s/%s' % (new_addr, new_prefixlen)) yield current def supernet(self, prefixlen_diff=1, new_prefix=None): """The supernet containing the current network. Args: prefixlen_diff: An integer, the amount the prefix length of the network should be decreased by. For example, given a /24 network and a prefixlen_diff of 3, a supernet with a /21 netmask is returned. Returns: An IPv4 network object. Raises: ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have a negative prefix length. OR If prefixlen_diff and new_prefix are both set or new_prefix is a larger number than the current prefix (larger number means a smaller network) """ if self._prefixlen == 0: return self if new_prefix is not None: if new_prefix > self._prefixlen: raise ValueError('new prefix must be shorter') if prefixlen_diff != 1: raise ValueError('cannot set prefixlen_diff and new_prefix') prefixlen_diff = self._prefixlen - new_prefix if self.prefixlen - prefixlen_diff < 0: raise ValueError( 'current prefixlen is %d, cannot have a prefixlen_diff of %d' % (self.prefixlen, prefixlen_diff)) # TODO (pmoody): optimize this. t = self.__class__('%s/%d' % (self.network_address, self.prefixlen - prefixlen_diff), strict=False) return t.__class__('%s/%d' % (t.network_address, t.prefixlen)) @property def is_multicast(self): """Test if the address is reserved for multicast use. Returns: A boolean, True if the address is a multicast address. See RFC 2373 2.7 for details. """ return (self.network_address.is_multicast and self.broadcast_address.is_multicast) @property def is_reserved(self): """Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within one of the reserved IPv6 Network ranges. """ return (self.network_address.is_reserved and self.broadcast_address.is_reserved) @property def is_link_local(self): """Test if the address is reserved for link-local. Returns: A boolean, True if the address is reserved per RFC 4291. """ return (self.network_address.is_link_local and self.broadcast_address.is_link_local) @property def is_private(self): """Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per iana-ipv4-special-registry or iana-ipv6-special-registry. """ return (self.network_address.is_private and self.broadcast_address.is_private) @property def is_global(self): """Test if this address is allocated for public networks. Returns: A boolean, True if the address is not reserved per iana-ipv4-special-registry or iana-ipv6-special-registry. """ return not self.is_private @property def is_unspecified(self): """Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in RFC 2373 2.5.2. """ return (self.network_address.is_unspecified and self.broadcast_address.is_unspecified) @property def is_loopback(self): """Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback address as defined in RFC 2373 2.5.3. """ return (self.network_address.is_loopback and self.broadcast_address.is_loopback) class _BaseV4(object): """Base IPv4 object. The following methods are used by IPv4 objects in both single IP addresses and networks. """ # Equivalent to 255.255.255.255 or 32 bits of 1's. _ALL_ONES = (2**IPV4LENGTH) - 1 _DECIMAL_DIGITS = frozenset('0123456789') # the valid octets for host and netmasks. only useful for IPv4. _valid_mask_octets = frozenset((255, 254, 252, 248, 240, 224, 192, 128, 0)) def __init__(self, address): self._version = 4 self._max_prefixlen = IPV4LENGTH def _explode_shorthand_ip_string(self): return str(self) def _ip_int_from_string(self, ip_str): """Turn the given IP string into an integer for comparison. Args: ip_str: A string, the IP ip_str. Returns: The IP ip_str as an integer. Raises: AddressValueError: if ip_str isn't a valid IPv4 Address. """ if not ip_str: raise AddressValueError('Address cannot be empty') octets = ip_str.split('.') if len(octets) != 4: raise AddressValueError("Expected 4 octets in %r" % ip_str) try: return _int_from_bytes(map(self._parse_octet, octets), 'big') except ValueError as exc: raise AddressValueError("%s in %r" % (exc, ip_str)) def _parse_octet(self, octet_str): """Convert a decimal octet into an integer. Args: octet_str: A string, the number to parse. Returns: The octet as an integer. Raises: ValueError: if the octet isn't strictly a decimal from [0..255]. """ if not octet_str: raise ValueError("Empty octet not permitted") # Whitelist the characters, since int() allows a lot of bizarre stuff. if not self._DECIMAL_DIGITS.issuperset(octet_str): msg = "Only decimal digits permitted in %r" raise ValueError(msg % octet_str) # We do the length check second, since the invalid character error # is likely to be more informative for the user if len(octet_str) > 3: msg = "At most 3 characters permitted in %r" raise ValueError(msg % octet_str) # Convert to integer (we know digits are legal) octet_int = int(octet_str, 10) # Any octets that look like they *might* be written in octal, # and which don't look exactly the same in both octal and # decimal are rejected as ambiguous if octet_int > 7 and octet_str[0] == '0': msg = "Ambiguous (octal/decimal) value in %r not permitted" raise ValueError(msg % octet_str) if octet_int > 255: raise ValueError("Octet %d (> 255) not permitted" % octet_int) return octet_int def _string_from_ip_int(self, ip_int): """Turns a 32-bit integer into dotted decimal notation. Args: ip_int: An integer, the IP address. Returns: The IP address as a string in dotted decimal notation. """ return '.'.join(map(str, _int_to_bytes(ip_int, 4, 'big'))) def _is_valid_netmask(self, netmask): """Verify that the netmask is valid. Args: netmask: A string, either a prefix or dotted decimal netmask. Returns: A boolean, True if the prefix represents a valid IPv4 netmask. """ mask = netmask.split('.') if len(mask) == 4: try: for x in mask: if int(x) not in self._valid_mask_octets: return False except ValueError: # Found something that isn't an integer or isn't valid return False for idx, y in enumerate(mask): if idx > 0 and y > mask[idx - 1]: return False return True try: netmask = int(netmask) except ValueError: return False return 0 <= netmask <= self._max_prefixlen def _is_hostmask(self, ip_str): """Test if the IP string is a hostmask (rather than a netmask). Args: ip_str: A string, the potential hostmask. Returns: A boolean, True if the IP string is a hostmask. """ bits = ip_str.split('.') try: parts = [x for x in map(int, bits) if x in self._valid_mask_octets] except ValueError: return False if len(parts) != len(bits): return False if parts[0] < parts[-1]: return True return False def _reverse_pointer(self): """Return the reverse DNS pointer name for the IPv4 address. This implements the method described in RFC1035 3.5. """ reverse_octets = str(self).split('.')[::-1] return '.'.join(reverse_octets) + '.in-addr.arpa' @property def max_prefixlen(self): return self._max_prefixlen @property def version(self): return self._version class IPv4Address(_BaseV4, _BaseAddress): """Represent and manipulate single IPv4 Addresses.""" def __init__(self, address): """ Args: address: A string or integer representing the IP Additionally, an integer can be passed, so IPv4Address('192.0.2.1') == IPv4Address(3221225985). or, more generally IPv4Address(int(IPv4Address('192.0.2.1'))) == IPv4Address('192.0.2.1') Raises: AddressValueError: If ipaddress isn't a valid IPv4 address. """ _BaseAddress.__init__(self, address) _BaseV4.__init__(self, address) # Efficient constructor from integer. if isinstance(address, int): self._check_int_address(address) self._ip = address return # Constructing from a packed address if isinstance(address, bytes): self._check_packed_address(address, 4) self._ip = _int_from_bytes(address, 'big') return # Assume input argument to be string or any object representation # which converts into a formatted IP string. addr_str = str(address) self._ip = self._ip_int_from_string(addr_str) @property def packed(self): """The binary representation of this address.""" return v4_int_to_packed(self._ip) @property def is_reserved(self): """Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within the reserved IPv4 Network range. """ reserved_network = IPv4Network('240.0.0.0/4') return self in reserved_network @property def is_private(self): """Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per iana-ipv4-special-registry. """ return (self in IPv4Network('0.0.0.0/8') or self in IPv4Network('10.0.0.0/8') or self in IPv4Network('127.0.0.0/8') or self in IPv4Network('169.254.0.0/16') or self in IPv4Network('172.16.0.0/12') or self in IPv4Network('192.0.0.0/29') or self in IPv4Network('192.0.0.170/31') or self in IPv4Network('192.0.2.0/24') or self in IPv4Network('192.168.0.0/16') or self in IPv4Network('198.18.0.0/15') or self in IPv4Network('198.51.100.0/24') or self in IPv4Network('203.0.113.0/24') or self in IPv4Network('240.0.0.0/4') or self in IPv4Network('255.255.255.255/32')) @property def is_multicast(self): """Test if the address is reserved for multicast use. Returns: A boolean, True if the address is multicast. See RFC 3171 for details. """ multicast_network = IPv4Network('224.0.0.0/4') return self in multicast_network @property def is_unspecified(self): """Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in RFC 5735 3. """ unspecified_address = IPv4Address('0.0.0.0') return self == unspecified_address @property def is_loopback(self): """Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback per RFC 3330. """ loopback_network = IPv4Network('127.0.0.0/8') return self in loopback_network @property def is_link_local(self): """Test if the address is reserved for link-local. Returns: A boolean, True if the address is link-local per RFC 3927. """ linklocal_network = IPv4Network('169.254.0.0/16') return self in linklocal_network class IPv4Interface(IPv4Address): def __init__(self, address): if isinstance(address, (bytes, int)): IPv4Address.__init__(self, address) self.network = IPv4Network(self._ip) self._prefixlen = self._max_prefixlen return addr = _split_optional_netmask(address) IPv4Address.__init__(self, addr[0]) self.network = IPv4Network(address, strict=False) self._prefixlen = self.network._prefixlen self.netmask = self.network.netmask self.hostmask = self.network.hostmask def __str__(self): return '%s/%d' % (self._string_from_ip_int(self._ip), self.network.prefixlen) def __eq__(self, other): address_equal = IPv4Address.__eq__(self, other) if not address_equal or address_equal is NotImplemented: return address_equal try: return self.network == other.network except AttributeError: # An interface with an associated network is NOT the # same as an unassociated address. That's why the hash # takes the extra info into account. return False def __lt__(self, other): address_less = IPv4Address.__lt__(self, other) if address_less is NotImplemented: return NotImplemented try: return self.network < other.network except AttributeError: # We *do* allow addresses and interfaces to be sorted. The # unassociated address is considered less than all interfaces. return False def __hash__(self): return self._ip ^ self._prefixlen ^ int(self.network.network_address) @property def ip(self): return IPv4Address(self._ip) @property def with_prefixlen(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self._prefixlen) @property def with_netmask(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self.netmask) @property def with_hostmask(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self.hostmask) class IPv4Network(_BaseV4, _BaseNetwork): """This class represents and manipulates 32-bit IPv4 network + addresses.. Attributes: [examples for IPv4Network('192.0.2.0/27')] .network_address: IPv4Address('192.0.2.0') .hostmask: IPv4Address('0.0.0.31') .broadcast_address: IPv4Address('192.0.2.32') .netmask: IPv4Address('255.255.255.224') .prefixlen: 27 """ # Class to use when creating address objects _address_class = IPv4Address def __init__(self, address, strict=True): """Instantiate a new IPv4 network object. Args: address: A string or integer representing the IP [& network]. '192.0.2.0/24' '192.0.2.0/255.255.255.0' '192.0.0.2/0.0.0.255' are all functionally the same in IPv4. Similarly, '192.0.2.1' '192.0.2.1/255.255.255.255' '192.0.2.1/32' are also functionally equivalent. That is to say, failing to provide a subnetmask will create an object with a mask of /32. If the mask (portion after the / in the argument) is given in dotted quad form, it is treated as a netmask if it starts with a non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it starts with a zero field (e.g. 0.255.255.255 == /8), with the single exception of an all-zero mask which is treated as a netmask == /0. If no mask is given, a default of /32 is used. Additionally, an integer can be passed, so IPv4Network('192.0.2.1') == IPv4Network(3221225985) or, more generally IPv4Interface(int(IPv4Interface('192.0.2.1'))) == IPv4Interface('192.0.2.1') Raises: AddressValueError: If ipaddress isn't a valid IPv4 address. NetmaskValueError: If the netmask isn't valid for an IPv4 address. ValueError: If strict is True and a network address is not supplied. """ _BaseV4.__init__(self, address) _BaseNetwork.__init__(self, address) # Constructing from a packed address if isinstance(address, bytes): self.network_address = IPv4Address(address) self._prefixlen = self._max_prefixlen self.netmask = IPv4Address(self._ALL_ONES) #fixme: address/network test here return # Efficient constructor from integer. if isinstance(address, int): self.network_address = IPv4Address(address) self._prefixlen = self._max_prefixlen self.netmask = IPv4Address(self._ALL_ONES) #fixme: address/network test here. return # Assume input argument to be string or any object representation # which converts into a formatted IP prefix string. addr = _split_optional_netmask(address) self.network_address = IPv4Address(self._ip_int_from_string(addr[0])) if len(addr) == 2: try: # Check for a netmask in prefix length form self._prefixlen = self._prefix_from_prefix_string(addr[1]) except NetmaskValueError: # Check for a netmask or hostmask in dotted-quad form. # This may raise NetmaskValueError. self._prefixlen = self._prefix_from_ip_string(addr[1]) else: self._prefixlen = self._max_prefixlen self.netmask = IPv4Address(self._ip_int_from_prefix(self._prefixlen)) if strict: if (IPv4Address(int(self.network_address) & int(self.netmask)) != self.network_address): raise ValueError('%s has host bits set' % self) self.network_address = IPv4Address(int(self.network_address) & int(self.netmask)) if self._prefixlen == (self._max_prefixlen - 1): self.hosts = self.__iter__ @property def is_global(self): """Test if this address is allocated for public networks. Returns: A boolean, True if the address is not reserved per iana-ipv4-special-registry. """ return (not (self.network_address in IPv4Network('100.64.0.0/10') and self.broadcast_address in IPv4Network('100.64.0.0/10')) and not self.is_private) class _BaseV6(object): """Base IPv6 object. The following methods are used by IPv6 objects in both single IP addresses and networks. """ _ALL_ONES = (2**IPV6LENGTH) - 1 _HEXTET_COUNT = 8 _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef') def __init__(self, address): self._version = 6 self._max_prefixlen = IPV6LENGTH def _ip_int_from_string(self, ip_str): """Turn an IPv6 ip_str into an integer. Args: ip_str: A string, the IPv6 ip_str. Returns: An int, the IPv6 address Raises: AddressValueError: if ip_str isn't a valid IPv6 Address. """ if not ip_str: raise AddressValueError('Address cannot be empty') parts = ip_str.split(':') # An IPv6 address needs at least 2 colons (3 parts). _min_parts = 3 if len(parts) < _min_parts: msg = "At least %d parts expected in %r" % (_min_parts, ip_str) raise AddressValueError(msg) # If the address has an IPv4-style suffix, convert it to hexadecimal. if '.' in parts[-1]: try: ipv4_int = IPv4Address(parts.pop())._ip except AddressValueError as exc: raise AddressValueError("%s in %r" % (exc, ip_str)) parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF)) parts.append('%x' % (ipv4_int & 0xFFFF)) # An IPv6 address can't have more than 8 colons (9 parts). # The extra colon comes from using the "::" notation for a single # leading or trailing zero part. _max_parts = self._HEXTET_COUNT + 1 if len(parts) > _max_parts: msg = "At most %d colons permitted in %r" % (_max_parts-1, ip_str) raise AddressValueError(msg) # Disregarding the endpoints, find '::' with nothing in between. # This indicates that a run of zeroes has been skipped. skip_index = None for i in range(1, len(parts) - 1): if not parts[i]: if skip_index is not None: # Can't have more than one '::' msg = "At most one '::' permitted in %r" % ip_str raise AddressValueError(msg) skip_index = i # parts_hi is the number of parts to copy from above/before the '::' # parts_lo is the number of parts to copy from below/after the '::' if skip_index is not None: # If we found a '::', then check if it also covers the endpoints. parts_hi = skip_index parts_lo = len(parts) - skip_index - 1 if not parts[0]: parts_hi -= 1 if parts_hi: msg = "Leading ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # ^: requires ^:: if not parts[-1]: parts_lo -= 1 if parts_lo: msg = "Trailing ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # :$ requires ::$ parts_skipped = self._HEXTET_COUNT - (parts_hi + parts_lo) if parts_skipped < 1: msg = "Expected at most %d other parts with '::' in %r" raise AddressValueError(msg % (self._HEXTET_COUNT-1, ip_str)) else: # Otherwise, allocate the entire address to parts_hi. The # endpoints could still be empty, but _parse_hextet() will check # for that. if len(parts) != self._HEXTET_COUNT: msg = "Exactly %d parts expected without '::' in %r" raise AddressValueError(msg % (self._HEXTET_COUNT, ip_str)) if not parts[0]: msg = "Leading ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # ^: requires ^:: if not parts[-1]: msg = "Trailing ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # :$ requires ::$ parts_hi = len(parts) parts_lo = 0 parts_skipped = 0 try: # Now, parse the hextets into a 128-bit integer. ip_int = 0 for i in range(parts_hi): ip_int <<= 16 ip_int |= self._parse_hextet(parts[i]) ip_int <<= 16 * parts_skipped for i in range(-parts_lo, 0): ip_int <<= 16 ip_int |= self._parse_hextet(parts[i]) return ip_int except ValueError as exc: raise AddressValueError("%s in %r" % (exc, ip_str)) def _parse_hextet(self, hextet_str): """Convert an IPv6 hextet string into an integer. Args: hextet_str: A string, the number to parse. Returns: The hextet as an integer. Raises: ValueError: if the input isn't strictly a hex number from [0..FFFF]. """ # Whitelist the characters, since int() allows a lot of bizarre stuff. if not self._HEX_DIGITS.issuperset(hextet_str): raise ValueError("Only hex digits permitted in %r" % hextet_str) # We do the length check second, since the invalid character error # is likely to be more informative for the user if len(hextet_str) > 4: msg = "At most 4 characters permitted in %r" raise ValueError(msg % hextet_str) # Length check means we can skip checking the integer value return int(hextet_str, 16) def _compress_hextets(self, hextets): """Compresses a list of hextets. Compresses a list of strings, replacing the longest continuous sequence of "0" in the list with "" and adding empty strings at the beginning or at the end of the string such that subsequently calling ":".join(hextets) will produce the compressed version of the IPv6 address. Args: hextets: A list of strings, the hextets to compress. Returns: A list of strings. """ best_doublecolon_start = -1 best_doublecolon_len = 0 doublecolon_start = -1 doublecolon_len = 0 for index, hextet in enumerate(hextets): if hextet == '0': doublecolon_len += 1 if doublecolon_start == -1: # Start of a sequence of zeros. doublecolon_start = index if doublecolon_len > best_doublecolon_len: # This is the longest sequence of zeros so far. best_doublecolon_len = doublecolon_len best_doublecolon_start = doublecolon_start else: doublecolon_len = 0 doublecolon_start = -1 if best_doublecolon_len > 1: best_doublecolon_end = (best_doublecolon_start + best_doublecolon_len) # For zeros at the end of the address. if best_doublecolon_end == len(hextets): hextets += [''] hextets[best_doublecolon_start:best_doublecolon_end] = [''] # For zeros at the beginning of the address. if best_doublecolon_start == 0: hextets = [''] + hextets return hextets def _string_from_ip_int(self, ip_int=None): """Turns a 128-bit integer into hexadecimal notation. Args: ip_int: An integer, the IP address. Returns: A string, the hexadecimal representation of the address. Raises: ValueError: The address is bigger than 128 bits of all ones. """ if ip_int is None: ip_int = int(self._ip) if ip_int > self._ALL_ONES: raise ValueError('IPv6 address is too large') hex_str = '%032x' % ip_int hextets = ['%x' % int(hex_str[x:x+4], 16) for x in range(0, 32, 4)] hextets = self._compress_hextets(hextets) return ':'.join(hextets) def _explode_shorthand_ip_string(self): """Expand a shortened IPv6 address. Args: ip_str: A string, the IPv6 address. Returns: A string, the expanded IPv6 address. """ if isinstance(self, IPv6Network): ip_str = str(self.network_address) elif isinstance(self, IPv6Interface): ip_str = str(self.ip) else: ip_str = str(self) ip_int = self._ip_int_from_string(ip_str) hex_str = '%032x' % ip_int parts = [hex_str[x:x+4] for x in range(0, 32, 4)] if isinstance(self, (_BaseNetwork, IPv6Interface)): return '%s/%d' % (':'.join(parts), self._prefixlen) return ':'.join(parts) def _reverse_pointer(self): """Return the reverse DNS pointer name for the IPv6 address. This implements the method described in RFC3596 2.5. """ reverse_chars = self.exploded[::-1].replace(':', '') return '.'.join(reverse_chars) + '.ip6.arpa' @property def max_prefixlen(self): return self._max_prefixlen @property def version(self): return self._version class IPv6Address(_BaseV6, _BaseAddress): """Represent and manipulate single IPv6 Addresses.""" def __init__(self, address): """Instantiate a new IPv6 address object. Args: address: A string or integer representing the IP Additionally, an integer can be passed, so IPv6Address('2001:db8::') == IPv6Address(42540766411282592856903984951653826560) or, more generally IPv6Address(int(IPv6Address('2001:db8::'))) == IPv6Address('2001:db8::') Raises: AddressValueError: If address isn't a valid IPv6 address. """ _BaseAddress.__init__(self, address) _BaseV6.__init__(self, address) # Efficient constructor from integer. if isinstance(address, int): self._check_int_address(address) self._ip = address return # Constructing from a packed address if isinstance(address, bytes): self._check_packed_address(address, 16) self._ip = _int_from_bytes(address, 'big') return # Assume input argument to be string or any object representation # which converts into a formatted IP string. addr_str = str(address) self._ip = self._ip_int_from_string(addr_str) @property def packed(self): """The binary representation of this address.""" return v6_int_to_packed(self._ip) @property def is_multicast(self): """Test if the address is reserved for multicast use. Returns: A boolean, True if the address is a multicast address. See RFC 2373 2.7 for details. """ multicast_network = IPv6Network('ff00::/8') return self in multicast_network @property def is_reserved(self): """Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within one of the reserved IPv6 Network ranges. """ reserved_networks = [IPv6Network('::/8'), IPv6Network('100::/8'), IPv6Network('200::/7'), IPv6Network('400::/6'), IPv6Network('800::/5'), IPv6Network('1000::/4'), IPv6Network('4000::/3'), IPv6Network('6000::/3'), IPv6Network('8000::/3'), IPv6Network('A000::/3'), IPv6Network('C000::/3'), IPv6Network('E000::/4'), IPv6Network('F000::/5'), IPv6Network('F800::/6'), IPv6Network('FE00::/9')] return any(self in x for x in reserved_networks) @property def is_link_local(self): """Test if the address is reserved for link-local. Returns: A boolean, True if the address is reserved per RFC 4291. """ linklocal_network = IPv6Network('fe80::/10') return self in linklocal_network @property def is_site_local(self): """Test if the address is reserved for site-local. Note that the site-local address space has been deprecated by RFC 3879. Use is_private to test if this address is in the space of unique local addresses as defined by RFC 4193. Returns: A boolean, True if the address is reserved per RFC 3513 2.5.6. """ sitelocal_network = IPv6Network('fec0::/10') return self in sitelocal_network @property def is_private(self): """Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per iana-ipv6-special-registry. """ return (self in IPv6Network('::1/128') or self in IPv6Network('::/128') or self in IPv6Network('::ffff:0:0/96') or self in IPv6Network('100::/64') or self in IPv6Network('2001::/23') or self in IPv6Network('2001:2::/48') or self in IPv6Network('2001:db8::/32') or self in IPv6Network('2001:10::/28') or self in IPv6Network('fc00::/7') or self in IPv6Network('fe80::/10')) @property def is_global(self): """Test if this address is allocated for public networks. Returns: A boolean, true if the address is not reserved per iana-ipv6-special-registry. """ return not self.is_private @property def is_unspecified(self): """Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in RFC 2373 2.5.2. """ return self._ip == 0 @property def is_loopback(self): """Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback address as defined in RFC 2373 2.5.3. """ return self._ip == 1 @property def ipv4_mapped(self): """Return the IPv4 mapped address. Returns: If the IPv6 address is a v4 mapped address, return the IPv4 mapped address. Return None otherwise. """ if (self._ip >> 32) != 0xFFFF: return None return IPv4Address(self._ip & 0xFFFFFFFF) @property def teredo(self): """Tuple of embedded teredo IPs. Returns: Tuple of the (server, client) IPs or None if the address doesn't appear to be a teredo address (doesn't start with 2001::/32) """ if (self._ip >> 96) != 0x20010000: return None return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF), IPv4Address(~self._ip & 0xFFFFFFFF)) @property def sixtofour(self): """Return the IPv4 6to4 embedded address. Returns: The IPv4 6to4-embedded address if present or None if the address doesn't appear to contain a 6to4 embedded address. """ if (self._ip >> 112) != 0x2002: return None return IPv4Address((self._ip >> 80) & 0xFFFFFFFF) class IPv6Interface(IPv6Address): def __init__(self, address): if isinstance(address, (bytes, int)): IPv6Address.__init__(self, address) self.network = IPv6Network(self._ip) self._prefixlen = self._max_prefixlen return addr = _split_optional_netmask(address) IPv6Address.__init__(self, addr[0]) self.network = IPv6Network(address, strict=False) self.netmask = self.network.netmask self._prefixlen = self.network._prefixlen self.hostmask = self.network.hostmask def __str__(self): return '%s/%d' % (self._string_from_ip_int(self._ip), self.network.prefixlen) def __eq__(self, other): address_equal = IPv6Address.__eq__(self, other) if not address_equal or address_equal is NotImplemented: return address_equal try: return self.network == other.network except AttributeError: # An interface with an associated network is NOT the # same as an unassociated address. That's why the hash # takes the extra info into account. return False def __lt__(self, other): address_less = IPv6Address.__lt__(self, other) if address_less is NotImplemented: return NotImplemented try: return self.network < other.network except AttributeError: # We *do* allow addresses and interfaces to be sorted. The # unassociated address is considered less than all interfaces. return False def __hash__(self): return self._ip ^ self._prefixlen ^ int(self.network.network_address) @property def ip(self): return IPv6Address(self._ip) @property def with_prefixlen(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self._prefixlen) @property def with_netmask(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self.netmask) @property def with_hostmask(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self.hostmask) @property def is_unspecified(self): return self._ip == 0 and self.network.is_unspecified @property def is_loopback(self): return self._ip == 1 and self.network.is_loopback class IPv6Network(_BaseV6, _BaseNetwork): """This class represents and manipulates 128-bit IPv6 networks. Attributes: [examples for IPv6('2001:db8::1000/124')] .network_address: IPv6Address('2001:db8::1000') .hostmask: IPv6Address('::f') .broadcast_address: IPv6Address('2001:db8::100f') .netmask: IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0') .prefixlen: 124 """ # Class to use when creating address objects _address_class = IPv6Address def __init__(self, address, strict=True): """Instantiate a new IPv6 Network object. Args: address: A string or integer representing the IPv6 network or the IP and prefix/netmask. '2001:db8::/128' '2001:db8:0000:0000:0000:0000:0000:0000/128' '2001:db8::' are all functionally the same in IPv6. That is to say, failing to provide a subnetmask will create an object with a mask of /128. Additionally, an integer can be passed, so IPv6Network('2001:db8::') == IPv6Network(42540766411282592856903984951653826560) or, more generally IPv6Network(int(IPv6Network('2001:db8::'))) == IPv6Network('2001:db8::') strict: A boolean. If true, ensure that we have been passed A true network address, eg, 2001:db8::1000/124 and not an IP address on a network, eg, 2001:db8::1/124. Raises: AddressValueError: If address isn't a valid IPv6 address. NetmaskValueError: If the netmask isn't valid for an IPv6 address. ValueError: If strict was True and a network address was not supplied. """ _BaseV6.__init__(self, address) _BaseNetwork.__init__(self, address) # Efficient constructor from integer. if isinstance(address, int): self.network_address = IPv6Address(address) self._prefixlen = self._max_prefixlen self.netmask = IPv6Address(self._ALL_ONES) return # Constructing from a packed address if isinstance(address, bytes): self.network_address = IPv6Address(address) self._prefixlen = self._max_prefixlen self.netmask = IPv6Address(self._ALL_ONES) return # Assume input argument to be string or any object representation # which converts into a formatted IP prefix string. addr = _split_optional_netmask(address) self.network_address = IPv6Address(self._ip_int_from_string(addr[0])) if len(addr) == 2: # This may raise NetmaskValueError self._prefixlen = self._prefix_from_prefix_string(addr[1]) else: self._prefixlen = self._max_prefixlen self.netmask = IPv6Address(self._ip_int_from_prefix(self._prefixlen)) if strict: if (IPv6Address(int(self.network_address) & int(self.netmask)) != self.network_address): raise ValueError('%s has host bits set' % self) self.network_address = IPv6Address(int(self.network_address) & int(self.netmask)) if self._prefixlen == (self._max_prefixlen - 1): self.hosts = self.__iter__ def hosts(self): """Generate Iterator over usable hosts in a network. This is like __iter__ except it doesn't return the Subnet-Router anycast address. """ network = int(self.network_address) broadcast = int(self.broadcast_address) for x in long_range(1, broadcast - network + 1): yield self._address_class(network + x) @property def is_site_local(self): """Test if the address is reserved for site-local. Note that the site-local address space has been deprecated by RFC 3879. Use is_private to test if this address is in the space of unique local addresses as defined by RFC 4193. Returns: A boolean, True if the address is reserved per RFC 3513 2.5.6. """ return (self.network_address.is_site_local and self.broadcast_address.is_site_local)
saltstack/salt
salt/ext/ipaddress.py
collapse_addresses
python
def collapse_addresses(addresses): i = 0 addrs = [] ips = [] nets = [] # split IP addresses and networks for ip in addresses: if isinstance(ip, _BaseAddress): if ips and ips[-1]._version != ip._version: raise TypeError("%s and %s are not of the same version" % ( ip, ips[-1])) ips.append(ip) elif ip._prefixlen == ip._max_prefixlen: if ips and ips[-1]._version != ip._version: raise TypeError("%s and %s are not of the same version" % ( ip, ips[-1])) try: ips.append(ip.ip) except AttributeError: ips.append(ip.network_address) else: if nets and nets[-1]._version != ip._version: raise TypeError("%s and %s are not of the same version" % ( ip, nets[-1])) nets.append(ip) # sort and dedup ips = sorted(set(ips)) nets = sorted(set(nets)) while i < len(ips): (first, last) = _find_address_range(ips[i:]) i = ips.index(last) + 1 addrs.extend(summarize_address_range(first, last)) return iter(_collapse_addresses_recursive(sorted( addrs + nets, key=_BaseNetwork._get_networks_key)))
Collapse a list of IP objects. Example: collapse_addresses([IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/25')]) -> [IPv4Network('192.0.2.0/24')] Args: addresses: An iterator of IPv4Network or IPv6Network objects. Returns: An iterator of the collapsed IPv(4|6)Network objects. Raises: TypeError: If passed a list of mixed version objects.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/ext/ipaddress.py#L375-L429
[ "def isinstance(val, types):\n if types is int:\n types = (int, long)\n elif type(types) is tuple and int in types:\n types += (long,)\n return _builtin_isinstance(val, types)\n", "def _find_address_range(addresses):\n \"\"\"Find a sequence of IPv#Address.\n\n Args:\n addresses: a list of IPv#Address objects.\n\n Returns:\n A tuple containing the first and last IP addresses in the sequence.\n\n \"\"\"\n first = last = addresses[0]\n for ip in addresses[1:]:\n if ip._ip == last._ip + 1:\n last = ip\n else:\n break\n return (first, last)\n", "def summarize_address_range(first, last):\n \"\"\"Summarize a network range given the first and last IP addresses.\n\n Example:\n >>> list(summarize_address_range(IPv4Address('192.0.2.0'),\n ... IPv4Address('192.0.2.130')))\n ... #doctest: +NORMALIZE_WHITESPACE\n [IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/31'),\n IPv4Network('192.0.2.130/32')]\n\n Args:\n first: the first IPv4Address or IPv6Address in the range.\n last: the last IPv4Address or IPv6Address in the range.\n\n Returns:\n An iterator of the summarized IPv(4|6) network objects.\n\n Raise:\n TypeError:\n If the first and last objects are not IP addresses.\n If the first and last objects are not the same version.\n ValueError:\n If the last object is not greater than the first.\n If the version of the first address is not 4 or 6.\n\n \"\"\"\n if (not (isinstance(first, _BaseAddress) and\n isinstance(last, _BaseAddress))):\n raise TypeError('first and last must be IP addresses, not networks')\n if first.version != last.version:\n raise TypeError(\"%s and %s are not of the same version\" % (\n first, last))\n if first > last:\n raise ValueError('last IP address must be greater than first')\n\n if first.version == 4:\n ip = IPv4Network\n elif first.version == 6:\n ip = IPv6Network\n else:\n raise ValueError('unknown IP version')\n\n ip_bits = first._max_prefixlen\n first_int = first._ip\n last_int = last._ip\n while first_int <= last_int:\n nbits = min(_count_righthand_zero_bits(first_int, ip_bits),\n _int_bit_length(last_int - first_int + 1) - 1)\n net = ip('%s/%d' % (first, ip_bits - nbits))\n yield net\n first_int += 1 << nbits\n if first_int - 1 == ip._ALL_ONES:\n break\n first = first.__class__(first_int)\n", "def _collapse_addresses_recursive(addresses):\n \"\"\"Loops through the addresses, collapsing concurrent netblocks.\n\n Example:\n\n ip1 = IPv4Network('192.0.2.0/26')\n ip2 = IPv4Network('192.0.2.64/26')\n ip3 = IPv4Network('192.0.2.128/26')\n ip4 = IPv4Network('192.0.2.192/26')\n\n _collapse_addresses_recursive([ip1, ip2, ip3, ip4]) ->\n [IPv4Network('192.0.2.0/24')]\n\n This shouldn't be called directly; it is called via\n collapse_addresses([]).\n\n Args:\n addresses: A list of IPv4Network's or IPv6Network's\n\n Returns:\n A list of IPv4Network's or IPv6Network's depending on what we were\n passed.\n\n \"\"\"\n while True:\n last_addr = None\n ret_array = []\n optimized = False\n\n for cur_addr in addresses:\n if not ret_array:\n last_addr = cur_addr\n ret_array.append(cur_addr)\n elif (cur_addr.network_address >= last_addr.network_address and\n cur_addr.broadcast_address <= last_addr.broadcast_address):\n optimized = True\n elif cur_addr == list(last_addr.supernet().subnets())[1]:\n ret_array[-1] = last_addr = last_addr.supernet()\n optimized = True\n else:\n last_addr = cur_addr\n ret_array.append(cur_addr)\n\n addresses = ret_array\n if not optimized:\n return addresses\n" ]
''' Python 2.[67] port of Python 3.4's ipaddress module Almost verbatim copy of the core lib, with compatibility changes Source: https://bitbucket.org/kwi/py2-ipaddress/ ''' # pylint: skip-file # List of compatibility changes: # Python 3 uses only new-style classes. # s/class \(\w\+\):/class \1(object):/ # Use iterator versions of map and range: from itertools import imap as map range = xrange # Except that xrange only supports machine integers, not longs, so... def long_range(start, end): while start < end: yield start start += 1 # This backport uses bytearray instead of bytes, as bytes is the same # as str in Python 2.7. bytes = bytearray # Python 2 does not support exception chaining. # s/ from None$// # When checking for instances of int, also allow Python 2's long. _builtin_isinstance = isinstance def isinstance(val, types): if types is int: types = (int, long) elif type(types) is tuple and int in types: types += (long,) return _builtin_isinstance(val, types) # functools.lru_cache is Python 3.2+ only. # /@functools.lru_cache()/d # int().to_bytes is Python 3.2+ only. # s/\(\w+\)\.to_bytes(/_int_to_bytes(\1, / def _int_to_bytes(self, length, byteorder, signed=False): assert byteorder == 'big' and signed is False if self < 0 or self >= 256**length: raise OverflowError() return bytearray(('%0*x' % (length * 2, self)).decode('hex')) # int.from_bytes is Python 3.2+ only. # s/int\.from_bytes(/_int_from_bytes(/g def _int_from_bytes(what, byteorder, signed=False): assert byteorder == 'big' and signed is False return int(str(bytearray(what)).encode('hex'), 16) # Python 2.6 has no int.bit_length() if hasattr(int, 'bit_length'): _int_bit_length = lambda i: i.bit_length() else: _int_bit_length = lambda i: len(bin(abs(i))) - 2 # ---------------------------------------------------------------------------- # Copyright 2007 Google Inc. # Licensed to PSF under a Contributor Agreement. """A fast, lightweight IPv4/IPv6 manipulation library in Python. This library is used to create/poke/manipulate IPv4 and IPv6 addresses and networks. """ __version__ = '1.0' import functools IPV4LENGTH = 32 IPV6LENGTH = 128 class AddressValueError(ValueError): """A Value Error related to the address.""" class NetmaskValueError(ValueError): """A Value Error related to the netmask.""" def ip_address(address): """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Address or IPv6Address object. Raises: ValueError: if the *address* passed isn't either a v4 or a v6 address """ try: return IPv4Address(address) except (AddressValueError, NetmaskValueError): pass try: return IPv6Address(address) except (AddressValueError, NetmaskValueError): pass raise ValueError('%r does not appear to be an IPv4 or IPv6 address' % address) def ip_network(address, strict=True): """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP network. Either IPv4 or IPv6 networks may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Network or IPv6Network object. Raises: ValueError: if the string passed isn't either a v4 or a v6 address. Or if the network has host bits set. """ try: return IPv4Network(address, strict) except (AddressValueError, NetmaskValueError): pass try: return IPv6Network(address, strict) except (AddressValueError, NetmaskValueError): pass raise ValueError('%r does not appear to be an IPv4 or IPv6 network' % address) def ip_interface(address): """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Interface or IPv6Interface object. Raises: ValueError: if the string passed isn't either a v4 or a v6 address. Notes: The IPv?Interface classes describe an Address on a particular Network, so they're basically a combination of both the Address and Network classes. """ try: return IPv4Interface(address) except (AddressValueError, NetmaskValueError): pass try: return IPv6Interface(address) except (AddressValueError, NetmaskValueError): pass raise ValueError('%r does not appear to be an IPv4 or IPv6 interface' % address) def v4_int_to_packed(address): """Represent an address as 4 packed bytes in network (big-endian) order. Args: address: An integer representation of an IPv4 IP address. Returns: The integer address packed as 4 bytes in network (big-endian) order. Raises: ValueError: If the integer is negative or too large to be an IPv4 IP address. """ try: return _int_to_bytes(address, 4, 'big') except Exception: raise ValueError("Address negative or too large for IPv4") def v6_int_to_packed(address): """Represent an address as 16 packed bytes in network (big-endian) order. Args: address: An integer representation of an IPv6 IP address. Returns: The integer address packed as 16 bytes in network (big-endian) order. """ try: return _int_to_bytes(address, 16, 'big') except Exception: raise ValueError("Address negative or too large for IPv6") def _split_optional_netmask(address): """Helper to split the netmask and raise AddressValueError if needed""" addr = str(address).split('/') if len(addr) > 2: raise AddressValueError("Only one '/' permitted in %r" % address) return addr def _find_address_range(addresses): """Find a sequence of IPv#Address. Args: addresses: a list of IPv#Address objects. Returns: A tuple containing the first and last IP addresses in the sequence. """ first = last = addresses[0] for ip in addresses[1:]: if ip._ip == last._ip + 1: last = ip else: break return (first, last) def _count_righthand_zero_bits(number, bits): """Count the number of zero bits on the right hand side. Args: number: an integer. bits: maximum number of bits to count. Returns: The number of zero bits on the right hand side of the number. """ if number == 0: return bits for i in range(bits): if (number >> i) & 1: return i # All bits of interest were zero, even if there are more in the number return bits def summarize_address_range(first, last): """Summarize a network range given the first and last IP addresses. Example: >>> list(summarize_address_range(IPv4Address('192.0.2.0'), ... IPv4Address('192.0.2.130'))) ... #doctest: +NORMALIZE_WHITESPACE [IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/31'), IPv4Network('192.0.2.130/32')] Args: first: the first IPv4Address or IPv6Address in the range. last: the last IPv4Address or IPv6Address in the range. Returns: An iterator of the summarized IPv(4|6) network objects. Raise: TypeError: If the first and last objects are not IP addresses. If the first and last objects are not the same version. ValueError: If the last object is not greater than the first. If the version of the first address is not 4 or 6. """ if (not (isinstance(first, _BaseAddress) and isinstance(last, _BaseAddress))): raise TypeError('first and last must be IP addresses, not networks') if first.version != last.version: raise TypeError("%s and %s are not of the same version" % ( first, last)) if first > last: raise ValueError('last IP address must be greater than first') if first.version == 4: ip = IPv4Network elif first.version == 6: ip = IPv6Network else: raise ValueError('unknown IP version') ip_bits = first._max_prefixlen first_int = first._ip last_int = last._ip while first_int <= last_int: nbits = min(_count_righthand_zero_bits(first_int, ip_bits), _int_bit_length(last_int - first_int + 1) - 1) net = ip('%s/%d' % (first, ip_bits - nbits)) yield net first_int += 1 << nbits if first_int - 1 == ip._ALL_ONES: break first = first.__class__(first_int) def _collapse_addresses_recursive(addresses): """Loops through the addresses, collapsing concurrent netblocks. Example: ip1 = IPv4Network('192.0.2.0/26') ip2 = IPv4Network('192.0.2.64/26') ip3 = IPv4Network('192.0.2.128/26') ip4 = IPv4Network('192.0.2.192/26') _collapse_addresses_recursive([ip1, ip2, ip3, ip4]) -> [IPv4Network('192.0.2.0/24')] This shouldn't be called directly; it is called via collapse_addresses([]). Args: addresses: A list of IPv4Network's or IPv6Network's Returns: A list of IPv4Network's or IPv6Network's depending on what we were passed. """ while True: last_addr = None ret_array = [] optimized = False for cur_addr in addresses: if not ret_array: last_addr = cur_addr ret_array.append(cur_addr) elif (cur_addr.network_address >= last_addr.network_address and cur_addr.broadcast_address <= last_addr.broadcast_address): optimized = True elif cur_addr == list(last_addr.supernet().subnets())[1]: ret_array[-1] = last_addr = last_addr.supernet() optimized = True else: last_addr = cur_addr ret_array.append(cur_addr) addresses = ret_array if not optimized: return addresses def get_mixed_type_key(obj): """Return a key suitable for sorting between networks and addresses. Address and Network objects are not sortable by default; they're fundamentally different so the expression IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24') doesn't make any sense. There are some times however, where you may wish to have ipaddress sort these for you anyway. If you need to do this, you can use this function as the key= argument to sorted(). Args: obj: either a Network or Address object. Returns: appropriate key. """ if isinstance(obj, _BaseNetwork): return obj._get_networks_key() elif isinstance(obj, _BaseAddress): return obj._get_address_key() return NotImplemented class _TotalOrderingMixin(object): # Helper that derives the other comparison operations from # __lt__ and __eq__ # We avoid functools.total_ordering because it doesn't handle # NotImplemented correctly yet (http://bugs.python.org/issue10042) def __eq__(self, other): raise NotImplementedError def __ne__(self, other): equal = self.__eq__(other) if equal is NotImplemented: return NotImplemented return not equal def __lt__(self, other): raise NotImplementedError def __le__(self, other): less = self.__lt__(other) if less is NotImplemented or not less: return self.__eq__(other) return less def __gt__(self, other): less = self.__lt__(other) if less is NotImplemented: return NotImplemented equal = self.__eq__(other) if equal is NotImplemented: return NotImplemented return not (less or equal) def __ge__(self, other): less = self.__lt__(other) if less is NotImplemented: return NotImplemented return not less class _IPAddressBase(_TotalOrderingMixin): """The mother class.""" @property def exploded(self): """Return the longhand version of the IP address as a string.""" return self._explode_shorthand_ip_string() @property def compressed(self): """Return the shorthand version of the IP address as a string.""" return str(self) @property def reverse_pointer(self): """The name of the reverse DNS pointer for the IP address, e.g.: >>> ipaddress.ip_address("127.0.0.1").reverse_pointer '1.0.0.127.in-addr.arpa' >>> ipaddress.ip_address("2001:db8::1").reverse_pointer '1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa' """ return self._reverse_pointer() @property def version(self): msg = '%200s has no version specified' % (type(self),) raise NotImplementedError(msg) def _check_int_address(self, address): if address < 0: msg = "%d (< 0) is not permitted as an IPv%d address" raise AddressValueError(msg % (address, self._version)) if address > self._ALL_ONES: msg = "%d (>= 2**%d) is not permitted as an IPv%d address" raise AddressValueError(msg % (address, self._max_prefixlen, self._version)) def _check_packed_address(self, address, expected_len): address_len = len(address) if address_len != expected_len: msg = "%r (len %d != %d) is not permitted as an IPv%d address" raise AddressValueError(msg % (address, address_len, expected_len, self._version)) def _ip_int_from_prefix(self, prefixlen): """Turn the prefix length into a bitwise netmask Args: prefixlen: An integer, the prefix length. Returns: An integer. """ return self._ALL_ONES ^ (self._ALL_ONES >> prefixlen) def _prefix_from_ip_int(self, ip_int): """Return prefix length from the bitwise netmask. Args: ip_int: An integer, the netmask in expanded bitwise format Returns: An integer, the prefix length. Raises: ValueError: If the input intermingles zeroes & ones """ trailing_zeroes = _count_righthand_zero_bits(ip_int, self._max_prefixlen) prefixlen = self._max_prefixlen - trailing_zeroes leading_ones = ip_int >> trailing_zeroes all_ones = (1 << prefixlen) - 1 if leading_ones != all_ones: byteslen = self._max_prefixlen // 8 details = _int_to_bytes(ip_int, byteslen, 'big') msg = 'Netmask pattern %r mixes zeroes & ones' raise ValueError(msg % details) return prefixlen def _report_invalid_netmask(self, netmask_str): msg = '%r is not a valid netmask' % netmask_str raise NetmaskValueError(msg) def _prefix_from_prefix_string(self, prefixlen_str): """Return prefix length from a numeric string Args: prefixlen_str: The string to be converted Returns: An integer, the prefix length. Raises: NetmaskValueError: If the input is not a valid netmask """ # int allows a leading +/- as well as surrounding whitespace, # so we ensure that isn't the case if not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str): self._report_invalid_netmask(prefixlen_str) try: prefixlen = int(prefixlen_str) except ValueError: self._report_invalid_netmask(prefixlen_str) if not (0 <= prefixlen <= self._max_prefixlen): self._report_invalid_netmask(prefixlen_str) return prefixlen def _prefix_from_ip_string(self, ip_str): """Turn a netmask/hostmask string into a prefix length Args: ip_str: The netmask/hostmask to be converted Returns: An integer, the prefix length. Raises: NetmaskValueError: If the input is not a valid netmask/hostmask """ # Parse the netmask/hostmask like an IP address. try: ip_int = self._ip_int_from_string(ip_str) except AddressValueError: self._report_invalid_netmask(ip_str) # Try matching a netmask (this would be /1*0*/ as a bitwise regexp). # Note that the two ambiguous cases (all-ones and all-zeroes) are # treated as netmasks. try: return self._prefix_from_ip_int(ip_int) except ValueError: pass # Invert the bits, and try matching a /0+1+/ hostmask instead. ip_int ^= self._ALL_ONES try: return self._prefix_from_ip_int(ip_int) except ValueError: self._report_invalid_netmask(ip_str) class _BaseAddress(_IPAddressBase): """A generic IP object. This IP class contains the version independent methods which are used by single IP addresses. """ def __init__(self, address): if (not isinstance(address, bytes) and '/' in str(address)): raise AddressValueError("Unexpected '/' in %r" % address) def __int__(self): return self._ip def __eq__(self, other): try: return (self._ip == other._ip and self._version == other._version) except AttributeError: return NotImplemented def __lt__(self, other): if self._version != other._version: raise TypeError('%s and %s are not of the same version' % ( self, other)) if not isinstance(other, _BaseAddress): raise TypeError('%s and %s are not of the same type' % ( self, other)) if self._ip != other._ip: return self._ip < other._ip return False # Shorthand for Integer addition and subtraction. This is not # meant to ever support addition/subtraction of addresses. def __add__(self, other): if not isinstance(other, int): return NotImplemented return self.__class__(int(self) + other) def __sub__(self, other): if not isinstance(other, int): return NotImplemented return self.__class__(int(self) - other) def __repr__(self): return '%s(%r)' % (self.__class__.__name__, str(self)) def __str__(self): return str(self._string_from_ip_int(self._ip)) def __hash__(self): return hash(hex(int(self._ip))) def _get_address_key(self): return (self._version, self) class _BaseNetwork(_IPAddressBase): """A generic IP network object. This IP class contains the version independent methods which are used by networks. """ def __init__(self, address): self._cache = {} def __repr__(self): return '%s(%r)' % (self.__class__.__name__, str(self)) def __str__(self): return '%s/%d' % (self.network_address, self.prefixlen) def hosts(self): """Generate Iterator over usable hosts in a network. This is like __iter__ except it doesn't return the network or broadcast addresses. """ network = int(self.network_address) broadcast = int(self.broadcast_address) for x in long_range(network + 1, broadcast): yield self._address_class(x) def __iter__(self): network = int(self.network_address) broadcast = int(self.broadcast_address) for x in long_range(network, broadcast + 1): yield self._address_class(x) def __getitem__(self, n): network = int(self.network_address) broadcast = int(self.broadcast_address) if n >= 0: if network + n > broadcast: raise IndexError return self._address_class(network + n) else: n += 1 if broadcast + n < network: raise IndexError return self._address_class(broadcast + n) def __lt__(self, other): if self._version != other._version: raise TypeError('%s and %s are not of the same version' % ( self, other)) if not isinstance(other, _BaseNetwork): raise TypeError('%s and %s are not of the same type' % ( self, other)) if self.network_address != other.network_address: return self.network_address < other.network_address if self.netmask != other.netmask: return self.netmask < other.netmask return False def __eq__(self, other): try: return (self._version == other._version and self.network_address == other.network_address and int(self.netmask) == int(other.netmask)) except AttributeError: return NotImplemented def __hash__(self): return hash(int(self.network_address) ^ int(self.netmask)) def __contains__(self, other): # always false if one is v4 and the other is v6. if self._version != other._version: return False # dealing with another network. if isinstance(other, _BaseNetwork): return False # dealing with another address else: # address return (int(self.network_address) <= int(other._ip) <= int(self.broadcast_address)) def overlaps(self, other): """Tell if self is partly contained in other.""" return self.network_address in other or ( self.broadcast_address in other or ( other.network_address in self or ( other.broadcast_address in self))) @property def broadcast_address(self): x = self._cache.get('broadcast_address') if x is None: x = self._address_class(int(self.network_address) | int(self.hostmask)) self._cache['broadcast_address'] = x return x @property def hostmask(self): x = self._cache.get('hostmask') if x is None: x = self._address_class(int(self.netmask) ^ self._ALL_ONES) self._cache['hostmask'] = x return x @property def with_prefixlen(self): return '%s/%d' % (self.network_address, self._prefixlen) @property def with_netmask(self): return '%s/%s' % (self.network_address, self.netmask) @property def with_hostmask(self): return '%s/%s' % (self.network_address, self.hostmask) @property def num_addresses(self): """Number of hosts in the current subnet.""" return int(self.broadcast_address) - int(self.network_address) + 1 @property def _address_class(self): # Returning bare address objects (rather than interfaces) allows for # more consistent behaviour across the network address, broadcast # address and individual host addresses. msg = '%200s has no associated address class' % (type(self),) raise NotImplementedError(msg) @property def prefixlen(self): return self._prefixlen def address_exclude(self, other): """Remove an address from a larger block. For example: addr1 = ip_network('192.0.2.0/28') addr2 = ip_network('192.0.2.1/32') addr1.address_exclude(addr2) = [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'), IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')] or IPv6: addr1 = ip_network('2001:db8::1/32') addr2 = ip_network('2001:db8::1/128') addr1.address_exclude(addr2) = [ip_network('2001:db8::1/128'), ip_network('2001:db8::2/127'), ip_network('2001:db8::4/126'), ip_network('2001:db8::8/125'), ... ip_network('2001:db8:8000::/33')] Args: other: An IPv4Network or IPv6Network object of the same type. Returns: An iterator of the IPv(4|6)Network objects which is self minus other. Raises: TypeError: If self and other are of differing address versions, or if other is not a network object. ValueError: If other is not completely contained by self. """ if not self._version == other._version: raise TypeError("%s and %s are not of the same version" % ( self, other)) if not isinstance(other, _BaseNetwork): raise TypeError("%s is not a network object" % other) if not (other.network_address >= self.network_address and other.broadcast_address <= self.broadcast_address): raise ValueError('%s not contained in %s' % (other, self)) if other == self: raise StopIteration # Make sure we're comparing the network of other. other = other.__class__('%s/%s' % (other.network_address, other.prefixlen)) s1, s2 = self.subnets() while s1 != other and s2 != other: if (other.network_address >= s1.network_address and other.broadcast_address <= s1.broadcast_address): yield s2 s1, s2 = s1.subnets() elif (other.network_address >= s2.network_address and other.broadcast_address <= s2.broadcast_address): yield s1 s1, s2 = s2.subnets() else: # If we got here, there's a bug somewhere. raise AssertionError('Error performing exclusion: ' 's1: %s s2: %s other: %s' % (s1, s2, other)) if s1 == other: yield s2 elif s2 == other: yield s1 else: # If we got here, there's a bug somewhere. raise AssertionError('Error performing exclusion: ' 's1: %s s2: %s other: %s' % (s1, s2, other)) def compare_networks(self, other): """Compare two IP objects. This is only concerned about the comparison of the integer representation of the network addresses. This means that the host bits aren't considered at all in this method. If you want to compare host bits, you can easily enough do a 'HostA._ip < HostB._ip' Args: other: An IP object. Returns: If the IP versions of self and other are the same, returns: -1 if self < other: eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25') IPv6Network('2001:db8::1000/124') < IPv6Network('2001:db8::2000/124') 0 if self == other eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24') IPv6Network('2001:db8::1000/124') == IPv6Network('2001:db8::1000/124') 1 if self > other eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25') IPv6Network('2001:db8::2000/124') > IPv6Network('2001:db8::1000/124') Raises: TypeError if the IP versions are different. """ # does this need to raise a ValueError? if self._version != other._version: raise TypeError('%s and %s are not of the same type' % ( self, other)) # self._version == other._version below here: if self.network_address < other.network_address: return -1 if self.network_address > other.network_address: return 1 # self.network_address == other.network_address below here: if self.netmask < other.netmask: return -1 if self.netmask > other.netmask: return 1 return 0 def _get_networks_key(self): """Network-only key function. Returns an object that identifies this address' network and netmask. This function is a suitable "key" argument for sorted() and list.sort(). """ return (self._version, self.network_address, self.netmask) def subnets(self, prefixlen_diff=1, new_prefix=None): """The subnets which join to make the current subnet. In the case that self contains only one IP (self._prefixlen == 32 for IPv4 or self._prefixlen == 128 for IPv6), yield an iterator with just ourself. Args: prefixlen_diff: An integer, the amount the prefix length should be increased by. This should not be set if new_prefix is also set. new_prefix: The desired new prefix length. This must be a larger number (smaller prefix) than the existing prefix. This should not be set if prefixlen_diff is also set. Returns: An iterator of IPv(4|6) objects. Raises: ValueError: The prefixlen_diff is too small or too large. OR prefixlen_diff and new_prefix are both set or new_prefix is a smaller number than the current prefix (smaller number means a larger network) """ if self._prefixlen == self._max_prefixlen: yield self return if new_prefix is not None: if new_prefix < self._prefixlen: raise ValueError('new prefix must be longer') if prefixlen_diff != 1: raise ValueError('cannot set prefixlen_diff and new_prefix') prefixlen_diff = new_prefix - self._prefixlen if prefixlen_diff < 0: raise ValueError('prefix length diff must be > 0') new_prefixlen = self._prefixlen + prefixlen_diff if new_prefixlen > self._max_prefixlen: raise ValueError( 'prefix length diff %d is invalid for netblock %s' % ( new_prefixlen, self)) first = self.__class__('%s/%s' % (self.network_address, self._prefixlen + prefixlen_diff)) yield first current = first while True: broadcast = current.broadcast_address if broadcast == self.broadcast_address: return new_addr = self._address_class(int(broadcast) + 1) current = self.__class__('%s/%s' % (new_addr, new_prefixlen)) yield current def supernet(self, prefixlen_diff=1, new_prefix=None): """The supernet containing the current network. Args: prefixlen_diff: An integer, the amount the prefix length of the network should be decreased by. For example, given a /24 network and a prefixlen_diff of 3, a supernet with a /21 netmask is returned. Returns: An IPv4 network object. Raises: ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have a negative prefix length. OR If prefixlen_diff and new_prefix are both set or new_prefix is a larger number than the current prefix (larger number means a smaller network) """ if self._prefixlen == 0: return self if new_prefix is not None: if new_prefix > self._prefixlen: raise ValueError('new prefix must be shorter') if prefixlen_diff != 1: raise ValueError('cannot set prefixlen_diff and new_prefix') prefixlen_diff = self._prefixlen - new_prefix if self.prefixlen - prefixlen_diff < 0: raise ValueError( 'current prefixlen is %d, cannot have a prefixlen_diff of %d' % (self.prefixlen, prefixlen_diff)) # TODO (pmoody): optimize this. t = self.__class__('%s/%d' % (self.network_address, self.prefixlen - prefixlen_diff), strict=False) return t.__class__('%s/%d' % (t.network_address, t.prefixlen)) @property def is_multicast(self): """Test if the address is reserved for multicast use. Returns: A boolean, True if the address is a multicast address. See RFC 2373 2.7 for details. """ return (self.network_address.is_multicast and self.broadcast_address.is_multicast) @property def is_reserved(self): """Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within one of the reserved IPv6 Network ranges. """ return (self.network_address.is_reserved and self.broadcast_address.is_reserved) @property def is_link_local(self): """Test if the address is reserved for link-local. Returns: A boolean, True if the address is reserved per RFC 4291. """ return (self.network_address.is_link_local and self.broadcast_address.is_link_local) @property def is_private(self): """Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per iana-ipv4-special-registry or iana-ipv6-special-registry. """ return (self.network_address.is_private and self.broadcast_address.is_private) @property def is_global(self): """Test if this address is allocated for public networks. Returns: A boolean, True if the address is not reserved per iana-ipv4-special-registry or iana-ipv6-special-registry. """ return not self.is_private @property def is_unspecified(self): """Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in RFC 2373 2.5.2. """ return (self.network_address.is_unspecified and self.broadcast_address.is_unspecified) @property def is_loopback(self): """Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback address as defined in RFC 2373 2.5.3. """ return (self.network_address.is_loopback and self.broadcast_address.is_loopback) class _BaseV4(object): """Base IPv4 object. The following methods are used by IPv4 objects in both single IP addresses and networks. """ # Equivalent to 255.255.255.255 or 32 bits of 1's. _ALL_ONES = (2**IPV4LENGTH) - 1 _DECIMAL_DIGITS = frozenset('0123456789') # the valid octets for host and netmasks. only useful for IPv4. _valid_mask_octets = frozenset((255, 254, 252, 248, 240, 224, 192, 128, 0)) def __init__(self, address): self._version = 4 self._max_prefixlen = IPV4LENGTH def _explode_shorthand_ip_string(self): return str(self) def _ip_int_from_string(self, ip_str): """Turn the given IP string into an integer for comparison. Args: ip_str: A string, the IP ip_str. Returns: The IP ip_str as an integer. Raises: AddressValueError: if ip_str isn't a valid IPv4 Address. """ if not ip_str: raise AddressValueError('Address cannot be empty') octets = ip_str.split('.') if len(octets) != 4: raise AddressValueError("Expected 4 octets in %r" % ip_str) try: return _int_from_bytes(map(self._parse_octet, octets), 'big') except ValueError as exc: raise AddressValueError("%s in %r" % (exc, ip_str)) def _parse_octet(self, octet_str): """Convert a decimal octet into an integer. Args: octet_str: A string, the number to parse. Returns: The octet as an integer. Raises: ValueError: if the octet isn't strictly a decimal from [0..255]. """ if not octet_str: raise ValueError("Empty octet not permitted") # Whitelist the characters, since int() allows a lot of bizarre stuff. if not self._DECIMAL_DIGITS.issuperset(octet_str): msg = "Only decimal digits permitted in %r" raise ValueError(msg % octet_str) # We do the length check second, since the invalid character error # is likely to be more informative for the user if len(octet_str) > 3: msg = "At most 3 characters permitted in %r" raise ValueError(msg % octet_str) # Convert to integer (we know digits are legal) octet_int = int(octet_str, 10) # Any octets that look like they *might* be written in octal, # and which don't look exactly the same in both octal and # decimal are rejected as ambiguous if octet_int > 7 and octet_str[0] == '0': msg = "Ambiguous (octal/decimal) value in %r not permitted" raise ValueError(msg % octet_str) if octet_int > 255: raise ValueError("Octet %d (> 255) not permitted" % octet_int) return octet_int def _string_from_ip_int(self, ip_int): """Turns a 32-bit integer into dotted decimal notation. Args: ip_int: An integer, the IP address. Returns: The IP address as a string in dotted decimal notation. """ return '.'.join(map(str, _int_to_bytes(ip_int, 4, 'big'))) def _is_valid_netmask(self, netmask): """Verify that the netmask is valid. Args: netmask: A string, either a prefix or dotted decimal netmask. Returns: A boolean, True if the prefix represents a valid IPv4 netmask. """ mask = netmask.split('.') if len(mask) == 4: try: for x in mask: if int(x) not in self._valid_mask_octets: return False except ValueError: # Found something that isn't an integer or isn't valid return False for idx, y in enumerate(mask): if idx > 0 and y > mask[idx - 1]: return False return True try: netmask = int(netmask) except ValueError: return False return 0 <= netmask <= self._max_prefixlen def _is_hostmask(self, ip_str): """Test if the IP string is a hostmask (rather than a netmask). Args: ip_str: A string, the potential hostmask. Returns: A boolean, True if the IP string is a hostmask. """ bits = ip_str.split('.') try: parts = [x for x in map(int, bits) if x in self._valid_mask_octets] except ValueError: return False if len(parts) != len(bits): return False if parts[0] < parts[-1]: return True return False def _reverse_pointer(self): """Return the reverse DNS pointer name for the IPv4 address. This implements the method described in RFC1035 3.5. """ reverse_octets = str(self).split('.')[::-1] return '.'.join(reverse_octets) + '.in-addr.arpa' @property def max_prefixlen(self): return self._max_prefixlen @property def version(self): return self._version class IPv4Address(_BaseV4, _BaseAddress): """Represent and manipulate single IPv4 Addresses.""" def __init__(self, address): """ Args: address: A string or integer representing the IP Additionally, an integer can be passed, so IPv4Address('192.0.2.1') == IPv4Address(3221225985). or, more generally IPv4Address(int(IPv4Address('192.0.2.1'))) == IPv4Address('192.0.2.1') Raises: AddressValueError: If ipaddress isn't a valid IPv4 address. """ _BaseAddress.__init__(self, address) _BaseV4.__init__(self, address) # Efficient constructor from integer. if isinstance(address, int): self._check_int_address(address) self._ip = address return # Constructing from a packed address if isinstance(address, bytes): self._check_packed_address(address, 4) self._ip = _int_from_bytes(address, 'big') return # Assume input argument to be string or any object representation # which converts into a formatted IP string. addr_str = str(address) self._ip = self._ip_int_from_string(addr_str) @property def packed(self): """The binary representation of this address.""" return v4_int_to_packed(self._ip) @property def is_reserved(self): """Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within the reserved IPv4 Network range. """ reserved_network = IPv4Network('240.0.0.0/4') return self in reserved_network @property def is_private(self): """Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per iana-ipv4-special-registry. """ return (self in IPv4Network('0.0.0.0/8') or self in IPv4Network('10.0.0.0/8') or self in IPv4Network('127.0.0.0/8') or self in IPv4Network('169.254.0.0/16') or self in IPv4Network('172.16.0.0/12') or self in IPv4Network('192.0.0.0/29') or self in IPv4Network('192.0.0.170/31') or self in IPv4Network('192.0.2.0/24') or self in IPv4Network('192.168.0.0/16') or self in IPv4Network('198.18.0.0/15') or self in IPv4Network('198.51.100.0/24') or self in IPv4Network('203.0.113.0/24') or self in IPv4Network('240.0.0.0/4') or self in IPv4Network('255.255.255.255/32')) @property def is_multicast(self): """Test if the address is reserved for multicast use. Returns: A boolean, True if the address is multicast. See RFC 3171 for details. """ multicast_network = IPv4Network('224.0.0.0/4') return self in multicast_network @property def is_unspecified(self): """Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in RFC 5735 3. """ unspecified_address = IPv4Address('0.0.0.0') return self == unspecified_address @property def is_loopback(self): """Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback per RFC 3330. """ loopback_network = IPv4Network('127.0.0.0/8') return self in loopback_network @property def is_link_local(self): """Test if the address is reserved for link-local. Returns: A boolean, True if the address is link-local per RFC 3927. """ linklocal_network = IPv4Network('169.254.0.0/16') return self in linklocal_network class IPv4Interface(IPv4Address): def __init__(self, address): if isinstance(address, (bytes, int)): IPv4Address.__init__(self, address) self.network = IPv4Network(self._ip) self._prefixlen = self._max_prefixlen return addr = _split_optional_netmask(address) IPv4Address.__init__(self, addr[0]) self.network = IPv4Network(address, strict=False) self._prefixlen = self.network._prefixlen self.netmask = self.network.netmask self.hostmask = self.network.hostmask def __str__(self): return '%s/%d' % (self._string_from_ip_int(self._ip), self.network.prefixlen) def __eq__(self, other): address_equal = IPv4Address.__eq__(self, other) if not address_equal or address_equal is NotImplemented: return address_equal try: return self.network == other.network except AttributeError: # An interface with an associated network is NOT the # same as an unassociated address. That's why the hash # takes the extra info into account. return False def __lt__(self, other): address_less = IPv4Address.__lt__(self, other) if address_less is NotImplemented: return NotImplemented try: return self.network < other.network except AttributeError: # We *do* allow addresses and interfaces to be sorted. The # unassociated address is considered less than all interfaces. return False def __hash__(self): return self._ip ^ self._prefixlen ^ int(self.network.network_address) @property def ip(self): return IPv4Address(self._ip) @property def with_prefixlen(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self._prefixlen) @property def with_netmask(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self.netmask) @property def with_hostmask(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self.hostmask) class IPv4Network(_BaseV4, _BaseNetwork): """This class represents and manipulates 32-bit IPv4 network + addresses.. Attributes: [examples for IPv4Network('192.0.2.0/27')] .network_address: IPv4Address('192.0.2.0') .hostmask: IPv4Address('0.0.0.31') .broadcast_address: IPv4Address('192.0.2.32') .netmask: IPv4Address('255.255.255.224') .prefixlen: 27 """ # Class to use when creating address objects _address_class = IPv4Address def __init__(self, address, strict=True): """Instantiate a new IPv4 network object. Args: address: A string or integer representing the IP [& network]. '192.0.2.0/24' '192.0.2.0/255.255.255.0' '192.0.0.2/0.0.0.255' are all functionally the same in IPv4. Similarly, '192.0.2.1' '192.0.2.1/255.255.255.255' '192.0.2.1/32' are also functionally equivalent. That is to say, failing to provide a subnetmask will create an object with a mask of /32. If the mask (portion after the / in the argument) is given in dotted quad form, it is treated as a netmask if it starts with a non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it starts with a zero field (e.g. 0.255.255.255 == /8), with the single exception of an all-zero mask which is treated as a netmask == /0. If no mask is given, a default of /32 is used. Additionally, an integer can be passed, so IPv4Network('192.0.2.1') == IPv4Network(3221225985) or, more generally IPv4Interface(int(IPv4Interface('192.0.2.1'))) == IPv4Interface('192.0.2.1') Raises: AddressValueError: If ipaddress isn't a valid IPv4 address. NetmaskValueError: If the netmask isn't valid for an IPv4 address. ValueError: If strict is True and a network address is not supplied. """ _BaseV4.__init__(self, address) _BaseNetwork.__init__(self, address) # Constructing from a packed address if isinstance(address, bytes): self.network_address = IPv4Address(address) self._prefixlen = self._max_prefixlen self.netmask = IPv4Address(self._ALL_ONES) #fixme: address/network test here return # Efficient constructor from integer. if isinstance(address, int): self.network_address = IPv4Address(address) self._prefixlen = self._max_prefixlen self.netmask = IPv4Address(self._ALL_ONES) #fixme: address/network test here. return # Assume input argument to be string or any object representation # which converts into a formatted IP prefix string. addr = _split_optional_netmask(address) self.network_address = IPv4Address(self._ip_int_from_string(addr[0])) if len(addr) == 2: try: # Check for a netmask in prefix length form self._prefixlen = self._prefix_from_prefix_string(addr[1]) except NetmaskValueError: # Check for a netmask or hostmask in dotted-quad form. # This may raise NetmaskValueError. self._prefixlen = self._prefix_from_ip_string(addr[1]) else: self._prefixlen = self._max_prefixlen self.netmask = IPv4Address(self._ip_int_from_prefix(self._prefixlen)) if strict: if (IPv4Address(int(self.network_address) & int(self.netmask)) != self.network_address): raise ValueError('%s has host bits set' % self) self.network_address = IPv4Address(int(self.network_address) & int(self.netmask)) if self._prefixlen == (self._max_prefixlen - 1): self.hosts = self.__iter__ @property def is_global(self): """Test if this address is allocated for public networks. Returns: A boolean, True if the address is not reserved per iana-ipv4-special-registry. """ return (not (self.network_address in IPv4Network('100.64.0.0/10') and self.broadcast_address in IPv4Network('100.64.0.0/10')) and not self.is_private) class _BaseV6(object): """Base IPv6 object. The following methods are used by IPv6 objects in both single IP addresses and networks. """ _ALL_ONES = (2**IPV6LENGTH) - 1 _HEXTET_COUNT = 8 _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef') def __init__(self, address): self._version = 6 self._max_prefixlen = IPV6LENGTH def _ip_int_from_string(self, ip_str): """Turn an IPv6 ip_str into an integer. Args: ip_str: A string, the IPv6 ip_str. Returns: An int, the IPv6 address Raises: AddressValueError: if ip_str isn't a valid IPv6 Address. """ if not ip_str: raise AddressValueError('Address cannot be empty') parts = ip_str.split(':') # An IPv6 address needs at least 2 colons (3 parts). _min_parts = 3 if len(parts) < _min_parts: msg = "At least %d parts expected in %r" % (_min_parts, ip_str) raise AddressValueError(msg) # If the address has an IPv4-style suffix, convert it to hexadecimal. if '.' in parts[-1]: try: ipv4_int = IPv4Address(parts.pop())._ip except AddressValueError as exc: raise AddressValueError("%s in %r" % (exc, ip_str)) parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF)) parts.append('%x' % (ipv4_int & 0xFFFF)) # An IPv6 address can't have more than 8 colons (9 parts). # The extra colon comes from using the "::" notation for a single # leading or trailing zero part. _max_parts = self._HEXTET_COUNT + 1 if len(parts) > _max_parts: msg = "At most %d colons permitted in %r" % (_max_parts-1, ip_str) raise AddressValueError(msg) # Disregarding the endpoints, find '::' with nothing in between. # This indicates that a run of zeroes has been skipped. skip_index = None for i in range(1, len(parts) - 1): if not parts[i]: if skip_index is not None: # Can't have more than one '::' msg = "At most one '::' permitted in %r" % ip_str raise AddressValueError(msg) skip_index = i # parts_hi is the number of parts to copy from above/before the '::' # parts_lo is the number of parts to copy from below/after the '::' if skip_index is not None: # If we found a '::', then check if it also covers the endpoints. parts_hi = skip_index parts_lo = len(parts) - skip_index - 1 if not parts[0]: parts_hi -= 1 if parts_hi: msg = "Leading ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # ^: requires ^:: if not parts[-1]: parts_lo -= 1 if parts_lo: msg = "Trailing ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # :$ requires ::$ parts_skipped = self._HEXTET_COUNT - (parts_hi + parts_lo) if parts_skipped < 1: msg = "Expected at most %d other parts with '::' in %r" raise AddressValueError(msg % (self._HEXTET_COUNT-1, ip_str)) else: # Otherwise, allocate the entire address to parts_hi. The # endpoints could still be empty, but _parse_hextet() will check # for that. if len(parts) != self._HEXTET_COUNT: msg = "Exactly %d parts expected without '::' in %r" raise AddressValueError(msg % (self._HEXTET_COUNT, ip_str)) if not parts[0]: msg = "Leading ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # ^: requires ^:: if not parts[-1]: msg = "Trailing ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # :$ requires ::$ parts_hi = len(parts) parts_lo = 0 parts_skipped = 0 try: # Now, parse the hextets into a 128-bit integer. ip_int = 0 for i in range(parts_hi): ip_int <<= 16 ip_int |= self._parse_hextet(parts[i]) ip_int <<= 16 * parts_skipped for i in range(-parts_lo, 0): ip_int <<= 16 ip_int |= self._parse_hextet(parts[i]) return ip_int except ValueError as exc: raise AddressValueError("%s in %r" % (exc, ip_str)) def _parse_hextet(self, hextet_str): """Convert an IPv6 hextet string into an integer. Args: hextet_str: A string, the number to parse. Returns: The hextet as an integer. Raises: ValueError: if the input isn't strictly a hex number from [0..FFFF]. """ # Whitelist the characters, since int() allows a lot of bizarre stuff. if not self._HEX_DIGITS.issuperset(hextet_str): raise ValueError("Only hex digits permitted in %r" % hextet_str) # We do the length check second, since the invalid character error # is likely to be more informative for the user if len(hextet_str) > 4: msg = "At most 4 characters permitted in %r" raise ValueError(msg % hextet_str) # Length check means we can skip checking the integer value return int(hextet_str, 16) def _compress_hextets(self, hextets): """Compresses a list of hextets. Compresses a list of strings, replacing the longest continuous sequence of "0" in the list with "" and adding empty strings at the beginning or at the end of the string such that subsequently calling ":".join(hextets) will produce the compressed version of the IPv6 address. Args: hextets: A list of strings, the hextets to compress. Returns: A list of strings. """ best_doublecolon_start = -1 best_doublecolon_len = 0 doublecolon_start = -1 doublecolon_len = 0 for index, hextet in enumerate(hextets): if hextet == '0': doublecolon_len += 1 if doublecolon_start == -1: # Start of a sequence of zeros. doublecolon_start = index if doublecolon_len > best_doublecolon_len: # This is the longest sequence of zeros so far. best_doublecolon_len = doublecolon_len best_doublecolon_start = doublecolon_start else: doublecolon_len = 0 doublecolon_start = -1 if best_doublecolon_len > 1: best_doublecolon_end = (best_doublecolon_start + best_doublecolon_len) # For zeros at the end of the address. if best_doublecolon_end == len(hextets): hextets += [''] hextets[best_doublecolon_start:best_doublecolon_end] = [''] # For zeros at the beginning of the address. if best_doublecolon_start == 0: hextets = [''] + hextets return hextets def _string_from_ip_int(self, ip_int=None): """Turns a 128-bit integer into hexadecimal notation. Args: ip_int: An integer, the IP address. Returns: A string, the hexadecimal representation of the address. Raises: ValueError: The address is bigger than 128 bits of all ones. """ if ip_int is None: ip_int = int(self._ip) if ip_int > self._ALL_ONES: raise ValueError('IPv6 address is too large') hex_str = '%032x' % ip_int hextets = ['%x' % int(hex_str[x:x+4], 16) for x in range(0, 32, 4)] hextets = self._compress_hextets(hextets) return ':'.join(hextets) def _explode_shorthand_ip_string(self): """Expand a shortened IPv6 address. Args: ip_str: A string, the IPv6 address. Returns: A string, the expanded IPv6 address. """ if isinstance(self, IPv6Network): ip_str = str(self.network_address) elif isinstance(self, IPv6Interface): ip_str = str(self.ip) else: ip_str = str(self) ip_int = self._ip_int_from_string(ip_str) hex_str = '%032x' % ip_int parts = [hex_str[x:x+4] for x in range(0, 32, 4)] if isinstance(self, (_BaseNetwork, IPv6Interface)): return '%s/%d' % (':'.join(parts), self._prefixlen) return ':'.join(parts) def _reverse_pointer(self): """Return the reverse DNS pointer name for the IPv6 address. This implements the method described in RFC3596 2.5. """ reverse_chars = self.exploded[::-1].replace(':', '') return '.'.join(reverse_chars) + '.ip6.arpa' @property def max_prefixlen(self): return self._max_prefixlen @property def version(self): return self._version class IPv6Address(_BaseV6, _BaseAddress): """Represent and manipulate single IPv6 Addresses.""" def __init__(self, address): """Instantiate a new IPv6 address object. Args: address: A string or integer representing the IP Additionally, an integer can be passed, so IPv6Address('2001:db8::') == IPv6Address(42540766411282592856903984951653826560) or, more generally IPv6Address(int(IPv6Address('2001:db8::'))) == IPv6Address('2001:db8::') Raises: AddressValueError: If address isn't a valid IPv6 address. """ _BaseAddress.__init__(self, address) _BaseV6.__init__(self, address) # Efficient constructor from integer. if isinstance(address, int): self._check_int_address(address) self._ip = address return # Constructing from a packed address if isinstance(address, bytes): self._check_packed_address(address, 16) self._ip = _int_from_bytes(address, 'big') return # Assume input argument to be string or any object representation # which converts into a formatted IP string. addr_str = str(address) self._ip = self._ip_int_from_string(addr_str) @property def packed(self): """The binary representation of this address.""" return v6_int_to_packed(self._ip) @property def is_multicast(self): """Test if the address is reserved for multicast use. Returns: A boolean, True if the address is a multicast address. See RFC 2373 2.7 for details. """ multicast_network = IPv6Network('ff00::/8') return self in multicast_network @property def is_reserved(self): """Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within one of the reserved IPv6 Network ranges. """ reserved_networks = [IPv6Network('::/8'), IPv6Network('100::/8'), IPv6Network('200::/7'), IPv6Network('400::/6'), IPv6Network('800::/5'), IPv6Network('1000::/4'), IPv6Network('4000::/3'), IPv6Network('6000::/3'), IPv6Network('8000::/3'), IPv6Network('A000::/3'), IPv6Network('C000::/3'), IPv6Network('E000::/4'), IPv6Network('F000::/5'), IPv6Network('F800::/6'), IPv6Network('FE00::/9')] return any(self in x for x in reserved_networks) @property def is_link_local(self): """Test if the address is reserved for link-local. Returns: A boolean, True if the address is reserved per RFC 4291. """ linklocal_network = IPv6Network('fe80::/10') return self in linklocal_network @property def is_site_local(self): """Test if the address is reserved for site-local. Note that the site-local address space has been deprecated by RFC 3879. Use is_private to test if this address is in the space of unique local addresses as defined by RFC 4193. Returns: A boolean, True if the address is reserved per RFC 3513 2.5.6. """ sitelocal_network = IPv6Network('fec0::/10') return self in sitelocal_network @property def is_private(self): """Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per iana-ipv6-special-registry. """ return (self in IPv6Network('::1/128') or self in IPv6Network('::/128') or self in IPv6Network('::ffff:0:0/96') or self in IPv6Network('100::/64') or self in IPv6Network('2001::/23') or self in IPv6Network('2001:2::/48') or self in IPv6Network('2001:db8::/32') or self in IPv6Network('2001:10::/28') or self in IPv6Network('fc00::/7') or self in IPv6Network('fe80::/10')) @property def is_global(self): """Test if this address is allocated for public networks. Returns: A boolean, true if the address is not reserved per iana-ipv6-special-registry. """ return not self.is_private @property def is_unspecified(self): """Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in RFC 2373 2.5.2. """ return self._ip == 0 @property def is_loopback(self): """Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback address as defined in RFC 2373 2.5.3. """ return self._ip == 1 @property def ipv4_mapped(self): """Return the IPv4 mapped address. Returns: If the IPv6 address is a v4 mapped address, return the IPv4 mapped address. Return None otherwise. """ if (self._ip >> 32) != 0xFFFF: return None return IPv4Address(self._ip & 0xFFFFFFFF) @property def teredo(self): """Tuple of embedded teredo IPs. Returns: Tuple of the (server, client) IPs or None if the address doesn't appear to be a teredo address (doesn't start with 2001::/32) """ if (self._ip >> 96) != 0x20010000: return None return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF), IPv4Address(~self._ip & 0xFFFFFFFF)) @property def sixtofour(self): """Return the IPv4 6to4 embedded address. Returns: The IPv4 6to4-embedded address if present or None if the address doesn't appear to contain a 6to4 embedded address. """ if (self._ip >> 112) != 0x2002: return None return IPv4Address((self._ip >> 80) & 0xFFFFFFFF) class IPv6Interface(IPv6Address): def __init__(self, address): if isinstance(address, (bytes, int)): IPv6Address.__init__(self, address) self.network = IPv6Network(self._ip) self._prefixlen = self._max_prefixlen return addr = _split_optional_netmask(address) IPv6Address.__init__(self, addr[0]) self.network = IPv6Network(address, strict=False) self.netmask = self.network.netmask self._prefixlen = self.network._prefixlen self.hostmask = self.network.hostmask def __str__(self): return '%s/%d' % (self._string_from_ip_int(self._ip), self.network.prefixlen) def __eq__(self, other): address_equal = IPv6Address.__eq__(self, other) if not address_equal or address_equal is NotImplemented: return address_equal try: return self.network == other.network except AttributeError: # An interface with an associated network is NOT the # same as an unassociated address. That's why the hash # takes the extra info into account. return False def __lt__(self, other): address_less = IPv6Address.__lt__(self, other) if address_less is NotImplemented: return NotImplemented try: return self.network < other.network except AttributeError: # We *do* allow addresses and interfaces to be sorted. The # unassociated address is considered less than all interfaces. return False def __hash__(self): return self._ip ^ self._prefixlen ^ int(self.network.network_address) @property def ip(self): return IPv6Address(self._ip) @property def with_prefixlen(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self._prefixlen) @property def with_netmask(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self.netmask) @property def with_hostmask(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self.hostmask) @property def is_unspecified(self): return self._ip == 0 and self.network.is_unspecified @property def is_loopback(self): return self._ip == 1 and self.network.is_loopback class IPv6Network(_BaseV6, _BaseNetwork): """This class represents and manipulates 128-bit IPv6 networks. Attributes: [examples for IPv6('2001:db8::1000/124')] .network_address: IPv6Address('2001:db8::1000') .hostmask: IPv6Address('::f') .broadcast_address: IPv6Address('2001:db8::100f') .netmask: IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0') .prefixlen: 124 """ # Class to use when creating address objects _address_class = IPv6Address def __init__(self, address, strict=True): """Instantiate a new IPv6 Network object. Args: address: A string or integer representing the IPv6 network or the IP and prefix/netmask. '2001:db8::/128' '2001:db8:0000:0000:0000:0000:0000:0000/128' '2001:db8::' are all functionally the same in IPv6. That is to say, failing to provide a subnetmask will create an object with a mask of /128. Additionally, an integer can be passed, so IPv6Network('2001:db8::') == IPv6Network(42540766411282592856903984951653826560) or, more generally IPv6Network(int(IPv6Network('2001:db8::'))) == IPv6Network('2001:db8::') strict: A boolean. If true, ensure that we have been passed A true network address, eg, 2001:db8::1000/124 and not an IP address on a network, eg, 2001:db8::1/124. Raises: AddressValueError: If address isn't a valid IPv6 address. NetmaskValueError: If the netmask isn't valid for an IPv6 address. ValueError: If strict was True and a network address was not supplied. """ _BaseV6.__init__(self, address) _BaseNetwork.__init__(self, address) # Efficient constructor from integer. if isinstance(address, int): self.network_address = IPv6Address(address) self._prefixlen = self._max_prefixlen self.netmask = IPv6Address(self._ALL_ONES) return # Constructing from a packed address if isinstance(address, bytes): self.network_address = IPv6Address(address) self._prefixlen = self._max_prefixlen self.netmask = IPv6Address(self._ALL_ONES) return # Assume input argument to be string or any object representation # which converts into a formatted IP prefix string. addr = _split_optional_netmask(address) self.network_address = IPv6Address(self._ip_int_from_string(addr[0])) if len(addr) == 2: # This may raise NetmaskValueError self._prefixlen = self._prefix_from_prefix_string(addr[1]) else: self._prefixlen = self._max_prefixlen self.netmask = IPv6Address(self._ip_int_from_prefix(self._prefixlen)) if strict: if (IPv6Address(int(self.network_address) & int(self.netmask)) != self.network_address): raise ValueError('%s has host bits set' % self) self.network_address = IPv6Address(int(self.network_address) & int(self.netmask)) if self._prefixlen == (self._max_prefixlen - 1): self.hosts = self.__iter__ def hosts(self): """Generate Iterator over usable hosts in a network. This is like __iter__ except it doesn't return the Subnet-Router anycast address. """ network = int(self.network_address) broadcast = int(self.broadcast_address) for x in long_range(1, broadcast - network + 1): yield self._address_class(network + x) @property def is_site_local(self): """Test if the address is reserved for site-local. Note that the site-local address space has been deprecated by RFC 3879. Use is_private to test if this address is in the space of unique local addresses as defined by RFC 4193. Returns: A boolean, True if the address is reserved per RFC 3513 2.5.6. """ return (self.network_address.is_site_local and self.broadcast_address.is_site_local)
saltstack/salt
salt/ext/ipaddress.py
_IPAddressBase._prefix_from_ip_int
python
def _prefix_from_ip_int(self, ip_int): trailing_zeroes = _count_righthand_zero_bits(ip_int, self._max_prefixlen) prefixlen = self._max_prefixlen - trailing_zeroes leading_ones = ip_int >> trailing_zeroes all_ones = (1 << prefixlen) - 1 if leading_ones != all_ones: byteslen = self._max_prefixlen // 8 details = _int_to_bytes(ip_int, byteslen, 'big') msg = 'Netmask pattern %r mixes zeroes & ones' raise ValueError(msg % details) return prefixlen
Return prefix length from the bitwise netmask. Args: ip_int: An integer, the netmask in expanded bitwise format Returns: An integer, the prefix length. Raises: ValueError: If the input intermingles zeroes & ones
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/ext/ipaddress.py#L548-L570
null
class _IPAddressBase(_TotalOrderingMixin): """The mother class.""" @property def exploded(self): """Return the longhand version of the IP address as a string.""" return self._explode_shorthand_ip_string() @property def compressed(self): """Return the shorthand version of the IP address as a string.""" return str(self) @property def reverse_pointer(self): """The name of the reverse DNS pointer for the IP address, e.g.: >>> ipaddress.ip_address("127.0.0.1").reverse_pointer '1.0.0.127.in-addr.arpa' >>> ipaddress.ip_address("2001:db8::1").reverse_pointer '1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa' """ return self._reverse_pointer() @property def version(self): msg = '%200s has no version specified' % (type(self),) raise NotImplementedError(msg) def _check_int_address(self, address): if address < 0: msg = "%d (< 0) is not permitted as an IPv%d address" raise AddressValueError(msg % (address, self._version)) if address > self._ALL_ONES: msg = "%d (>= 2**%d) is not permitted as an IPv%d address" raise AddressValueError(msg % (address, self._max_prefixlen, self._version)) def _check_packed_address(self, address, expected_len): address_len = len(address) if address_len != expected_len: msg = "%r (len %d != %d) is not permitted as an IPv%d address" raise AddressValueError(msg % (address, address_len, expected_len, self._version)) def _ip_int_from_prefix(self, prefixlen): """Turn the prefix length into a bitwise netmask Args: prefixlen: An integer, the prefix length. Returns: An integer. """ return self._ALL_ONES ^ (self._ALL_ONES >> prefixlen) def _report_invalid_netmask(self, netmask_str): msg = '%r is not a valid netmask' % netmask_str raise NetmaskValueError(msg) def _prefix_from_prefix_string(self, prefixlen_str): """Return prefix length from a numeric string Args: prefixlen_str: The string to be converted Returns: An integer, the prefix length. Raises: NetmaskValueError: If the input is not a valid netmask """ # int allows a leading +/- as well as surrounding whitespace, # so we ensure that isn't the case if not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str): self._report_invalid_netmask(prefixlen_str) try: prefixlen = int(prefixlen_str) except ValueError: self._report_invalid_netmask(prefixlen_str) if not (0 <= prefixlen <= self._max_prefixlen): self._report_invalid_netmask(prefixlen_str) return prefixlen def _prefix_from_ip_string(self, ip_str): """Turn a netmask/hostmask string into a prefix length Args: ip_str: The netmask/hostmask to be converted Returns: An integer, the prefix length. Raises: NetmaskValueError: If the input is not a valid netmask/hostmask """ # Parse the netmask/hostmask like an IP address. try: ip_int = self._ip_int_from_string(ip_str) except AddressValueError: self._report_invalid_netmask(ip_str) # Try matching a netmask (this would be /1*0*/ as a bitwise regexp). # Note that the two ambiguous cases (all-ones and all-zeroes) are # treated as netmasks. try: return self._prefix_from_ip_int(ip_int) except ValueError: pass # Invert the bits, and try matching a /0+1+/ hostmask instead. ip_int ^= self._ALL_ONES try: return self._prefix_from_ip_int(ip_int) except ValueError: self._report_invalid_netmask(ip_str)
saltstack/salt
salt/ext/ipaddress.py
_IPAddressBase._prefix_from_prefix_string
python
def _prefix_from_prefix_string(self, prefixlen_str): # int allows a leading +/- as well as surrounding whitespace, # so we ensure that isn't the case if not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str): self._report_invalid_netmask(prefixlen_str) try: prefixlen = int(prefixlen_str) except ValueError: self._report_invalid_netmask(prefixlen_str) if not (0 <= prefixlen <= self._max_prefixlen): self._report_invalid_netmask(prefixlen_str) return prefixlen
Return prefix length from a numeric string Args: prefixlen_str: The string to be converted Returns: An integer, the prefix length. Raises: NetmaskValueError: If the input is not a valid netmask
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/ext/ipaddress.py#L576-L598
null
class _IPAddressBase(_TotalOrderingMixin): """The mother class.""" @property def exploded(self): """Return the longhand version of the IP address as a string.""" return self._explode_shorthand_ip_string() @property def compressed(self): """Return the shorthand version of the IP address as a string.""" return str(self) @property def reverse_pointer(self): """The name of the reverse DNS pointer for the IP address, e.g.: >>> ipaddress.ip_address("127.0.0.1").reverse_pointer '1.0.0.127.in-addr.arpa' >>> ipaddress.ip_address("2001:db8::1").reverse_pointer '1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa' """ return self._reverse_pointer() @property def version(self): msg = '%200s has no version specified' % (type(self),) raise NotImplementedError(msg) def _check_int_address(self, address): if address < 0: msg = "%d (< 0) is not permitted as an IPv%d address" raise AddressValueError(msg % (address, self._version)) if address > self._ALL_ONES: msg = "%d (>= 2**%d) is not permitted as an IPv%d address" raise AddressValueError(msg % (address, self._max_prefixlen, self._version)) def _check_packed_address(self, address, expected_len): address_len = len(address) if address_len != expected_len: msg = "%r (len %d != %d) is not permitted as an IPv%d address" raise AddressValueError(msg % (address, address_len, expected_len, self._version)) def _ip_int_from_prefix(self, prefixlen): """Turn the prefix length into a bitwise netmask Args: prefixlen: An integer, the prefix length. Returns: An integer. """ return self._ALL_ONES ^ (self._ALL_ONES >> prefixlen) def _prefix_from_ip_int(self, ip_int): """Return prefix length from the bitwise netmask. Args: ip_int: An integer, the netmask in expanded bitwise format Returns: An integer, the prefix length. Raises: ValueError: If the input intermingles zeroes & ones """ trailing_zeroes = _count_righthand_zero_bits(ip_int, self._max_prefixlen) prefixlen = self._max_prefixlen - trailing_zeroes leading_ones = ip_int >> trailing_zeroes all_ones = (1 << prefixlen) - 1 if leading_ones != all_ones: byteslen = self._max_prefixlen // 8 details = _int_to_bytes(ip_int, byteslen, 'big') msg = 'Netmask pattern %r mixes zeroes & ones' raise ValueError(msg % details) return prefixlen def _report_invalid_netmask(self, netmask_str): msg = '%r is not a valid netmask' % netmask_str raise NetmaskValueError(msg) def _prefix_from_ip_string(self, ip_str): """Turn a netmask/hostmask string into a prefix length Args: ip_str: The netmask/hostmask to be converted Returns: An integer, the prefix length. Raises: NetmaskValueError: If the input is not a valid netmask/hostmask """ # Parse the netmask/hostmask like an IP address. try: ip_int = self._ip_int_from_string(ip_str) except AddressValueError: self._report_invalid_netmask(ip_str) # Try matching a netmask (this would be /1*0*/ as a bitwise regexp). # Note that the two ambiguous cases (all-ones and all-zeroes) are # treated as netmasks. try: return self._prefix_from_ip_int(ip_int) except ValueError: pass # Invert the bits, and try matching a /0+1+/ hostmask instead. ip_int ^= self._ALL_ONES try: return self._prefix_from_ip_int(ip_int) except ValueError: self._report_invalid_netmask(ip_str)
saltstack/salt
salt/ext/ipaddress.py
_IPAddressBase._prefix_from_ip_string
python
def _prefix_from_ip_string(self, ip_str): # Parse the netmask/hostmask like an IP address. try: ip_int = self._ip_int_from_string(ip_str) except AddressValueError: self._report_invalid_netmask(ip_str) # Try matching a netmask (this would be /1*0*/ as a bitwise regexp). # Note that the two ambiguous cases (all-ones and all-zeroes) are # treated as netmasks. try: return self._prefix_from_ip_int(ip_int) except ValueError: pass # Invert the bits, and try matching a /0+1+/ hostmask instead. ip_int ^= self._ALL_ONES try: return self._prefix_from_ip_int(ip_int) except ValueError: self._report_invalid_netmask(ip_str)
Turn a netmask/hostmask string into a prefix length Args: ip_str: The netmask/hostmask to be converted Returns: An integer, the prefix length. Raises: NetmaskValueError: If the input is not a valid netmask/hostmask
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/ext/ipaddress.py#L600-L631
null
class _IPAddressBase(_TotalOrderingMixin): """The mother class.""" @property def exploded(self): """Return the longhand version of the IP address as a string.""" return self._explode_shorthand_ip_string() @property def compressed(self): """Return the shorthand version of the IP address as a string.""" return str(self) @property def reverse_pointer(self): """The name of the reverse DNS pointer for the IP address, e.g.: >>> ipaddress.ip_address("127.0.0.1").reverse_pointer '1.0.0.127.in-addr.arpa' >>> ipaddress.ip_address("2001:db8::1").reverse_pointer '1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa' """ return self._reverse_pointer() @property def version(self): msg = '%200s has no version specified' % (type(self),) raise NotImplementedError(msg) def _check_int_address(self, address): if address < 0: msg = "%d (< 0) is not permitted as an IPv%d address" raise AddressValueError(msg % (address, self._version)) if address > self._ALL_ONES: msg = "%d (>= 2**%d) is not permitted as an IPv%d address" raise AddressValueError(msg % (address, self._max_prefixlen, self._version)) def _check_packed_address(self, address, expected_len): address_len = len(address) if address_len != expected_len: msg = "%r (len %d != %d) is not permitted as an IPv%d address" raise AddressValueError(msg % (address, address_len, expected_len, self._version)) def _ip_int_from_prefix(self, prefixlen): """Turn the prefix length into a bitwise netmask Args: prefixlen: An integer, the prefix length. Returns: An integer. """ return self._ALL_ONES ^ (self._ALL_ONES >> prefixlen) def _prefix_from_ip_int(self, ip_int): """Return prefix length from the bitwise netmask. Args: ip_int: An integer, the netmask in expanded bitwise format Returns: An integer, the prefix length. Raises: ValueError: If the input intermingles zeroes & ones """ trailing_zeroes = _count_righthand_zero_bits(ip_int, self._max_prefixlen) prefixlen = self._max_prefixlen - trailing_zeroes leading_ones = ip_int >> trailing_zeroes all_ones = (1 << prefixlen) - 1 if leading_ones != all_ones: byteslen = self._max_prefixlen // 8 details = _int_to_bytes(ip_int, byteslen, 'big') msg = 'Netmask pattern %r mixes zeroes & ones' raise ValueError(msg % details) return prefixlen def _report_invalid_netmask(self, netmask_str): msg = '%r is not a valid netmask' % netmask_str raise NetmaskValueError(msg) def _prefix_from_prefix_string(self, prefixlen_str): """Return prefix length from a numeric string Args: prefixlen_str: The string to be converted Returns: An integer, the prefix length. Raises: NetmaskValueError: If the input is not a valid netmask """ # int allows a leading +/- as well as surrounding whitespace, # so we ensure that isn't the case if not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str): self._report_invalid_netmask(prefixlen_str) try: prefixlen = int(prefixlen_str) except ValueError: self._report_invalid_netmask(prefixlen_str) if not (0 <= prefixlen <= self._max_prefixlen): self._report_invalid_netmask(prefixlen_str) return prefixlen
saltstack/salt
salt/ext/ipaddress.py
_BaseNetwork.subnets
python
def subnets(self, prefixlen_diff=1, new_prefix=None): if self._prefixlen == self._max_prefixlen: yield self return if new_prefix is not None: if new_prefix < self._prefixlen: raise ValueError('new prefix must be longer') if prefixlen_diff != 1: raise ValueError('cannot set prefixlen_diff and new_prefix') prefixlen_diff = new_prefix - self._prefixlen if prefixlen_diff < 0: raise ValueError('prefix length diff must be > 0') new_prefixlen = self._prefixlen + prefixlen_diff if new_prefixlen > self._max_prefixlen: raise ValueError( 'prefix length diff %d is invalid for netblock %s' % ( new_prefixlen, self)) first = self.__class__('%s/%s' % (self.network_address, self._prefixlen + prefixlen_diff)) yield first current = first while True: broadcast = current.broadcast_address if broadcast == self.broadcast_address: return new_addr = self._address_class(int(broadcast) + 1) current = self.__class__('%s/%s' % (new_addr, new_prefixlen)) yield current
The subnets which join to make the current subnet. In the case that self contains only one IP (self._prefixlen == 32 for IPv4 or self._prefixlen == 128 for IPv6), yield an iterator with just ourself. Args: prefixlen_diff: An integer, the amount the prefix length should be increased by. This should not be set if new_prefix is also set. new_prefix: The desired new prefix length. This must be a larger number (smaller prefix) than the existing prefix. This should not be set if prefixlen_diff is also set. Returns: An iterator of IPv(4|6) objects. Raises: ValueError: The prefixlen_diff is too small or too large. OR prefixlen_diff and new_prefix are both set or new_prefix is a smaller number than the current prefix (smaller number means a larger network)
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/ext/ipaddress.py#L967-L1027
null
class _BaseNetwork(_IPAddressBase): """A generic IP network object. This IP class contains the version independent methods which are used by networks. """ def __init__(self, address): self._cache = {} def __repr__(self): return '%s(%r)' % (self.__class__.__name__, str(self)) def __str__(self): return '%s/%d' % (self.network_address, self.prefixlen) def hosts(self): """Generate Iterator over usable hosts in a network. This is like __iter__ except it doesn't return the network or broadcast addresses. """ network = int(self.network_address) broadcast = int(self.broadcast_address) for x in long_range(network + 1, broadcast): yield self._address_class(x) def __iter__(self): network = int(self.network_address) broadcast = int(self.broadcast_address) for x in long_range(network, broadcast + 1): yield self._address_class(x) def __getitem__(self, n): network = int(self.network_address) broadcast = int(self.broadcast_address) if n >= 0: if network + n > broadcast: raise IndexError return self._address_class(network + n) else: n += 1 if broadcast + n < network: raise IndexError return self._address_class(broadcast + n) def __lt__(self, other): if self._version != other._version: raise TypeError('%s and %s are not of the same version' % ( self, other)) if not isinstance(other, _BaseNetwork): raise TypeError('%s and %s are not of the same type' % ( self, other)) if self.network_address != other.network_address: return self.network_address < other.network_address if self.netmask != other.netmask: return self.netmask < other.netmask return False def __eq__(self, other): try: return (self._version == other._version and self.network_address == other.network_address and int(self.netmask) == int(other.netmask)) except AttributeError: return NotImplemented def __hash__(self): return hash(int(self.network_address) ^ int(self.netmask)) def __contains__(self, other): # always false if one is v4 and the other is v6. if self._version != other._version: return False # dealing with another network. if isinstance(other, _BaseNetwork): return False # dealing with another address else: # address return (int(self.network_address) <= int(other._ip) <= int(self.broadcast_address)) def overlaps(self, other): """Tell if self is partly contained in other.""" return self.network_address in other or ( self.broadcast_address in other or ( other.network_address in self or ( other.broadcast_address in self))) @property def broadcast_address(self): x = self._cache.get('broadcast_address') if x is None: x = self._address_class(int(self.network_address) | int(self.hostmask)) self._cache['broadcast_address'] = x return x @property def hostmask(self): x = self._cache.get('hostmask') if x is None: x = self._address_class(int(self.netmask) ^ self._ALL_ONES) self._cache['hostmask'] = x return x @property def with_prefixlen(self): return '%s/%d' % (self.network_address, self._prefixlen) @property def with_netmask(self): return '%s/%s' % (self.network_address, self.netmask) @property def with_hostmask(self): return '%s/%s' % (self.network_address, self.hostmask) @property def num_addresses(self): """Number of hosts in the current subnet.""" return int(self.broadcast_address) - int(self.network_address) + 1 @property def _address_class(self): # Returning bare address objects (rather than interfaces) allows for # more consistent behaviour across the network address, broadcast # address and individual host addresses. msg = '%200s has no associated address class' % (type(self),) raise NotImplementedError(msg) @property def prefixlen(self): return self._prefixlen def address_exclude(self, other): """Remove an address from a larger block. For example: addr1 = ip_network('192.0.2.0/28') addr2 = ip_network('192.0.2.1/32') addr1.address_exclude(addr2) = [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'), IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')] or IPv6: addr1 = ip_network('2001:db8::1/32') addr2 = ip_network('2001:db8::1/128') addr1.address_exclude(addr2) = [ip_network('2001:db8::1/128'), ip_network('2001:db8::2/127'), ip_network('2001:db8::4/126'), ip_network('2001:db8::8/125'), ... ip_network('2001:db8:8000::/33')] Args: other: An IPv4Network or IPv6Network object of the same type. Returns: An iterator of the IPv(4|6)Network objects which is self minus other. Raises: TypeError: If self and other are of differing address versions, or if other is not a network object. ValueError: If other is not completely contained by self. """ if not self._version == other._version: raise TypeError("%s and %s are not of the same version" % ( self, other)) if not isinstance(other, _BaseNetwork): raise TypeError("%s is not a network object" % other) if not (other.network_address >= self.network_address and other.broadcast_address <= self.broadcast_address): raise ValueError('%s not contained in %s' % (other, self)) if other == self: raise StopIteration # Make sure we're comparing the network of other. other = other.__class__('%s/%s' % (other.network_address, other.prefixlen)) s1, s2 = self.subnets() while s1 != other and s2 != other: if (other.network_address >= s1.network_address and other.broadcast_address <= s1.broadcast_address): yield s2 s1, s2 = s1.subnets() elif (other.network_address >= s2.network_address and other.broadcast_address <= s2.broadcast_address): yield s1 s1, s2 = s2.subnets() else: # If we got here, there's a bug somewhere. raise AssertionError('Error performing exclusion: ' 's1: %s s2: %s other: %s' % (s1, s2, other)) if s1 == other: yield s2 elif s2 == other: yield s1 else: # If we got here, there's a bug somewhere. raise AssertionError('Error performing exclusion: ' 's1: %s s2: %s other: %s' % (s1, s2, other)) def compare_networks(self, other): """Compare two IP objects. This is only concerned about the comparison of the integer representation of the network addresses. This means that the host bits aren't considered at all in this method. If you want to compare host bits, you can easily enough do a 'HostA._ip < HostB._ip' Args: other: An IP object. Returns: If the IP versions of self and other are the same, returns: -1 if self < other: eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25') IPv6Network('2001:db8::1000/124') < IPv6Network('2001:db8::2000/124') 0 if self == other eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24') IPv6Network('2001:db8::1000/124') == IPv6Network('2001:db8::1000/124') 1 if self > other eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25') IPv6Network('2001:db8::2000/124') > IPv6Network('2001:db8::1000/124') Raises: TypeError if the IP versions are different. """ # does this need to raise a ValueError? if self._version != other._version: raise TypeError('%s and %s are not of the same type' % ( self, other)) # self._version == other._version below here: if self.network_address < other.network_address: return -1 if self.network_address > other.network_address: return 1 # self.network_address == other.network_address below here: if self.netmask < other.netmask: return -1 if self.netmask > other.netmask: return 1 return 0 def _get_networks_key(self): """Network-only key function. Returns an object that identifies this address' network and netmask. This function is a suitable "key" argument for sorted() and list.sort(). """ return (self._version, self.network_address, self.netmask) def supernet(self, prefixlen_diff=1, new_prefix=None): """The supernet containing the current network. Args: prefixlen_diff: An integer, the amount the prefix length of the network should be decreased by. For example, given a /24 network and a prefixlen_diff of 3, a supernet with a /21 netmask is returned. Returns: An IPv4 network object. Raises: ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have a negative prefix length. OR If prefixlen_diff and new_prefix are both set or new_prefix is a larger number than the current prefix (larger number means a smaller network) """ if self._prefixlen == 0: return self if new_prefix is not None: if new_prefix > self._prefixlen: raise ValueError('new prefix must be shorter') if prefixlen_diff != 1: raise ValueError('cannot set prefixlen_diff and new_prefix') prefixlen_diff = self._prefixlen - new_prefix if self.prefixlen - prefixlen_diff < 0: raise ValueError( 'current prefixlen is %d, cannot have a prefixlen_diff of %d' % (self.prefixlen, prefixlen_diff)) # TODO (pmoody): optimize this. t = self.__class__('%s/%d' % (self.network_address, self.prefixlen - prefixlen_diff), strict=False) return t.__class__('%s/%d' % (t.network_address, t.prefixlen)) @property def is_multicast(self): """Test if the address is reserved for multicast use. Returns: A boolean, True if the address is a multicast address. See RFC 2373 2.7 for details. """ return (self.network_address.is_multicast and self.broadcast_address.is_multicast) @property def is_reserved(self): """Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within one of the reserved IPv6 Network ranges. """ return (self.network_address.is_reserved and self.broadcast_address.is_reserved) @property def is_link_local(self): """Test if the address is reserved for link-local. Returns: A boolean, True if the address is reserved per RFC 4291. """ return (self.network_address.is_link_local and self.broadcast_address.is_link_local) @property def is_private(self): """Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per iana-ipv4-special-registry or iana-ipv6-special-registry. """ return (self.network_address.is_private and self.broadcast_address.is_private) @property def is_global(self): """Test if this address is allocated for public networks. Returns: A boolean, True if the address is not reserved per iana-ipv4-special-registry or iana-ipv6-special-registry. """ return not self.is_private @property def is_unspecified(self): """Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in RFC 2373 2.5.2. """ return (self.network_address.is_unspecified and self.broadcast_address.is_unspecified) @property def is_loopback(self): """Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback address as defined in RFC 2373 2.5.3. """ return (self.network_address.is_loopback and self.broadcast_address.is_loopback)
saltstack/salt
salt/ext/ipaddress.py
_BaseNetwork.supernet
python
def supernet(self, prefixlen_diff=1, new_prefix=None): if self._prefixlen == 0: return self if new_prefix is not None: if new_prefix > self._prefixlen: raise ValueError('new prefix must be shorter') if prefixlen_diff != 1: raise ValueError('cannot set prefixlen_diff and new_prefix') prefixlen_diff = self._prefixlen - new_prefix if self.prefixlen - prefixlen_diff < 0: raise ValueError( 'current prefixlen is %d, cannot have a prefixlen_diff of %d' % (self.prefixlen, prefixlen_diff)) # TODO (pmoody): optimize this. t = self.__class__('%s/%d' % (self.network_address, self.prefixlen - prefixlen_diff), strict=False) return t.__class__('%s/%d' % (t.network_address, t.prefixlen))
The supernet containing the current network. Args: prefixlen_diff: An integer, the amount the prefix length of the network should be decreased by. For example, given a /24 network and a prefixlen_diff of 3, a supernet with a /21 netmask is returned. Returns: An IPv4 network object. Raises: ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have a negative prefix length. OR If prefixlen_diff and new_prefix are both set or new_prefix is a larger number than the current prefix (larger number means a smaller network)
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/ext/ipaddress.py#L1029-L1068
null
class _BaseNetwork(_IPAddressBase): """A generic IP network object. This IP class contains the version independent methods which are used by networks. """ def __init__(self, address): self._cache = {} def __repr__(self): return '%s(%r)' % (self.__class__.__name__, str(self)) def __str__(self): return '%s/%d' % (self.network_address, self.prefixlen) def hosts(self): """Generate Iterator over usable hosts in a network. This is like __iter__ except it doesn't return the network or broadcast addresses. """ network = int(self.network_address) broadcast = int(self.broadcast_address) for x in long_range(network + 1, broadcast): yield self._address_class(x) def __iter__(self): network = int(self.network_address) broadcast = int(self.broadcast_address) for x in long_range(network, broadcast + 1): yield self._address_class(x) def __getitem__(self, n): network = int(self.network_address) broadcast = int(self.broadcast_address) if n >= 0: if network + n > broadcast: raise IndexError return self._address_class(network + n) else: n += 1 if broadcast + n < network: raise IndexError return self._address_class(broadcast + n) def __lt__(self, other): if self._version != other._version: raise TypeError('%s and %s are not of the same version' % ( self, other)) if not isinstance(other, _BaseNetwork): raise TypeError('%s and %s are not of the same type' % ( self, other)) if self.network_address != other.network_address: return self.network_address < other.network_address if self.netmask != other.netmask: return self.netmask < other.netmask return False def __eq__(self, other): try: return (self._version == other._version and self.network_address == other.network_address and int(self.netmask) == int(other.netmask)) except AttributeError: return NotImplemented def __hash__(self): return hash(int(self.network_address) ^ int(self.netmask)) def __contains__(self, other): # always false if one is v4 and the other is v6. if self._version != other._version: return False # dealing with another network. if isinstance(other, _BaseNetwork): return False # dealing with another address else: # address return (int(self.network_address) <= int(other._ip) <= int(self.broadcast_address)) def overlaps(self, other): """Tell if self is partly contained in other.""" return self.network_address in other or ( self.broadcast_address in other or ( other.network_address in self or ( other.broadcast_address in self))) @property def broadcast_address(self): x = self._cache.get('broadcast_address') if x is None: x = self._address_class(int(self.network_address) | int(self.hostmask)) self._cache['broadcast_address'] = x return x @property def hostmask(self): x = self._cache.get('hostmask') if x is None: x = self._address_class(int(self.netmask) ^ self._ALL_ONES) self._cache['hostmask'] = x return x @property def with_prefixlen(self): return '%s/%d' % (self.network_address, self._prefixlen) @property def with_netmask(self): return '%s/%s' % (self.network_address, self.netmask) @property def with_hostmask(self): return '%s/%s' % (self.network_address, self.hostmask) @property def num_addresses(self): """Number of hosts in the current subnet.""" return int(self.broadcast_address) - int(self.network_address) + 1 @property def _address_class(self): # Returning bare address objects (rather than interfaces) allows for # more consistent behaviour across the network address, broadcast # address and individual host addresses. msg = '%200s has no associated address class' % (type(self),) raise NotImplementedError(msg) @property def prefixlen(self): return self._prefixlen def address_exclude(self, other): """Remove an address from a larger block. For example: addr1 = ip_network('192.0.2.0/28') addr2 = ip_network('192.0.2.1/32') addr1.address_exclude(addr2) = [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'), IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')] or IPv6: addr1 = ip_network('2001:db8::1/32') addr2 = ip_network('2001:db8::1/128') addr1.address_exclude(addr2) = [ip_network('2001:db8::1/128'), ip_network('2001:db8::2/127'), ip_network('2001:db8::4/126'), ip_network('2001:db8::8/125'), ... ip_network('2001:db8:8000::/33')] Args: other: An IPv4Network or IPv6Network object of the same type. Returns: An iterator of the IPv(4|6)Network objects which is self minus other. Raises: TypeError: If self and other are of differing address versions, or if other is not a network object. ValueError: If other is not completely contained by self. """ if not self._version == other._version: raise TypeError("%s and %s are not of the same version" % ( self, other)) if not isinstance(other, _BaseNetwork): raise TypeError("%s is not a network object" % other) if not (other.network_address >= self.network_address and other.broadcast_address <= self.broadcast_address): raise ValueError('%s not contained in %s' % (other, self)) if other == self: raise StopIteration # Make sure we're comparing the network of other. other = other.__class__('%s/%s' % (other.network_address, other.prefixlen)) s1, s2 = self.subnets() while s1 != other and s2 != other: if (other.network_address >= s1.network_address and other.broadcast_address <= s1.broadcast_address): yield s2 s1, s2 = s1.subnets() elif (other.network_address >= s2.network_address and other.broadcast_address <= s2.broadcast_address): yield s1 s1, s2 = s2.subnets() else: # If we got here, there's a bug somewhere. raise AssertionError('Error performing exclusion: ' 's1: %s s2: %s other: %s' % (s1, s2, other)) if s1 == other: yield s2 elif s2 == other: yield s1 else: # If we got here, there's a bug somewhere. raise AssertionError('Error performing exclusion: ' 's1: %s s2: %s other: %s' % (s1, s2, other)) def compare_networks(self, other): """Compare two IP objects. This is only concerned about the comparison of the integer representation of the network addresses. This means that the host bits aren't considered at all in this method. If you want to compare host bits, you can easily enough do a 'HostA._ip < HostB._ip' Args: other: An IP object. Returns: If the IP versions of self and other are the same, returns: -1 if self < other: eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25') IPv6Network('2001:db8::1000/124') < IPv6Network('2001:db8::2000/124') 0 if self == other eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24') IPv6Network('2001:db8::1000/124') == IPv6Network('2001:db8::1000/124') 1 if self > other eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25') IPv6Network('2001:db8::2000/124') > IPv6Network('2001:db8::1000/124') Raises: TypeError if the IP versions are different. """ # does this need to raise a ValueError? if self._version != other._version: raise TypeError('%s and %s are not of the same type' % ( self, other)) # self._version == other._version below here: if self.network_address < other.network_address: return -1 if self.network_address > other.network_address: return 1 # self.network_address == other.network_address below here: if self.netmask < other.netmask: return -1 if self.netmask > other.netmask: return 1 return 0 def _get_networks_key(self): """Network-only key function. Returns an object that identifies this address' network and netmask. This function is a suitable "key" argument for sorted() and list.sort(). """ return (self._version, self.network_address, self.netmask) def subnets(self, prefixlen_diff=1, new_prefix=None): """The subnets which join to make the current subnet. In the case that self contains only one IP (self._prefixlen == 32 for IPv4 or self._prefixlen == 128 for IPv6), yield an iterator with just ourself. Args: prefixlen_diff: An integer, the amount the prefix length should be increased by. This should not be set if new_prefix is also set. new_prefix: The desired new prefix length. This must be a larger number (smaller prefix) than the existing prefix. This should not be set if prefixlen_diff is also set. Returns: An iterator of IPv(4|6) objects. Raises: ValueError: The prefixlen_diff is too small or too large. OR prefixlen_diff and new_prefix are both set or new_prefix is a smaller number than the current prefix (smaller number means a larger network) """ if self._prefixlen == self._max_prefixlen: yield self return if new_prefix is not None: if new_prefix < self._prefixlen: raise ValueError('new prefix must be longer') if prefixlen_diff != 1: raise ValueError('cannot set prefixlen_diff and new_prefix') prefixlen_diff = new_prefix - self._prefixlen if prefixlen_diff < 0: raise ValueError('prefix length diff must be > 0') new_prefixlen = self._prefixlen + prefixlen_diff if new_prefixlen > self._max_prefixlen: raise ValueError( 'prefix length diff %d is invalid for netblock %s' % ( new_prefixlen, self)) first = self.__class__('%s/%s' % (self.network_address, self._prefixlen + prefixlen_diff)) yield first current = first while True: broadcast = current.broadcast_address if broadcast == self.broadcast_address: return new_addr = self._address_class(int(broadcast) + 1) current = self.__class__('%s/%s' % (new_addr, new_prefixlen)) yield current @property def is_multicast(self): """Test if the address is reserved for multicast use. Returns: A boolean, True if the address is a multicast address. See RFC 2373 2.7 for details. """ return (self.network_address.is_multicast and self.broadcast_address.is_multicast) @property def is_reserved(self): """Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within one of the reserved IPv6 Network ranges. """ return (self.network_address.is_reserved and self.broadcast_address.is_reserved) @property def is_link_local(self): """Test if the address is reserved for link-local. Returns: A boolean, True if the address is reserved per RFC 4291. """ return (self.network_address.is_link_local and self.broadcast_address.is_link_local) @property def is_private(self): """Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per iana-ipv4-special-registry or iana-ipv6-special-registry. """ return (self.network_address.is_private and self.broadcast_address.is_private) @property def is_global(self): """Test if this address is allocated for public networks. Returns: A boolean, True if the address is not reserved per iana-ipv4-special-registry or iana-ipv6-special-registry. """ return not self.is_private @property def is_unspecified(self): """Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in RFC 2373 2.5.2. """ return (self.network_address.is_unspecified and self.broadcast_address.is_unspecified) @property def is_loopback(self): """Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback address as defined in RFC 2373 2.5.3. """ return (self.network_address.is_loopback and self.broadcast_address.is_loopback)
saltstack/salt
salt/ext/ipaddress.py
_BaseV4._ip_int_from_string
python
def _ip_int_from_string(self, ip_str): if not ip_str: raise AddressValueError('Address cannot be empty') octets = ip_str.split('.') if len(octets) != 4: raise AddressValueError("Expected 4 octets in %r" % ip_str) try: return _int_from_bytes(map(self._parse_octet, octets), 'big') except ValueError as exc: raise AddressValueError("%s in %r" % (exc, ip_str))
Turn the given IP string into an integer for comparison. Args: ip_str: A string, the IP ip_str. Returns: The IP ip_str as an integer. Raises: AddressValueError: if ip_str isn't a valid IPv4 Address.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/ext/ipaddress.py#L1176-L1199
null
class _BaseV4(object): """Base IPv4 object. The following methods are used by IPv4 objects in both single IP addresses and networks. """ # Equivalent to 255.255.255.255 or 32 bits of 1's. _ALL_ONES = (2**IPV4LENGTH) - 1 _DECIMAL_DIGITS = frozenset('0123456789') # the valid octets for host and netmasks. only useful for IPv4. _valid_mask_octets = frozenset((255, 254, 252, 248, 240, 224, 192, 128, 0)) def __init__(self, address): self._version = 4 self._max_prefixlen = IPV4LENGTH def _explode_shorthand_ip_string(self): return str(self) def _parse_octet(self, octet_str): """Convert a decimal octet into an integer. Args: octet_str: A string, the number to parse. Returns: The octet as an integer. Raises: ValueError: if the octet isn't strictly a decimal from [0..255]. """ if not octet_str: raise ValueError("Empty octet not permitted") # Whitelist the characters, since int() allows a lot of bizarre stuff. if not self._DECIMAL_DIGITS.issuperset(octet_str): msg = "Only decimal digits permitted in %r" raise ValueError(msg % octet_str) # We do the length check second, since the invalid character error # is likely to be more informative for the user if len(octet_str) > 3: msg = "At most 3 characters permitted in %r" raise ValueError(msg % octet_str) # Convert to integer (we know digits are legal) octet_int = int(octet_str, 10) # Any octets that look like they *might* be written in octal, # and which don't look exactly the same in both octal and # decimal are rejected as ambiguous if octet_int > 7 and octet_str[0] == '0': msg = "Ambiguous (octal/decimal) value in %r not permitted" raise ValueError(msg % octet_str) if octet_int > 255: raise ValueError("Octet %d (> 255) not permitted" % octet_int) return octet_int def _string_from_ip_int(self, ip_int): """Turns a 32-bit integer into dotted decimal notation. Args: ip_int: An integer, the IP address. Returns: The IP address as a string in dotted decimal notation. """ return '.'.join(map(str, _int_to_bytes(ip_int, 4, 'big'))) def _is_valid_netmask(self, netmask): """Verify that the netmask is valid. Args: netmask: A string, either a prefix or dotted decimal netmask. Returns: A boolean, True if the prefix represents a valid IPv4 netmask. """ mask = netmask.split('.') if len(mask) == 4: try: for x in mask: if int(x) not in self._valid_mask_octets: return False except ValueError: # Found something that isn't an integer or isn't valid return False for idx, y in enumerate(mask): if idx > 0 and y > mask[idx - 1]: return False return True try: netmask = int(netmask) except ValueError: return False return 0 <= netmask <= self._max_prefixlen def _is_hostmask(self, ip_str): """Test if the IP string is a hostmask (rather than a netmask). Args: ip_str: A string, the potential hostmask. Returns: A boolean, True if the IP string is a hostmask. """ bits = ip_str.split('.') try: parts = [x for x in map(int, bits) if x in self._valid_mask_octets] except ValueError: return False if len(parts) != len(bits): return False if parts[0] < parts[-1]: return True return False def _reverse_pointer(self): """Return the reverse DNS pointer name for the IPv4 address. This implements the method described in RFC1035 3.5. """ reverse_octets = str(self).split('.')[::-1] return '.'.join(reverse_octets) + '.in-addr.arpa' @property def max_prefixlen(self): return self._max_prefixlen @property def version(self): return self._version
saltstack/salt
salt/ext/ipaddress.py
_BaseV4._parse_octet
python
def _parse_octet(self, octet_str): if not octet_str: raise ValueError("Empty octet not permitted") # Whitelist the characters, since int() allows a lot of bizarre stuff. if not self._DECIMAL_DIGITS.issuperset(octet_str): msg = "Only decimal digits permitted in %r" raise ValueError(msg % octet_str) # We do the length check second, since the invalid character error # is likely to be more informative for the user if len(octet_str) > 3: msg = "At most 3 characters permitted in %r" raise ValueError(msg % octet_str) # Convert to integer (we know digits are legal) octet_int = int(octet_str, 10) # Any octets that look like they *might* be written in octal, # and which don't look exactly the same in both octal and # decimal are rejected as ambiguous if octet_int > 7 and octet_str[0] == '0': msg = "Ambiguous (octal/decimal) value in %r not permitted" raise ValueError(msg % octet_str) if octet_int > 255: raise ValueError("Octet %d (> 255) not permitted" % octet_int) return octet_int
Convert a decimal octet into an integer. Args: octet_str: A string, the number to parse. Returns: The octet as an integer. Raises: ValueError: if the octet isn't strictly a decimal from [0..255].
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/ext/ipaddress.py#L1201-L1235
null
class _BaseV4(object): """Base IPv4 object. The following methods are used by IPv4 objects in both single IP addresses and networks. """ # Equivalent to 255.255.255.255 or 32 bits of 1's. _ALL_ONES = (2**IPV4LENGTH) - 1 _DECIMAL_DIGITS = frozenset('0123456789') # the valid octets for host and netmasks. only useful for IPv4. _valid_mask_octets = frozenset((255, 254, 252, 248, 240, 224, 192, 128, 0)) def __init__(self, address): self._version = 4 self._max_prefixlen = IPV4LENGTH def _explode_shorthand_ip_string(self): return str(self) def _ip_int_from_string(self, ip_str): """Turn the given IP string into an integer for comparison. Args: ip_str: A string, the IP ip_str. Returns: The IP ip_str as an integer. Raises: AddressValueError: if ip_str isn't a valid IPv4 Address. """ if not ip_str: raise AddressValueError('Address cannot be empty') octets = ip_str.split('.') if len(octets) != 4: raise AddressValueError("Expected 4 octets in %r" % ip_str) try: return _int_from_bytes(map(self._parse_octet, octets), 'big') except ValueError as exc: raise AddressValueError("%s in %r" % (exc, ip_str)) def _string_from_ip_int(self, ip_int): """Turns a 32-bit integer into dotted decimal notation. Args: ip_int: An integer, the IP address. Returns: The IP address as a string in dotted decimal notation. """ return '.'.join(map(str, _int_to_bytes(ip_int, 4, 'big'))) def _is_valid_netmask(self, netmask): """Verify that the netmask is valid. Args: netmask: A string, either a prefix or dotted decimal netmask. Returns: A boolean, True if the prefix represents a valid IPv4 netmask. """ mask = netmask.split('.') if len(mask) == 4: try: for x in mask: if int(x) not in self._valid_mask_octets: return False except ValueError: # Found something that isn't an integer or isn't valid return False for idx, y in enumerate(mask): if idx > 0 and y > mask[idx - 1]: return False return True try: netmask = int(netmask) except ValueError: return False return 0 <= netmask <= self._max_prefixlen def _is_hostmask(self, ip_str): """Test if the IP string is a hostmask (rather than a netmask). Args: ip_str: A string, the potential hostmask. Returns: A boolean, True if the IP string is a hostmask. """ bits = ip_str.split('.') try: parts = [x for x in map(int, bits) if x in self._valid_mask_octets] except ValueError: return False if len(parts) != len(bits): return False if parts[0] < parts[-1]: return True return False def _reverse_pointer(self): """Return the reverse DNS pointer name for the IPv4 address. This implements the method described in RFC1035 3.5. """ reverse_octets = str(self).split('.')[::-1] return '.'.join(reverse_octets) + '.in-addr.arpa' @property def max_prefixlen(self): return self._max_prefixlen @property def version(self): return self._version
saltstack/salt
salt/ext/ipaddress.py
_BaseV4._is_valid_netmask
python
def _is_valid_netmask(self, netmask): mask = netmask.split('.') if len(mask) == 4: try: for x in mask: if int(x) not in self._valid_mask_octets: return False except ValueError: # Found something that isn't an integer or isn't valid return False for idx, y in enumerate(mask): if idx > 0 and y > mask[idx - 1]: return False return True try: netmask = int(netmask) except ValueError: return False return 0 <= netmask <= self._max_prefixlen
Verify that the netmask is valid. Args: netmask: A string, either a prefix or dotted decimal netmask. Returns: A boolean, True if the prefix represents a valid IPv4 netmask.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/ext/ipaddress.py#L1249-L1278
null
class _BaseV4(object): """Base IPv4 object. The following methods are used by IPv4 objects in both single IP addresses and networks. """ # Equivalent to 255.255.255.255 or 32 bits of 1's. _ALL_ONES = (2**IPV4LENGTH) - 1 _DECIMAL_DIGITS = frozenset('0123456789') # the valid octets for host and netmasks. only useful for IPv4. _valid_mask_octets = frozenset((255, 254, 252, 248, 240, 224, 192, 128, 0)) def __init__(self, address): self._version = 4 self._max_prefixlen = IPV4LENGTH def _explode_shorthand_ip_string(self): return str(self) def _ip_int_from_string(self, ip_str): """Turn the given IP string into an integer for comparison. Args: ip_str: A string, the IP ip_str. Returns: The IP ip_str as an integer. Raises: AddressValueError: if ip_str isn't a valid IPv4 Address. """ if not ip_str: raise AddressValueError('Address cannot be empty') octets = ip_str.split('.') if len(octets) != 4: raise AddressValueError("Expected 4 octets in %r" % ip_str) try: return _int_from_bytes(map(self._parse_octet, octets), 'big') except ValueError as exc: raise AddressValueError("%s in %r" % (exc, ip_str)) def _parse_octet(self, octet_str): """Convert a decimal octet into an integer. Args: octet_str: A string, the number to parse. Returns: The octet as an integer. Raises: ValueError: if the octet isn't strictly a decimal from [0..255]. """ if not octet_str: raise ValueError("Empty octet not permitted") # Whitelist the characters, since int() allows a lot of bizarre stuff. if not self._DECIMAL_DIGITS.issuperset(octet_str): msg = "Only decimal digits permitted in %r" raise ValueError(msg % octet_str) # We do the length check second, since the invalid character error # is likely to be more informative for the user if len(octet_str) > 3: msg = "At most 3 characters permitted in %r" raise ValueError(msg % octet_str) # Convert to integer (we know digits are legal) octet_int = int(octet_str, 10) # Any octets that look like they *might* be written in octal, # and which don't look exactly the same in both octal and # decimal are rejected as ambiguous if octet_int > 7 and octet_str[0] == '0': msg = "Ambiguous (octal/decimal) value in %r not permitted" raise ValueError(msg % octet_str) if octet_int > 255: raise ValueError("Octet %d (> 255) not permitted" % octet_int) return octet_int def _string_from_ip_int(self, ip_int): """Turns a 32-bit integer into dotted decimal notation. Args: ip_int: An integer, the IP address. Returns: The IP address as a string in dotted decimal notation. """ return '.'.join(map(str, _int_to_bytes(ip_int, 4, 'big'))) def _is_hostmask(self, ip_str): """Test if the IP string is a hostmask (rather than a netmask). Args: ip_str: A string, the potential hostmask. Returns: A boolean, True if the IP string is a hostmask. """ bits = ip_str.split('.') try: parts = [x for x in map(int, bits) if x in self._valid_mask_octets] except ValueError: return False if len(parts) != len(bits): return False if parts[0] < parts[-1]: return True return False def _reverse_pointer(self): """Return the reverse DNS pointer name for the IPv4 address. This implements the method described in RFC1035 3.5. """ reverse_octets = str(self).split('.')[::-1] return '.'.join(reverse_octets) + '.in-addr.arpa' @property def max_prefixlen(self): return self._max_prefixlen @property def version(self): return self._version
saltstack/salt
salt/ext/ipaddress.py
IPv4Address.is_private
python
def is_private(self): return (self in IPv4Network('0.0.0.0/8') or self in IPv4Network('10.0.0.0/8') or self in IPv4Network('127.0.0.0/8') or self in IPv4Network('169.254.0.0/16') or self in IPv4Network('172.16.0.0/12') or self in IPv4Network('192.0.0.0/29') or self in IPv4Network('192.0.0.170/31') or self in IPv4Network('192.0.2.0/24') or self in IPv4Network('192.168.0.0/16') or self in IPv4Network('198.18.0.0/15') or self in IPv4Network('198.51.100.0/24') or self in IPv4Network('203.0.113.0/24') or self in IPv4Network('240.0.0.0/4') or self in IPv4Network('255.255.255.255/32'))
Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per iana-ipv4-special-registry.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/ext/ipaddress.py#L1377-L1398
null
class IPv4Address(_BaseV4, _BaseAddress): """Represent and manipulate single IPv4 Addresses.""" def __init__(self, address): """ Args: address: A string or integer representing the IP Additionally, an integer can be passed, so IPv4Address('192.0.2.1') == IPv4Address(3221225985). or, more generally IPv4Address(int(IPv4Address('192.0.2.1'))) == IPv4Address('192.0.2.1') Raises: AddressValueError: If ipaddress isn't a valid IPv4 address. """ _BaseAddress.__init__(self, address) _BaseV4.__init__(self, address) # Efficient constructor from integer. if isinstance(address, int): self._check_int_address(address) self._ip = address return # Constructing from a packed address if isinstance(address, bytes): self._check_packed_address(address, 4) self._ip = _int_from_bytes(address, 'big') return # Assume input argument to be string or any object representation # which converts into a formatted IP string. addr_str = str(address) self._ip = self._ip_int_from_string(addr_str) @property def packed(self): """The binary representation of this address.""" return v4_int_to_packed(self._ip) @property def is_reserved(self): """Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within the reserved IPv4 Network range. """ reserved_network = IPv4Network('240.0.0.0/4') return self in reserved_network @property @property def is_multicast(self): """Test if the address is reserved for multicast use. Returns: A boolean, True if the address is multicast. See RFC 3171 for details. """ multicast_network = IPv4Network('224.0.0.0/4') return self in multicast_network @property def is_unspecified(self): """Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in RFC 5735 3. """ unspecified_address = IPv4Address('0.0.0.0') return self == unspecified_address @property def is_loopback(self): """Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback per RFC 3330. """ loopback_network = IPv4Network('127.0.0.0/8') return self in loopback_network @property def is_link_local(self): """Test if the address is reserved for link-local. Returns: A boolean, True if the address is link-local per RFC 3927. """ linklocal_network = IPv4Network('169.254.0.0/16') return self in linklocal_network
saltstack/salt
salt/ext/ipaddress.py
_BaseV6._explode_shorthand_ip_string
python
def _explode_shorthand_ip_string(self): if isinstance(self, IPv6Network): ip_str = str(self.network_address) elif isinstance(self, IPv6Interface): ip_str = str(self.ip) else: ip_str = str(self) ip_int = self._ip_int_from_string(ip_str) hex_str = '%032x' % ip_int parts = [hex_str[x:x+4] for x in range(0, 32, 4)] if isinstance(self, (_BaseNetwork, IPv6Interface)): return '%s/%d' % (':'.join(parts), self._prefixlen) return ':'.join(parts)
Expand a shortened IPv6 address. Args: ip_str: A string, the IPv6 address. Returns: A string, the expanded IPv6 address.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/ext/ipaddress.py#L1847-L1869
null
class _BaseV6(object): """Base IPv6 object. The following methods are used by IPv6 objects in both single IP addresses and networks. """ _ALL_ONES = (2**IPV6LENGTH) - 1 _HEXTET_COUNT = 8 _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef') def __init__(self, address): self._version = 6 self._max_prefixlen = IPV6LENGTH def _ip_int_from_string(self, ip_str): """Turn an IPv6 ip_str into an integer. Args: ip_str: A string, the IPv6 ip_str. Returns: An int, the IPv6 address Raises: AddressValueError: if ip_str isn't a valid IPv6 Address. """ if not ip_str: raise AddressValueError('Address cannot be empty') parts = ip_str.split(':') # An IPv6 address needs at least 2 colons (3 parts). _min_parts = 3 if len(parts) < _min_parts: msg = "At least %d parts expected in %r" % (_min_parts, ip_str) raise AddressValueError(msg) # If the address has an IPv4-style suffix, convert it to hexadecimal. if '.' in parts[-1]: try: ipv4_int = IPv4Address(parts.pop())._ip except AddressValueError as exc: raise AddressValueError("%s in %r" % (exc, ip_str)) parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF)) parts.append('%x' % (ipv4_int & 0xFFFF)) # An IPv6 address can't have more than 8 colons (9 parts). # The extra colon comes from using the "::" notation for a single # leading or trailing zero part. _max_parts = self._HEXTET_COUNT + 1 if len(parts) > _max_parts: msg = "At most %d colons permitted in %r" % (_max_parts-1, ip_str) raise AddressValueError(msg) # Disregarding the endpoints, find '::' with nothing in between. # This indicates that a run of zeroes has been skipped. skip_index = None for i in range(1, len(parts) - 1): if not parts[i]: if skip_index is not None: # Can't have more than one '::' msg = "At most one '::' permitted in %r" % ip_str raise AddressValueError(msg) skip_index = i # parts_hi is the number of parts to copy from above/before the '::' # parts_lo is the number of parts to copy from below/after the '::' if skip_index is not None: # If we found a '::', then check if it also covers the endpoints. parts_hi = skip_index parts_lo = len(parts) - skip_index - 1 if not parts[0]: parts_hi -= 1 if parts_hi: msg = "Leading ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # ^: requires ^:: if not parts[-1]: parts_lo -= 1 if parts_lo: msg = "Trailing ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # :$ requires ::$ parts_skipped = self._HEXTET_COUNT - (parts_hi + parts_lo) if parts_skipped < 1: msg = "Expected at most %d other parts with '::' in %r" raise AddressValueError(msg % (self._HEXTET_COUNT-1, ip_str)) else: # Otherwise, allocate the entire address to parts_hi. The # endpoints could still be empty, but _parse_hextet() will check # for that. if len(parts) != self._HEXTET_COUNT: msg = "Exactly %d parts expected without '::' in %r" raise AddressValueError(msg % (self._HEXTET_COUNT, ip_str)) if not parts[0]: msg = "Leading ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # ^: requires ^:: if not parts[-1]: msg = "Trailing ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # :$ requires ::$ parts_hi = len(parts) parts_lo = 0 parts_skipped = 0 try: # Now, parse the hextets into a 128-bit integer. ip_int = 0 for i in range(parts_hi): ip_int <<= 16 ip_int |= self._parse_hextet(parts[i]) ip_int <<= 16 * parts_skipped for i in range(-parts_lo, 0): ip_int <<= 16 ip_int |= self._parse_hextet(parts[i]) return ip_int except ValueError as exc: raise AddressValueError("%s in %r" % (exc, ip_str)) def _parse_hextet(self, hextet_str): """Convert an IPv6 hextet string into an integer. Args: hextet_str: A string, the number to parse. Returns: The hextet as an integer. Raises: ValueError: if the input isn't strictly a hex number from [0..FFFF]. """ # Whitelist the characters, since int() allows a lot of bizarre stuff. if not self._HEX_DIGITS.issuperset(hextet_str): raise ValueError("Only hex digits permitted in %r" % hextet_str) # We do the length check second, since the invalid character error # is likely to be more informative for the user if len(hextet_str) > 4: msg = "At most 4 characters permitted in %r" raise ValueError(msg % hextet_str) # Length check means we can skip checking the integer value return int(hextet_str, 16) def _compress_hextets(self, hextets): """Compresses a list of hextets. Compresses a list of strings, replacing the longest continuous sequence of "0" in the list with "" and adding empty strings at the beginning or at the end of the string such that subsequently calling ":".join(hextets) will produce the compressed version of the IPv6 address. Args: hextets: A list of strings, the hextets to compress. Returns: A list of strings. """ best_doublecolon_start = -1 best_doublecolon_len = 0 doublecolon_start = -1 doublecolon_len = 0 for index, hextet in enumerate(hextets): if hextet == '0': doublecolon_len += 1 if doublecolon_start == -1: # Start of a sequence of zeros. doublecolon_start = index if doublecolon_len > best_doublecolon_len: # This is the longest sequence of zeros so far. best_doublecolon_len = doublecolon_len best_doublecolon_start = doublecolon_start else: doublecolon_len = 0 doublecolon_start = -1 if best_doublecolon_len > 1: best_doublecolon_end = (best_doublecolon_start + best_doublecolon_len) # For zeros at the end of the address. if best_doublecolon_end == len(hextets): hextets += [''] hextets[best_doublecolon_start:best_doublecolon_end] = [''] # For zeros at the beginning of the address. if best_doublecolon_start == 0: hextets = [''] + hextets return hextets def _string_from_ip_int(self, ip_int=None): """Turns a 128-bit integer into hexadecimal notation. Args: ip_int: An integer, the IP address. Returns: A string, the hexadecimal representation of the address. Raises: ValueError: The address is bigger than 128 bits of all ones. """ if ip_int is None: ip_int = int(self._ip) if ip_int > self._ALL_ONES: raise ValueError('IPv6 address is too large') hex_str = '%032x' % ip_int hextets = ['%x' % int(hex_str[x:x+4], 16) for x in range(0, 32, 4)] hextets = self._compress_hextets(hextets) return ':'.join(hextets) def _reverse_pointer(self): """Return the reverse DNS pointer name for the IPv6 address. This implements the method described in RFC3596 2.5. """ reverse_chars = self.exploded[::-1].replace(':', '') return '.'.join(reverse_chars) + '.ip6.arpa' @property def max_prefixlen(self): return self._max_prefixlen @property def version(self): return self._version